@nibssplc/cams-sdk 0.0.1-beta.35 โ†’ 0.0.1-beta.37

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
@@ -1,601 +1,155 @@
1
- # NIBSS CAMS SDK
1
+ # @nibssplc/cams-sdk
2
2
 
3
- Central Authentication Management Service (CAMS) SDK for popup-based authentication with Azure AD + custom 2FA.
3
+ Central Authentication Management Service (CAMS) SDK for popup-based authentication with Azure AD and custom 2FA.
4
4
 
5
- ## Features
6
-
7
- - ๐Ÿ” Secure popup-based authentication
8
- - ๐Ÿ›ก๏ธ Origin validation and security controls
9
- - โฑ๏ธ Configurable auth and idle timeouts with retry logic
10
- - ๐Ÿ”„ Automatic token management with JWT expiration checking
11
- - ๐Ÿ“ฑ Session management with event callbacks
12
- - ๐Ÿงช Comprehensive TypeScript support with Zod validation
13
- - โš›๏ธ React hooks and components for seamless integration
14
- - ๐Ÿ”ต Azure AD MSAL integration support
15
- - โœ… Full test coverage
16
-
17
- ## Packages
5
+ ## Installation
18
6
 
19
- ### Core SDK
20
7
  ```bash
21
8
  npm install @nibssplc/cams-sdk
22
9
  ```
23
10
 
24
- ### React Integration
25
- ```bash
26
- npm install @nibssplc/cams-sdk-react
27
- ```
28
-
29
- ## Quick Start
11
+ ## Features
30
12
 
31
- ### Core SDK Usage
13
+ - ๐Ÿ” Popup-based authentication flow
14
+ - ๐Ÿ›ก๏ธ Built-in 2FA/MFA support
15
+ - ๐Ÿ“ฆ Session management with automatic timeout
16
+ - ๐Ÿ”„ Retry mechanism for failed authentications
17
+ - ๐ŸŽฏ TypeScript support
18
+ - โœ… Input validation with Zod
19
+ - ๐Ÿชต Debug logging capabilities
32
20
 
33
- #### Basic Popup Authentication
21
+ ## Quick Start
34
22
 
35
23
  ```typescript
36
- import { openCAMSPopUpLogin, CAMSConfig } from '@nibssplc/cams-sdk';
24
+ import { authenticateWithCAMS, CAMSConfig } from '@nibssplc/cams-sdk';
37
25
 
38
26
  const config: CAMSConfig = {
39
- camsUrl: 'https://your-cams-instance.com/auth',
40
- messageOrigin: 'your-cams-instance.com',
27
+ camsUrl: 'https://your-cams-url.com',
28
+ messageOrigin: 'https://your-cams-url.com',
41
29
  windowWidth: 500,
42
30
  windowHeight: 600,
43
- authTimeout: 300000, // 5 minutes auth timeout
44
- idleTimeout: 120000, // 2 minutes idle timeout
45
- debug: true, // Enable debug logging
31
+ authTimeout: 300000, // 5 minutes
32
+ debug: true
46
33
  };
47
34
 
35
+ const appCode = 'your-app-guid';
36
+
48
37
  try {
49
- const profile = await openCAMSPopUpLogin(config);
50
- console.log('Authentication successful:', profile);
38
+ const result = await authenticateWithCAMS(appCode, config);
39
+ console.log('Authenticated:', result);
51
40
  } catch (error) {
52
41
  console.error('Authentication failed:', error);
53
42
  }
54
43
  ```
55
44
 
56
- #### Session Management
45
+ ## Configuration
57
46
 
58
- ```typescript
59
- import { CAMSSessionManager } from '@nibssplc/cams-sdk';
47
+ ### CAMSConfig
60
48
 
61
- const session = new CAMSSessionManager(localStorage, 'my_app', {
62
- onAuthSuccess: (response) => console.log('Login successful'),
63
- onAuthError: (error) => console.error('Login failed:', error),
64
- onTokenExpired: () => console.log('Token expired'),
65
- });
49
+ | Property | Type | Required | Default | Description |
50
+ |----------|------|----------|---------|-------------|
51
+ | `camsUrl` | string | Yes | - | CAMS authentication URL |
52
+ | `messageOrigin` | string | Yes | - | Expected message origin for security |
53
+ | `windowWidth` | number | Yes | - | Popup window width |
54
+ | `windowHeight` | number | Yes | - | Popup window height |
55
+ | `authTimeout` | number | No | 300000 | Authentication timeout (ms) |
56
+ | `idleTimeout` | number | No | 60000 | Idle timeout (ms) |
57
+ | `storageKey` | string | No | 'cams-session' | Custom storage key |
58
+ | `retryAttempts` | number | No | 0 | Auto-retry on failure |
59
+ | `debug` | boolean | No | false | Enable debug logging |
66
60
 
67
- // Login
68
- try {
69
- await session.login(config);
70
-
71
- // Check authentication status
72
- if (session.isAuthenticated()) {
73
- const token = session.getAccessToken();
74
- const profile = await session.getProfile();
75
- }
76
- } catch (error) {
77
- // Handle authentication error
78
- }
79
-
80
- // Logout
81
- await session.logout();
82
- ```
61
+ ## API Reference
83
62
 
84
- ### React Integration
63
+ ### authenticateWithCAMS
85
64
 
86
- #### Basic React Hook
65
+ Main authentication function that opens a popup and handles the authentication flow.
87
66
 
88
67
  ```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
- }
68
+ function authenticateWithCAMS(
69
+ appCode: string,
70
+ config: CAMSConfig
71
+ ): Promise<AuthResult>
122
72
  ```
123
73
 
124
- #### React Provider Pattern
74
+ ### Session Management
125
75
 
126
76
  ```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
- }
77
+ import { SessionManager } from '@nibssplc/cams-sdk';
137
78
 
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
- ```
79
+ const sessionManager = new SessionManager(config);
165
80
 
166
- #### Unified Provider (Recommended)
81
+ // Check if session is valid
82
+ const isValid = sessionManager.isSessionValid();
167
83
 
168
- ```typescript
169
- import { UnifiedCAMSProvider, useCAMSContext } from '@nibssplc/cams-sdk-react';
170
-
171
- // Regular CAMS Authentication
172
- function App() {
173
- return (
174
- <UnifiedCAMSProvider
175
- mode="REGULAR"
176
- appCode="12345678-1234-1234-1234-123456789abc"
177
- storageKey="CAMS-AUTH-SDK"
178
- >
179
- <LoginComponent />
180
- </UnifiedCAMSProvider>
181
- );
182
- }
84
+ // Get session data
85
+ const session = sessionManager.getSession();
183
86
 
184
- // Azure AD MSAL Authentication
185
- function App() {
186
- return (
187
- <UnifiedCAMSProvider
188
- mode="MSAL"
189
- appCode="12345678-1234-1234-1234-123456789abc"
190
- msalConfig={msalConfig}
191
- mfaUrl="/auth/multi-factor"
192
- storageKey="CAMS-MSAL-AUTH-SDK"
193
- >
194
- <LoginComponent />
195
- </UnifiedCAMSProvider>
196
- );
197
- }
87
+ // Clear session
88
+ sessionManager.clearSession();
198
89
  ```
199
90
 
200
- #### Azure AD MSAL Integration
91
+ ### MFA Authentication
201
92
 
202
93
  ```typescript
203
- import { CAMSMSALProvider, useCAMSMSALContext } from '@nibssplc/cams-sdk-react';
204
- import { Configuration } from '@azure/msal-browser';
205
-
206
- const msalConfig: Configuration = {
207
- auth: {
208
- clientId: 'your-azure-client-id',
209
- authority: 'https://login.microsoftonline.com/your-tenant-id',
210
- redirectUri: window.location.origin,
211
- },
212
- };
94
+ import { authenticateWithMFA } from '@nibssplc/cams-sdk';
213
95
 
214
- // App.tsx
215
- function App() {
216
- return (
217
- <CAMSMSALProvider
218
- msalConfig={msalConfig}
219
- mfaUrl="/auth/multi-factor"
220
- storageKey="CAMS-MSAL-AUTH-SDK"
221
- >
222
- <LoginComponent />
223
- </CAMSMSALProvider>
224
- );
225
- }
226
-
227
- // LoginComponent.tsx
228
- function LoginComponent() {
229
- const { login, logout, isAuthenticated, isLoading, userProfile } = useCAMSMSALContext();
230
-
231
- if (isLoading) return <div>Loading...</div>;
232
-
233
- return (
234
- <div>
235
- {isAuthenticated ? (
236
- <div>
237
- <p>Welcome, {userProfile?.name}!</p>
238
- <button onClick={logout}>Logout</button>
239
- </div>
240
- ) : (
241
- <button onClick={login}>Login with Azure AD</button>
242
- )}
243
- </div>
244
- );
245
- }
246
- ```
247
-
248
- ## Configuration Options
249
-
250
- ### Core SDK Configuration
251
-
252
- ```typescript
253
- interface CAMSConfig {
254
- camsUrl: string; // CAMS authentication URL
255
- messageOrigin: string; // Expected message origin (hostname)
256
- windowWidth: number; // Popup window width
257
- windowHeight: number; // Popup window height
258
- authTimeout?: number; // Auth timeout in ms (default: 300000)
259
- idleTimeout?: number; // Idle timeout in ms (default: 120000)
260
- storageKey?: string; // Custom storage key
261
- retryAttempts?: number; // Auto-retry on failure (default: 0)
262
- debug?: boolean; // Enable debug logging (default: false)
263
- }
264
- ```
265
-
266
- ### React Hook Options
267
-
268
- ```typescript
269
- interface UseCAMSAuthOptions {
270
- appCode: string; // Application code
271
- storageKey?: string; // Storage key (default: "CAMS-AUTH-SDK")
272
- onAuthSuccess?: (token: string) => void; // Success callback
273
- onAuthError?: (error: CAMSError) => void; // Error callback
274
- onTokenExpired?: () => void; // Token expiry callback
275
- }
276
-
277
- interface UseCAMSMSALAuthOptions {
278
- mfaUrl?: string; // MFA URL (default: "/auth/multi-factor")
279
- storageKey?: string; // Storage key (default: "CAMS-MSAL-AUTH-SDK")
280
- scopes?: string[]; // MSAL scopes (default: ["openid", "profile", "email"])
281
- prompt?: string; // MSAL prompt (default: "login")
282
- allowedOrigins?: string[]; // Allowed message origins
283
- messageOrigin?: string; // Expected message origin
284
- onAuthSuccess?: (token: string) => void; // Success callback
285
- onAuthError?: (error: CAMSError) => void; // Error callback
286
- }
96
+ const result = await authenticateWithMFA({
97
+ appCode: 'your-app-guid',
98
+ MFAEndpoint: 'https://your-mfa-endpoint.com',
99
+ accessToken: 'user-access-token'
100
+ });
287
101
  ```
288
102
 
289
103
  ## Error Handling
290
104
 
291
- The SDK provides typed errors for better error handling:
292
-
293
105
  ```typescript
294
106
  import { CAMSError, CAMSErrorType } from '@nibssplc/cams-sdk';
295
107
 
296
108
  try {
297
- await session.login(config);
109
+ await authenticateWithCAMS(appCode, config);
298
110
  } catch (error) {
299
111
  if (error instanceof CAMSError) {
300
112
  switch (error.type) {
301
113
  case CAMSErrorType.POPUP_BLOCKED:
302
- // Handle popup blocker
114
+ console.error('Popup was blocked');
303
115
  break;
304
116
  case CAMSErrorType.TIMEOUT:
305
- // Handle timeout
306
- break;
307
- case CAMSErrorType.INVALID_URL:
308
- // Handle invalid URL
309
- break;
310
- case CAMSErrorType.INVALID_ORIGIN:
311
- // Handle invalid message origin
117
+ console.error('Authentication timed out');
312
118
  break;
313
119
  case CAMSErrorType.USER_CANCELLED:
314
- // Handle user cancellation
315
- break;
316
- case CAMSErrorType.MAX_RETRIES_EXCEEDED:
317
- // Handle retry limit exceeded
120
+ console.error('User cancelled authentication');
318
121
  break;
319
- case CAMSErrorType.API_VALIDATION_ERROR:
320
- // Handle API validation errors
321
- break;
322
- }
323
- }
324
- }
325
- ```
326
-
327
- ## Security Features
328
-
329
- - **URL Validation**: Prevents open redirect attacks using Zod schemas
330
- - **Origin Validation**: Validates message origins with subdomain support
331
- - **Token Validation**: JWT parsing with expiration checking
332
- - **Secure Storage**: Configurable storage with automatic cleanup
333
- - **Input Sanitization**: Log injection prevention
334
-
335
- ## API Reference
336
-
337
- ### Core SDK
338
-
339
- #### Session Manager
340
-
341
- ```typescript
342
- new CAMSSessionManager(
343
- storage?: StorageLike | null, // Storage implementation (default: localStorage)
344
- keyPrefix?: string, // Storage key prefix (default: "CAMS-SDK")
345
- events?: CAMSEvents // Event callbacks
346
- )
347
- ```
348
-
349
- **Methods:**
350
- - `login(config: CAMSConfig): Promise<CAMSTokenResponse>` - Authenticate user
351
- - `logout(): Promise<void>` - Clear session
352
- - `isAuthenticated(): boolean` - Check if user is authenticated
353
- - `getAccessToken(): string | null` - Get current token
354
- - `getProfile(): Promise<Profile | null>` - Extract user profile from JWT
355
- - `setToken(token: string): void` - Store token
356
- - `clearToken(): void` - Clear stored token
357
-
358
- #### Popup Window Control
359
-
360
- ```typescript
361
- import { closeWindow } from '@nibssplc/cams-sdk';
362
-
363
- // Manually close active authentication popup
364
- closeWindow();
365
- ```
366
-
367
- **Methods:**
368
- - `closeWindow(): void` - Manually close any active authentication popup window
369
-
370
- ### React Hooks
371
-
372
- #### useCAMSAuth
373
-
374
- ```typescript
375
- const {
376
- login, // (config: CAMSConfig) => Promise<void>
377
- logout, // () => Promise<void>
378
- isAuthenticated, // boolean
379
- isLoading, // boolean
380
- error, // CAMSError | null
381
- token, // string | null
382
- profile, // Profile | null
383
- appCode, // string
384
- storageKey, // string
385
- } = useCAMSAuth(options);
386
- ```
387
-
388
- #### useCAMSMSALAuth
389
-
390
- ```typescript
391
- const {
392
- login, // () => Promise<void>
393
- logout, // () => Promise<void>
394
- isAuthenticated, // boolean
395
- isLoading, // boolean
396
- error, // CAMSError | null
397
- idToken, // string
398
- accessToken, // string
399
- appCode, // string
400
- storageKey, // string
401
- } = useCAMSMSALAuth(options);
402
- ```
403
-
404
- ### React Components
405
-
406
- #### UnifiedCAMSProvider (Recommended)
407
-
408
- Unified provider supporting both regular CAMS and Azure AD MSAL authentication.
409
-
410
- ```typescript
411
- // Regular CAMS Authentication
412
- <UnifiedCAMSProvider
413
- mode="REGULAR"
414
- appCode="12345678-1234-1234-1234-123456789abc" // Valid GUID required
415
- storageKey="CAMS-AUTH"
416
- >
417
- {children}
418
- </UnifiedCAMSProvider>
419
-
420
- // Azure AD MSAL Authentication
421
- <UnifiedCAMSProvider
422
- mode="MSAL"
423
- appCode="12345678-1234-1234-1234-123456789abc" // Valid GUID required
424
- msalConfig={config}
425
- mfaUrl="/auth/mfa"
426
- >
427
- {children}
428
- </UnifiedCAMSProvider>
429
- ```
430
-
431
- #### CAMSProvider (Legacy)
432
-
433
- Provides CAMS authentication context to child components.
434
-
435
- ```typescript
436
- <CAMSProvider appCode="your-app" storageKey="CAMS-AUTH">
437
- {children}
438
- </CAMSProvider>
439
- ```
440
-
441
- #### CAMSMSALProvider (Legacy)
442
-
443
- Provides CAMS + Azure AD MSAL authentication context.
444
-
445
- ```typescript
446
- <CAMSMSALProvider msalConfig={config} mfaUrl="/auth/mfa">
447
- {children}
448
- </CAMSMSALProvider>
449
- ```
450
-
451
- #### ProtectedRoute
452
-
453
- Route component that requires authentication.
454
-
455
- ```typescript
456
- <ProtectedRoute fallback={<LoginPage />}>
457
- <Dashboard />
458
- </ProtectedRoute>
459
- ```
460
-
461
- ## Popup Authentication
462
-
463
- When your popup app also uses the CAMS SDK, special handling is required to prevent conflicts:
464
-
465
- ```typescript
466
- import { useCAMSPopupAuth } from '@nibssplc/cams-sdk-react';
467
-
468
- // In your popup app
469
- function PopupApp() {
470
- const { completeAuth, errorAuth, isPopup } = useCAMSPopupAuth();
471
-
472
- useEffect(() => {
473
- if (isPopup) {
474
- // Your auth logic here
475
- performAuth().then(profile => {
476
- completeAuth({
477
- userProfile: {
478
- name: profile.name,
479
- tokens: { Bearer: profile.token }
480
- }
481
- });
482
- }).catch(errorAuth);
483
- }
484
- }, [isPopup]);
485
-
486
- return <div>Authenticating...</div>;
487
- }
488
- ```
489
-
490
- See [POPUP_AUTH_GUIDE.md](./POPUP_AUTH_GUIDE.md) for detailed implementation guide.
491
-
492
- ## Debugging
493
-
494
- The SDK includes comprehensive logging to aid in debugging:
495
-
496
- ```typescript
497
- import { Logger, LogLevel } from '@nibssplc/cams-sdk';
498
-
499
- // Set global log level
500
- Logger.setLevel(LogLevel.DEBUG);
501
-
502
- // Or enable debug mode in config
503
- const config = {
504
- // ... other config
505
- debug: true // Automatically sets debug level
506
- };
507
- ```
508
-
509
- **Log Levels:**
510
- - `ERROR`: Critical errors only
511
- - `WARN`: Warnings and errors (default)
512
- - `INFO`: General information, warnings, and errors
513
- - `DEBUG`: All logs including detailed flow information
514
-
515
- ## Message Protocol
516
-
517
- The SDK expects specific message formats from the authentication window:
518
-
519
- ### Success Message (Profile)
520
- ```typescript
521
- {
522
- userProfile: {
523
- name: string,
524
- image?: string | null,
525
- tokens: {
526
- Bearer: string
122
+ default:
123
+ console.error('Authentication error:', error.message);
527
124
  }
528
125
  }
529
126
  }
530
127
  ```
531
128
 
532
- ### Failure Message
533
- ```typescript
534
- {
535
- type: "AUTH_FAILURE",
536
- error: string,
537
- errorCode?: string,
538
- errorDetails?: any
539
- }
540
- ```
129
+ ## Types
541
130
 
542
- ### Error Message
543
131
  ```typescript
544
- {
545
- error: string
132
+ export interface Profile {
133
+ email: string;
134
+ name: string;
135
+ // ... other profile fields
546
136
  }
547
- ```
548
137
 
549
- ### Heartbeat (Optional)
550
- ```typescript
551
- {
552
- type: "heartbeat"
138
+ export interface AuthResult {
139
+ success: boolean;
140
+ profile?: Profile;
141
+ token?: string;
553
142
  }
554
143
  ```
555
144
 
556
- ## Development
557
-
558
- ```bash
559
- # Install dependencies
560
- npm install
561
-
562
- # Build core SDK
563
- npm run build
564
-
565
- # Build React package
566
- npm run build:react
145
+ ## React Integration
567
146
 
568
- # Run tests (core)
569
- npm test
147
+ For React applications, use the companion package [@nibssplc/cams-sdk-react](./packages/react/README.md).
570
148
 
571
- # Run tests (React)
572
- npm run test:react
573
-
574
- # Lint
575
- npm run lint
576
-
577
- # Publish all packages
578
- npm run publish:all
579
- ```
580
-
581
- ## Project Structure
149
+ ## License
582
150
 
583
- ```
584
- NIBSS-CAMS-SDK/
585
- โ”œโ”€โ”€ src/ # Core SDK source
586
- โ”‚ โ”œโ”€โ”€ auth.ts # Main authentication logic
587
- โ”‚ โ”œโ”€โ”€ sessionManager.ts # Session management
588
- โ”‚ โ”œโ”€โ”€ types.ts # TypeScript definitions
589
- โ”‚ โ”œโ”€โ”€ validators.ts # Zod schemas
590
- โ”‚ โ””โ”€โ”€ logger.ts # Logging utilities
591
- โ”œโ”€โ”€ packages/
592
- โ”‚ โ””โ”€โ”€ react/ # React integration package
593
- โ”‚ โ””โ”€โ”€ src/
594
- โ”‚ โ”œโ”€โ”€ hooks/ # React hooks
595
- โ”‚ โ””โ”€โ”€ components/ # React components
596
- โ””โ”€โ”€ dist/ # Built packages
597
- ```
151
+ MIT
598
152
 
599
- ## License
153
+ ## Author
600
154
 
601
- MIT ยฉ NIBSS PLC
155
+ NIBSS PLC, Caleb Boluwade
package/dist/auth.d.ts CHANGED
@@ -2,7 +2,5 @@ import { CAMSConfig } from "./types";
2
2
  import { Profile } from "./validators";
3
3
  export declare const generateSecureWindowName: () => string;
4
4
  export declare const isPopupWindow: () => boolean;
5
- export declare const forwardAuthToParent: (data: any, targetOrigin?: string) => void;
6
- export declare const closeWindow: () => void;
7
5
  export declare function validateConfig(config: CAMSConfig): URL;
8
6
  export declare function openCAMSPopUpLogin(config: CAMSConfig): Promise<Profile>;