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