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

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 DELETED
@@ -1,601 +0,0 @@
1
- # NIBSS CAMS SDK
2
-
3
- Central Authentication Management Service (CAMS) SDK for popup-based authentication with Azure AD + custom 2FA.
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
18
-
19
- ### Core SDK
20
- ```bash
21
- npm install @nibssplc/cams-sdk
22
- ```
23
-
24
- ### React Integration
25
- ```bash
26
- npm install @nibssplc/cams-sdk-react
27
- ```
28
-
29
- ## Quick Start
30
-
31
- ### Core SDK Usage
32
-
33
- #### Basic Popup Authentication
34
-
35
- ```typescript
36
- import { openCAMSPopUpLogin, CAMSConfig } from '@nibssplc/cams-sdk';
37
-
38
- const config: CAMSConfig = {
39
- camsUrl: 'https://your-cams-instance.com/auth',
40
- messageOrigin: 'your-cams-instance.com',
41
- windowWidth: 500,
42
- windowHeight: 600,
43
- authTimeout: 300000, // 5 minutes auth timeout
44
- idleTimeout: 120000, // 2 minutes idle timeout
45
- debug: true, // Enable debug logging
46
- };
47
-
48
- try {
49
- const profile = await openCAMSPopUpLogin(config);
50
- console.log('Authentication successful:', profile);
51
- } catch (error) {
52
- console.error('Authentication failed:', error);
53
- }
54
- ```
55
-
56
- #### Session Management
57
-
58
- ```typescript
59
- import { CAMSSessionManager } from '@nibssplc/cams-sdk';
60
-
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
- });
66
-
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
- ```
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
- #### Unified Provider (Recommended)
167
-
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
- }
183
-
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
- }
198
- ```
199
-
200
- #### Azure AD MSAL Integration
201
-
202
- ```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
- };
213
-
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
- }
287
- ```
288
-
289
- ## Error Handling
290
-
291
- The SDK provides typed errors for better error handling:
292
-
293
- ```typescript
294
- import { CAMSError, CAMSErrorType } from '@nibssplc/cams-sdk';
295
-
296
- try {
297
- await session.login(config);
298
- } catch (error) {
299
- if (error instanceof CAMSError) {
300
- switch (error.type) {
301
- case CAMSErrorType.POPUP_BLOCKED:
302
- // Handle popup blocker
303
- break;
304
- 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
312
- break;
313
- case CAMSErrorType.USER_CANCELLED:
314
- // Handle user cancellation
315
- break;
316
- case CAMSErrorType.MAX_RETRIES_EXCEEDED:
317
- // Handle retry limit exceeded
318
- 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
527
- }
528
- }
529
- }
530
- ```
531
-
532
- ### Failure Message
533
- ```typescript
534
- {
535
- type: "AUTH_FAILURE",
536
- error: string,
537
- errorCode?: string,
538
- errorDetails?: any
539
- }
540
- ```
541
-
542
- ### Error Message
543
- ```typescript
544
- {
545
- error: string
546
- }
547
- ```
548
-
549
- ### Heartbeat (Optional)
550
- ```typescript
551
- {
552
- type: "heartbeat"
553
- }
554
- ```
555
-
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
567
-
568
- # Run tests (core)
569
- npm test
570
-
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
582
-
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
- ```
598
-
599
- ## License
600
-
601
- MIT ยฉ NIBSS PLC