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

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
@@ -23,16 +23,14 @@ class CAMSError extends Error {
23
23
 
24
24
  // Validate the returned token - non-empty string
25
25
  const ProfileSchema = zod.z.object({
26
- type: zod.z.literal("AUTH_SUCCESS"),
27
- userProfile: zod.z
28
- .object({
26
+ type: zod.z.literal("AUTH_SUCCESS").or(zod.z.literal("AUTH_FAILURE")),
27
+ userProfile: zod.z.object({
29
28
  name: zod.z.string(),
30
29
  email: zod.z.email(),
31
30
  mfaIsEnabled: zod.z.boolean(),
32
31
  message: zod.z.string(),
33
32
  isAuthenticated: zod.z.boolean(),
34
33
  userType: zod.z.enum(["SUPER_ADMIN", "ADMIN", "USER"]),
35
- redirectURL: zod.z.url().optional(),
36
34
  tokens: zod.z.object({
37
35
  Nonce: zod.z.string(),
38
36
  Bearer: zod.z.string(),
@@ -64,38 +62,24 @@ class Logger {
64
62
  static setLevel(level) {
65
63
  Logger.level = level;
66
64
  }
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
65
  static error(message, context) {
82
66
  if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.ERROR) {
83
- console.error(`${Logger.prefix} ERROR:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
67
+ console.error(`${Logger.prefix} ERROR:`, message, context || '');
84
68
  }
85
69
  }
86
70
  static warn(message, context) {
87
71
  if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.WARN) {
88
- console.warn(`${Logger.prefix} WARN:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
72
+ console.warn(`${Logger.prefix} WARN:`, message, context || '');
89
73
  }
90
74
  }
91
75
  static info(message, context) {
92
76
  if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.INFO) {
93
- console.info(`${Logger.prefix} INFO:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
77
+ console.info(`${Logger.prefix} INFO:`, message, context || '');
94
78
  }
95
79
  }
96
80
  static debug(message, context) {
97
81
  if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.DEBUG) {
98
- console.debug(`${Logger.prefix} DEBUG:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
82
+ console.debug(`${Logger.prefix} DEBUG:`, message, context || '');
99
83
  }
100
84
  }
101
85
  }
@@ -572,6 +556,7 @@ exports.ErrorMessageSchema = ErrorMessageSchema;
572
556
  exports.Logger = Logger;
573
557
  exports.ProfileSchema = ProfileSchema;
574
558
  exports.URLSchema = URLSchema;
559
+ exports.generateSecureWindowName = generateSecureWindowName;
575
560
  exports.openCAMSPopUpLogin = openCAMSPopUpLogin;
576
561
  exports.validateConfig = validateConfig;
577
562
  //# sourceMappingURL=index.cjs.js.map