@nibssplc/cams-sdk 0.0.1-beta.13 → 0.0.1-beta.14

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.
@@ -0,0 +1 @@
1
+ export {};
package/dist/auth.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import { CAMSConfig, CAMSTokenResponse } from "./types";
2
- export declare function validateConfig(config: CAMSConfig): void;
2
+ export declare function validateConfig(config: CAMSConfig): URL;
3
3
  export declare function openCAMSPopUpLogin(config: CAMSConfig): Promise<CAMSTokenResponse>;
package/dist/index.cjs.js CHANGED
@@ -10,16 +10,18 @@ exports.CAMSErrorType = void 0;
10
10
  CAMSErrorType["USER_CANCELLED"] = "USER_CANCELLED";
11
11
  CAMSErrorType["INVALID_URL"] = "INVALID_URL";
12
12
  CAMSErrorType["MAX_RETRIES_EXCEEDED"] = "MAX_RETRIES_EXCEEDED";
13
+ CAMSErrorType["API_VALIDATION_ERROR"] = "API_VALIDATION_ERROR";
13
14
  })(exports.CAMSErrorType || (exports.CAMSErrorType = {}));
14
15
  class CAMSError extends Error {
16
+ type;
15
17
  constructor(type, message) {
16
18
  super(message);
17
19
  this.type = type;
18
- this.name = 'CAMSError';
20
+ this.name = this.constructor.name;
19
21
  }
20
22
  }
21
23
 
22
- // Validate the returned token - Base64 format with minimum 20 chars
24
+ // Validate the returned token - non-empty string
23
25
  const TokenMessageSchema = zod.z.object({
24
26
  type: zod.z.literal("AUTH_SUCCESS"),
25
27
  accessToken: zod.z.string().min(1, "Access token cannot be empty"),
@@ -46,14 +48,7 @@ const ProfileSchema = zod.z.object({
46
48
  family_name: zod.z.string().optional(),
47
49
  roles: zod.z.array(zod.z.string()).optional(),
48
50
  });
49
- // Matches IPv4 addresses like 192.168.x.x, 10.x.x.x, 172.16–31.x.x
50
- const internalIpRegex = /^(http:\/\/|https:\/\/)((10\.\d{1,3}\.\d{1,3}\.\d{1,3})|(192\.168\.\d{1,3}\.\d{1,3})|(172\.(1[6-9]|2\d|3[0-1])\.\d{1,3}\.\d{1,3}))(:\d+)?$/;
51
- const URLSchema = zod.z.url().refine((url) => url.startsWith("https://") || // normal HTTPS
52
- /^http:\/\/localhost(:\d+)?$/i.test(url) || // localhost
53
- internalIpRegex.test(url), // internal LAN IPs
54
- {
55
- message: "Only HTTPS, http://localhost, or internal IPs (192.168.x.x, 10.x.x.x, 172.16–31.x.x) are allowed",
56
- });
51
+ const URLSchema = zod.z.url();
57
52
 
58
53
  exports.LogLevel = void 0;
59
54
  (function (LogLevel) {
@@ -63,158 +58,239 @@ exports.LogLevel = void 0;
63
58
  LogLevel[LogLevel["DEBUG"] = 3] = "DEBUG";
64
59
  })(exports.LogLevel || (exports.LogLevel = {}));
65
60
  class Logger {
61
+ static level = exports.LogLevel.WARN;
62
+ static prefix = '[CAMS-SDK]';
63
+ static isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';
66
64
  static setLevel(level) {
67
65
  Logger.level = level;
68
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-\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
+ }
69
81
  static error(message, context) {
70
82
  if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.ERROR) {
71
- console.error(`${Logger.prefix} ERROR:`, message, context || '');
83
+ console.error(`${Logger.prefix} ERROR:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
72
84
  }
73
85
  }
74
86
  static warn(message, context) {
75
87
  if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.WARN) {
76
- console.warn(`${Logger.prefix} WARN:`, message, context || '');
88
+ console.warn(`${Logger.prefix} WARN:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
77
89
  }
78
90
  }
79
91
  static info(message, context) {
80
92
  if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.INFO) {
81
- console.info(`${Logger.prefix} INFO:`, message, context || '');
93
+ console.info(`${Logger.prefix} INFO:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
82
94
  }
83
95
  }
84
96
  static debug(message, context) {
85
97
  if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.DEBUG) {
86
- console.debug(`${Logger.prefix} DEBUG:`, message, context || '');
98
+ console.debug(`${Logger.prefix} DEBUG:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
87
99
  }
88
100
  }
89
101
  }
90
- Logger.level = exports.LogLevel.WARN;
91
- Logger.prefix = '[CAMS-SDK]';
92
- Logger.isTestEnv = typeof process !== 'undefined' && process.env?.NODE_ENV === 'test';
93
102
 
94
103
  function validateConfig(config) {
95
- // Validate URL format
104
+ // Validate URL format and parse once
96
105
  const urlValidation = URLSchema.safeParse(config.camsUrl);
97
106
  if (!urlValidation.success) {
98
- throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'Invalid CAMS URL format');
107
+ throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Invalid CAMS URL format");
99
108
  }
100
109
  // Domain validation is mandatory for security
101
- if (!config.allowedDomains?.length) {
102
- throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');
103
- }
104
- const url = new URL(config.camsUrl); // URLSchema already validated this
105
- const isAllowed = config.allowedDomains.some(domain => url.hostname === domain || url.hostname.endsWith('.' + domain));
106
- if (!isAllowed) {
107
- throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'URL not in allowed domains list');
110
+ if (!config.messageOrigin) {
111
+ throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Message Origin must be specified for security");
108
112
  }
113
+ const url = new URL(config.camsUrl);
114
+ return url;
109
115
  }
110
116
  function openCAMSPopUpLogin(config) {
111
117
  return new Promise((resolve, reject) => {
112
118
  if (config.debug)
113
119
  Logger.setLevel(exports.LogLevel.DEBUG);
114
- Logger.info('Starting CAMS authentication', { url: config.camsUrl });
120
+ Logger.info("Starting CAMS authentication", { url: config.camsUrl });
121
+ let validatedUrl;
115
122
  try {
116
- validateConfig(config);
117
- Logger.debug('Config validation passed');
123
+ validatedUrl = validateConfig(config);
124
+ Logger.debug("Config validation passed");
118
125
  }
119
126
  catch (error) {
120
- Logger.error('Config validation failed', { error: error instanceof Error ? error.message : 'Unknown error' });
127
+ Logger.error("Config validation failed", {
128
+ error: error instanceof Error ? error.message : "Unknown error",
129
+ });
121
130
  reject(error);
122
131
  return;
123
132
  }
124
- const { camsUrl, allowedOrigin, windowHeight, windowWidth, timeout = 300000 } = config;
133
+ const { messageOrigin, windowHeight, windowWidth, authTimeout = 300000, // 5 minutes as a final failsafe
134
+ idleTimeout = 60000, // 1 minute of inactivity
135
+ } = config;
125
136
  let authWindow;
126
- let timeoutId = null;
137
+ let authTimeoutId = null;
138
+ let idleTimeoutId = null;
127
139
  let checkClosedInterval = null;
128
140
  try {
129
- Logger.debug('Opening popup window', { width: windowWidth, height: windowHeight });
130
- authWindow = window.open(camsUrl, "NIBSS CAMS Login", `width=${windowWidth},height=${windowHeight}`);
141
+ Logger.debug("Opening popup window", {
142
+ width: windowWidth,
143
+ height: windowHeight,
144
+ });
145
+ // Center the popup window
146
+ const left = (window.screen.width - windowWidth) / 2;
147
+ const top = (window.screen.height - windowHeight) / 2;
148
+ authWindow = window.open(validatedUrl.toString(), "_blank", `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes`);
131
149
  }
132
150
  catch (error) {
133
- Logger.error('Failed to open popup window', { error: error instanceof Error ? error.message : 'Unknown error' });
134
- reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window: " + (error instanceof Error ? error.message : "Unknown error")));
151
+ Logger.error("Failed to open popup window", {
152
+ error: error instanceof Error ? error.message : "Unknown error",
153
+ });
154
+ reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window: " +
155
+ (error instanceof Error ? error.message : "Unknown error")));
135
156
  return;
136
157
  }
137
158
  if (!authWindow) {
138
- Logger.error('Popup window blocked');
159
+ Logger.error("Popup window blocked");
139
160
  reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window. Please allow popups."));
140
161
  return;
141
162
  }
142
- Logger.debug('Popup window opened successfully');
163
+ Logger.debug("Popup window opened successfully");
143
164
  const cleanup = () => {
144
165
  window.removeEventListener("message", listener);
145
- if (timeoutId)
146
- clearTimeout(timeoutId);
166
+ if (idleTimeoutId)
167
+ clearTimeout(idleTimeoutId);
168
+ if (authTimeoutId)
169
+ clearTimeout(authTimeoutId);
147
170
  if (checkClosedInterval)
148
- clearInterval(checkClosedInterval);
149
- };
150
- const cleanupAndClose = (error) => {
151
- cleanup();
152
- try {
153
- if (authWindow && !authWindow.closed) {
154
- authWindow.close();
155
- }
156
- }
157
- catch {
158
- // Ignore close errors
159
- }
160
- if (error)
161
- reject(error);
171
+ clearTimeout(checkClosedInterval);
172
+ idleTimeoutId = null;
173
+ authTimeoutId = null;
174
+ checkClosedInterval = null;
162
175
  };
163
176
  const listener = (event) => {
164
- Logger.debug('Received message', { origin: event.origin, expectedOrigin: allowedOrigin, data: event.data });
165
- if (event.origin !== allowedOrigin) {
166
- Logger.warn('Blocked message from unauthorized origin', { origin: event.origin, expected: allowedOrigin });
177
+ Logger.debug("Received message", {
178
+ origin: event.origin,
179
+ expectedOrigin: messageOrigin,
180
+ data: event.data,
181
+ });
182
+ const originUrl = new URL(event.origin);
183
+ const isAllowedOrigin = originUrl.hostname === messageOrigin ||
184
+ originUrl.hostname.endsWith("." + messageOrigin);
185
+ if (!isAllowedOrigin) {
186
+ Logger.warn("Blocked message from unauthorized origin", {
187
+ origin: event.origin,
188
+ expected: messageOrigin,
189
+ });
167
190
  return;
168
191
  }
169
192
  // ✅ Validate payload
170
193
  const tokenMsg = TokenMessageSchema.safeParse(event.data);
171
194
  if (tokenMsg.success) {
172
- Logger.info('Authentication successful');
195
+ Logger.info("Authentication successful");
173
196
  cleanupAndClose();
174
197
  resolve({ token: tokenMsg.data.accessToken });
175
198
  return;
176
199
  }
177
200
  const errorMsg = ErrorMessageSchema.safeParse(event.data);
178
201
  if (errorMsg.success) {
179
- Logger.warn('Authentication error received', { error: errorMsg.data.error });
202
+ Logger.warn("Authentication error received", {
203
+ error: errorMsg.data.error,
204
+ });
180
205
  cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication failed: " + errorMsg.data.error));
181
206
  return;
182
207
  }
183
- Logger.error('Invalid message format received', {
208
+ Logger.error("Invalid message format received", {
184
209
  messageData: event.data,
185
210
  dataType: typeof event.data,
186
- tokenValidationError: tokenMsg.error?.issues,
187
- errorValidationError: errorMsg.error?.issues
211
+ tokenValidationError: tokenMsg.error
212
+ ? tokenMsg.error.issues
213
+ : undefined,
214
+ errorValidationError: errorMsg.error
215
+ ? errorMsg.error.issues
216
+ : undefined,
188
217
  });
189
218
  cleanupAndClose(new CAMSError(exports.CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
190
219
  };
191
- // Timeout handler
192
- Logger.debug('Setting timeout', { timeout });
193
- timeoutId = setTimeout(() => {
194
- Logger.warn('Authentication timeout', { timeout });
195
- cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));
196
- }, timeout);
197
- checkClosedInterval = setInterval(() => {
220
+ const cleanupAndClose = (error) => {
221
+ cleanup();
222
+ try {
223
+ if (authWindow && !authWindow.closed) {
224
+ authWindow.close();
225
+ }
226
+ }
227
+ catch {
228
+ // Ignore close errors
229
+ }
230
+ if (error)
231
+ reject(error);
232
+ };
233
+ const resetIdleTimeout = () => {
234
+ // Timeout handler
235
+ if (idleTimeoutId)
236
+ clearTimeout(idleTimeoutId);
237
+ Logger.debug("Resetting idle timeout", { idleTimeout });
238
+ idleTimeoutId = setTimeout(() => {
239
+ Logger.warn("Authentication idle timeout reached", { idleTimeout });
240
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timed out due to inactivity after ${idleTimeout}ms`));
241
+ }, idleTimeout);
242
+ };
243
+ Logger.debug("Setting auth timeout", { authTimeout });
244
+ authTimeoutId = setTimeout(() => {
245
+ Logger.warn("Authentication auth timeout reached", { authTimeout });
246
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication process exceeded auth time limit of ${authTimeout}ms`));
247
+ }, authTimeout);
248
+ resetIdleTimeout();
249
+ // Use exponential backoff for popup closure checking
250
+ let pollInterval = 1000; // Start with 1 second
251
+ const maxPollInterval = 5000; // Max 5 seconds
252
+ const checkClosed = () => {
198
253
  if (authWindow?.closed) {
199
- Logger.info('Authentication window closed by user');
254
+ Logger.info("Authentication window closed by user");
200
255
  cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
256
+ return;
201
257
  }
202
- }, 2000); // Reduced polling frequency
258
+ // Exponential backoff: increase interval up to max
259
+ pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);
260
+ checkClosedInterval = setTimeout(checkClosed, pollInterval);
261
+ };
262
+ checkClosedInterval = setTimeout(checkClosed, pollInterval);
203
263
  try {
204
264
  window.addEventListener("message", listener);
265
+ Logger.debug("Message listener attached");
205
266
  }
206
267
  catch (error) {
268
+ Logger.error("Failed to attach message listener", {
269
+ error: error instanceof Error ? error.message : "Unknown error",
270
+ });
207
271
  cleanup();
208
- reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " + (error instanceof Error ? error.message : "Unknown error")));
272
+ reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " +
273
+ (error instanceof Error ? error.message : "Unknown error")));
209
274
  return;
210
275
  }
276
+ // Add focus to the popup for better UX
277
+ try {
278
+ if (authWindow) {
279
+ authWindow.focus();
280
+ }
281
+ }
282
+ catch {
283
+ // Ignore focus errors (cross-origin restrictions)
284
+ }
211
285
  });
212
286
  }
213
287
 
214
288
  class TokenManager {
289
+ storage;
290
+ token = null;
291
+ storageKey;
215
292
  constructor(storage = sessionStorage, storageKey) {
216
293
  this.storage = storage;
217
- this.token = null;
218
294
  this.storageKey = storageKey || "cams_token";
219
295
  }
220
296
  setToken(token) {
@@ -223,6 +299,7 @@ class TokenManager {
223
299
  Logger.debug("Token stored", { storageKey: this.storageKey });
224
300
  }
225
301
  loadToken() {
302
+ // Return cached token if available
226
303
  if (this.token)
227
304
  return this.token;
228
305
  const raw = this.storage.getItem(this.storageKey);
@@ -238,38 +315,37 @@ class TokenManager {
238
315
  Logger.debug("Token cleared");
239
316
  }
240
317
  getAccessToken() {
241
- const token = this.loadToken();
242
- return token;
318
+ // Return cached token if available, avoiding redundant storage access
319
+ if (this.token)
320
+ return this.token;
321
+ return this.loadToken();
243
322
  }
244
323
  isExpired() {
245
324
  const token = this.loadToken();
246
325
  if (!token)
247
326
  return true;
248
- // JWT expiration check if available
249
- if (token) {
250
- try {
251
- const parts = token.split(".");
252
- if (parts.length < 3)
253
- return true; // Invalid JWT format
254
- const payload = JSON.parse(atob(parts[1]));
255
- if (typeof payload.exp !== "number")
256
- return true;
257
- const exp = payload.exp * 1000;
258
- return Date.now() > exp;
259
- }
260
- catch (error) {
261
- Logger.warn("Failed to parse JWT token", {
262
- error: error instanceof Error ? error.message : "Unknown error",
263
- });
327
+ try {
328
+ const parts = token.split(".");
329
+ if (parts.length < 3)
330
+ return true; // Invalid JWT format
331
+ const payload = JSON.parse(atob(parts[1]));
332
+ if (typeof payload.exp !== "number")
264
333
  return true;
265
- }
334
+ const exp = payload.exp * 1000;
335
+ return Date.now() > exp;
336
+ }
337
+ catch (error) {
338
+ Logger.warn("Failed to parse JWT token", {
339
+ error: error instanceof Error ? error.message : "Unknown error",
340
+ });
341
+ return true;
266
342
  }
267
- // Fallback: return true for safety when expiration cannot be determined
268
- return true;
269
343
  }
270
344
  }
271
345
 
272
346
  class CAMSSessionManager {
347
+ tokenManager;
348
+ events;
273
349
  constructor(storage = sessionStorage, storageKey, events = {}) {
274
350
  this.tokenManager = new TokenManager(storage, storageKey);
275
351
  this.events = events;
@@ -277,18 +353,27 @@ class CAMSSessionManager {
277
353
  async login(config) {
278
354
  try {
279
355
  Logger.info('Session login started');
280
- this.events.onAuthStart && this.events.onAuthStart();
356
+ if (this.events.onAuthStart)
357
+ this.events.onAuthStart();
281
358
  let attempts = 0;
282
- const maxAttempts = (config.retryAttempts ?? 0) + 1;
359
+ const maxAttempts = (config.retryAttempts !== undefined ? config.retryAttempts : 0) + 1;
283
360
  Logger.debug('Login retry configuration', { maxAttempts });
284
361
  while (attempts < maxAttempts) {
285
362
  try {
286
363
  attempts++;
287
364
  Logger.debug('Login attempt', { attempt: attempts, maxAttempts });
365
+ // Add exponential backoff delay for retries
366
+ if (attempts > 1) {
367
+ const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay
368
+ Logger.debug('Retry delay', { delay });
369
+ await new Promise(resolve => setTimeout(resolve, delay));
370
+ }
288
371
  const response = await openCAMSPopUpLogin(config);
372
+ Logger.debug('Login Response', response);
289
373
  this.tokenManager.setToken(response.token);
290
374
  Logger.info('Session login successful');
291
- this.events.onAuthSuccess && this.events.onAuthSuccess(response);
375
+ if (this.events.onAuthSuccess)
376
+ this.events.onAuthSuccess(response);
292
377
  return response;
293
378
  }
294
379
  catch (error) {
@@ -310,7 +395,8 @@ class CAMSSessionManager {
310
395
  const camsError = error instanceof CAMSError ? error :
311
396
  new CAMSError(exports.CAMSErrorType.USER_CANCELLED, errorMessage);
312
397
  Logger.error('Session login failed', { error: camsError.message, type: camsError.type });
313
- this.events.onAuthError && this.events.onAuthError(camsError);
398
+ if (this.events.onAuthError)
399
+ this.events.onAuthError(camsError);
314
400
  throw camsError;
315
401
  }
316
402
  }
@@ -318,15 +404,22 @@ class CAMSSessionManager {
318
404
  Logger.info('Session logout');
319
405
  this.tokenManager.clearToken();
320
406
  }
407
+ checkTokenExpiration() {
408
+ if (this.tokenManager.isExpired()) {
409
+ Logger.info('Token expired');
410
+ if (this.events.onTokenExpired)
411
+ this.events.onTokenExpired();
412
+ return true;
413
+ }
414
+ return false;
415
+ }
321
416
  isAuthenticated() {
322
417
  const token = this.tokenManager.loadToken();
323
418
  if (!token) {
324
419
  Logger.debug('No token found');
325
420
  return false;
326
421
  }
327
- if (this.tokenManager.isExpired()) {
328
- Logger.info('Token expired');
329
- this.events.onTokenExpired?.();
422
+ if (this.checkTokenExpiration()) {
330
423
  return false;
331
424
  }
332
425
  Logger.debug('Token is valid');
@@ -336,25 +429,28 @@ class CAMSSessionManager {
336
429
  const token = this.tokenManager.loadToken();
337
430
  if (!token)
338
431
  return null;
339
- if (this.tokenManager.isExpired()) {
340
- this.events.onTokenExpired?.();
432
+ if (this.checkTokenExpiration()) {
341
433
  return null;
342
434
  }
343
435
  return token;
344
436
  }
345
437
  decodeBase64Url(str) {
346
- // Convert base64url to base64
347
- str = str.replace(/-/g, '+').replace(/_/g, '/');
438
+ // Work with a copy to avoid mutating input
439
+ let result = str.replace(/-/g, '+').replace(/_/g, '/');
348
440
  // Add padding if needed
349
- while (str.length % 4) {
350
- str += '=';
441
+ while (result.length % 4) {
442
+ result += '=';
351
443
  }
352
- return atob(str);
444
+ return atob(result);
353
445
  }
354
446
  async getProfile() {
355
447
  const storedToken = this.tokenManager.loadToken();
356
448
  if (!storedToken)
357
449
  return null;
450
+ // Check token expiration before processing
451
+ if (this.checkTokenExpiration()) {
452
+ return null;
453
+ }
358
454
  try {
359
455
  const parts = storedToken.split('.');
360
456
  if (parts.length >= 3) { // JWT has header.payload.signature format