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

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