@nibssplc/cams-sdk 0.0.1-beta.37 → 0.0.1-beta.38

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
@@ -87,13 +87,31 @@
87
87
  }
88
88
 
89
89
  // Capture original functions to prevent tampering (client-side only)
90
- const originalAddEventListener = typeof window !== "undefined" ? window.addEventListener : null;
91
- const originalRemoveEventListener = typeof window !== "undefined" ? window.removeEventListener : null;
92
- const originalSetTimeout = typeof window !== "undefined" ? window.setTimeout : setTimeout;
93
- const originalClearTimeout = typeof window !== "undefined" ? window.clearTimeout : clearTimeout;
94
- // Generate random window name to prevent targeting
95
- const generateSecureWindowName = () => `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;
96
- // Detect if current window is a popup
90
+ // Constants
91
+ const DEFAULT_AUTH_TIMEOUT = 300000; // 5 minutes
92
+ const DEFAULT_IDLE_TIMEOUT = 120000; // 2 minutes
93
+ const INITIAL_POLL_INTERVAL = 1000;
94
+ const MAX_POLL_INTERVAL = 5000;
95
+ const WINDOW_FEATURES = "scrollbars=yes,resizable=yes";
96
+ // Secure reference to native functions
97
+ const NativeFunctions = {
98
+ addEventListener: typeof window !== "undefined" ? window.addEventListener : null,
99
+ removeEventListener: typeof window !== "undefined" ? window.removeEventListener : null,
100
+ setTimeout: typeof window !== "undefined" ? window.setTimeout : setTimeout,
101
+ clearTimeout: typeof window !== "undefined" ? window.clearTimeout : clearTimeout,
102
+ };
103
+ const defaultMicrosoftDomains = [
104
+ ".microsoft.com",
105
+ ".microsoftonline.com",
106
+ ".live.com",
107
+ ];
108
+ /**
109
+ * Generate a secure random window name to prevent targeting
110
+ */
111
+ const generateSecureWindowName = () => `NINSS_CAS_AUTH_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;
112
+ /**
113
+ * Detect if current window is a popup to prevent recursive popups
114
+ */
97
115
  const isPopupWindow = () => {
98
116
  if (typeof window === "undefined")
99
117
  return false;
@@ -104,256 +122,326 @@
104
122
  return false;
105
123
  }
106
124
  };
125
+ /**
126
+ * Safely close a window with error handling for cross-origin restrictions
127
+ */
128
+ const safeWindowClose = (window) => {
129
+ if (!window)
130
+ return;
131
+ try {
132
+ if (!window.closed) {
133
+ window.close();
134
+ }
135
+ }
136
+ catch (error) {
137
+ Logger.debug("Error closing window (cross-origin restriction)", {
138
+ error: error instanceof Error ? error.message : "Unknown error",
139
+ });
140
+ }
141
+ };
142
+ /**
143
+ * Center popup window on screen
144
+ */
145
+ const getPopupPosition = (width, height) => {
146
+ if (typeof window === "undefined")
147
+ return { left: 0, top: 0 };
148
+ const left = Math.max(0, (window.screen.width - width) / 2);
149
+ const top = Math.max(0, (window.screen.height - height) / 2);
150
+ return { left, top };
151
+ };
152
+ /**
153
+ * Validate origin against expected domain with support for subdomains and Microsoft redirects
154
+ */
155
+ const isValidOrigin = (eventOrigin, expectedOrigin, microsoftDomains = defaultMicrosoftDomains) => {
156
+ try {
157
+ const originUrl = new URL(eventOrigin);
158
+ const expectedHostname = expectedOrigin.startsWith("http")
159
+ ? new URL(expectedOrigin).hostname
160
+ : expectedOrigin;
161
+ // Check Microsoft domains for Azure AD redirects
162
+ const isMicrosoftDomain = microsoftDomains.some((domain) => originUrl.hostname.endsWith(domain));
163
+ // Allow exact match, subdomains, or Microsoft domains
164
+ return (originUrl.hostname === expectedHostname ||
165
+ originUrl.hostname.endsWith("." + expectedHostname) ||
166
+ isMicrosoftDomain);
167
+ }
168
+ catch {
169
+ return false;
170
+ }
171
+ };
172
+ /**
173
+ * Safely add message event listener with error handling
174
+ */
175
+ const addMessageListener = (listener) => {
176
+ if (!NativeFunctions.addEventListener) {
177
+ throw new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Message listener not available in current environment");
178
+ }
179
+ const wrappedListener = (event) => {
180
+ try {
181
+ listener(event);
182
+ }
183
+ catch (error) {
184
+ Logger.error("Error in message listener", {
185
+ error: error instanceof Error ? error.message : "Unknown error",
186
+ });
187
+ }
188
+ };
189
+ NativeFunctions.addEventListener.call(window, "message", wrappedListener);
190
+ return () => {
191
+ if (NativeFunctions.removeEventListener) {
192
+ NativeFunctions.removeEventListener.call(window, "message", wrappedListener);
193
+ }
194
+ };
195
+ };
196
+ /**
197
+ * Validate configuration and return parsed URL
198
+ */
107
199
  function validateConfig(config) {
108
- // Validate URL format and parse once
109
200
  const urlValidation = URLSchema.safeParse(config.camsUrl);
110
201
  if (!urlValidation.success) {
111
202
  throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Invalid CAMS URL format");
112
203
  }
113
- // Domain validation is mandatory for security
114
204
  if (!config.messageOrigin) {
115
205
  throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Message Origin must be specified for security");
116
206
  }
117
- const url = new URL(config.camsUrl);
118
- return url;
207
+ return new URL(config.camsUrl);
119
208
  }
209
+ /**
210
+ * Open CAMS authentication popup and handle the authentication flow
211
+ */
120
212
  function openCAMSPopUpLogin(config) {
121
213
  return new Promise((resolve, reject) => {
214
+ // Environment validation
122
215
  if (typeof window === "undefined") {
123
216
  reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Cannot open popup in server-side environment"));
124
217
  return;
125
218
  }
126
- if (config.debug)
127
- Logger.setLevel(exports.LogLevel.DEBUG);
128
- // If this is a popup window, don't open another popup
129
219
  if (isPopupWindow()) {
130
- Logger.warn("Cannot open popup from within popup window");
220
+ Logger.warn("Attempted to open popup from within popup window");
131
221
  reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Cannot open authentication popup from within popup window"));
132
222
  return;
133
223
  }
224
+ // Initialize logging
225
+ if (config.debug)
226
+ Logger.setLevel(exports.LogLevel.DEBUG);
134
227
  Logger.info("Starting CAMS authentication", { url: config.camsUrl });
228
+ // Validate configuration
135
229
  let validatedUrl;
136
230
  try {
137
231
  validatedUrl = validateConfig(config);
138
- Logger.debug("Config validation passed");
232
+ Logger.debug("Configuration validation passed");
139
233
  }
140
234
  catch (error) {
141
- Logger.error("Config validation failed", {
235
+ Logger.error("Configuration validation failed", {
142
236
  error: error instanceof Error ? error.message : "Unknown error",
143
237
  });
144
238
  reject(error);
145
239
  return;
146
240
  }
147
- const { messageOrigin, windowHeight, windowWidth, authTimeout = 300000, // 5 minutes as a final failsafe
148
- idleTimeout = 120000, // 2 minutes of inactivity
241
+ // Extract configuration with defaults
242
+ const { messageOrigin, windowHeight = 600, windowWidth = 500, authTimeout = DEFAULT_AUTH_TIMEOUT, idleTimeout = DEFAULT_IDLE_TIMEOUT,
243
+ // allowedRedirectDomains = defaultMicrosoftDomains,
149
244
  } = config;
150
- let authWindow;
245
+ // State management
246
+ let authWindow = null;
151
247
  let authTimeoutId = null;
152
248
  let idleTimeoutId = null;
153
249
  let checkClosedInterval = null;
154
- try {
155
- Logger.debug("Opening popup window", {
156
- width: windowWidth,
157
- height: windowHeight,
158
- });
159
- // Center the popup window
160
- const left = (window.screen.width - windowWidth) / 2;
161
- const top = (window.screen.height - windowHeight) / 2;
162
- const secureWindowName = generateSecureWindowName();
163
- authWindow = window.open(validatedUrl.toString(), secureWindowName, `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes`);
164
- }
165
- catch (error) {
166
- Logger.error("Failed to open popup window", {
167
- error: error instanceof Error ? error.message : "Unknown error",
168
- });
169
- reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
170
- return;
171
- }
172
- if (!authWindow) {
173
- Logger.error("Popup window blocked");
174
- reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
175
- return;
176
- }
177
- // Only check for immediate closure (true popup blocking)
178
- if (authWindow.closed) {
179
- Logger.error("Popup immediately closed by blocker");
180
- reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
181
- return;
182
- }
183
- Logger.debug("Popup window opened successfully");
250
+ let removeMessageListener = null;
251
+ /**
252
+ * Clean up all resources and timeouts
253
+ */
184
254
  const cleanup = () => {
185
- if (originalRemoveEventListener) {
186
- originalRemoveEventListener.call(window, "message", listener);
255
+ if (removeMessageListener) {
256
+ removeMessageListener();
257
+ removeMessageListener = null;
187
258
  }
188
259
  if (idleTimeoutId)
189
- originalClearTimeout(idleTimeoutId);
260
+ NativeFunctions.clearTimeout(idleTimeoutId);
190
261
  if (authTimeoutId)
191
- originalClearTimeout(authTimeoutId);
262
+ NativeFunctions.clearTimeout(authTimeoutId);
192
263
  if (checkClosedInterval)
193
- originalClearTimeout(checkClosedInterval);
264
+ NativeFunctions.clearTimeout(checkClosedInterval);
194
265
  idleTimeoutId = null;
195
266
  authTimeoutId = null;
196
267
  checkClosedInterval = null;
197
268
  };
198
- const listener = (event) => {
199
- const messageEvent = event;
269
+ /**
270
+ * Clean up and close the popup window, then reject with error
271
+ */
272
+ const cleanupAndClose = (error) => {
273
+ cleanup();
274
+ safeWindowClose(authWindow);
275
+ if (error) {
276
+ reject(error);
277
+ }
278
+ };
279
+ /**
280
+ * Reset idle timeout on user activity
281
+ */
282
+ const resetIdleTimeout = () => {
283
+ if (idleTimeoutId)
284
+ NativeFunctions.clearTimeout(idleTimeoutId);
285
+ Logger.debug("Resetting idle timeout", { idleTimeout });
286
+ idleTimeoutId = NativeFunctions.setTimeout(() => {
287
+ Logger.warn("Authentication idle timeout reached", { idleTimeout });
288
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timed out due to inactivity after ${idleTimeout}ms`));
289
+ }, idleTimeout);
290
+ };
291
+ /**
292
+ * Set up popup window closure detection with exponential backoff
293
+ */
294
+ const setupClosureDetection = () => {
295
+ let pollInterval = INITIAL_POLL_INTERVAL;
296
+ const checkClosed = () => {
297
+ try {
298
+ if (authWindow?.closed) {
299
+ Logger.info("Authentication window closed by user");
300
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
301
+ return;
302
+ }
303
+ }
304
+ catch (error) {
305
+ // Cross-origin access error means window is still open but on different domain
306
+ Logger.debug("Cannot access window.closed due to cross-origin restrictions", error);
307
+ }
308
+ // Exponential backoff with maximum limit
309
+ pollInterval = Math.min(pollInterval * 1.2, MAX_POLL_INTERVAL);
310
+ checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);
311
+ };
312
+ checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);
313
+ };
314
+ /**
315
+ * Handle incoming message events from the popup
316
+ */
317
+ const handleMessage = (event) => {
200
318
  Logger.debug("Received message", {
201
- origin: messageEvent.origin,
319
+ origin: event.origin,
202
320
  expectedOrigin: messageOrigin,
203
- data: messageEvent.data,
321
+ data: event.data,
204
322
  });
205
- const originUrl = new URL(messageEvent.origin);
206
- const expectedHostname = messageOrigin.startsWith("http")
207
- ? new URL(messageOrigin).hostname
208
- : messageOrigin;
209
- // Allow Microsoft redirect domains for Azure AD authentication
210
- const isMicrosoftDomain = originUrl.hostname.endsWith(".microsoft.com") ||
211
- originUrl.hostname.endsWith(".microsoftonline.com") ||
212
- originUrl.hostname.endsWith(".live.com");
213
- const isAllowedOrigin = originUrl.hostname === expectedHostname ||
214
- originUrl.hostname.endsWith("." + expectedHostname) ||
215
- isMicrosoftDomain;
216
- if (!isAllowedOrigin) {
323
+ // Security: Validate origin
324
+ if (!isValidOrigin(event.origin, messageOrigin, defaultMicrosoftDomains)) {
217
325
  Logger.warn("Blocked message from unauthorized origin", {
218
- origin: messageEvent.origin,
326
+ origin: event.origin,
219
327
  expected: messageOrigin,
220
- data: messageEvent.data,
328
+ data: event.data,
221
329
  });
222
330
  return;
223
331
  }
224
- // Validate event source
225
- if (messageEvent.source !== authWindow) {
332
+ // Security: Validate message source
333
+ if (event.source !== authWindow) {
226
334
  Logger.warn("Message from unexpected source", {
227
- source: messageEvent.source,
228
- origin: messageEvent.origin,
335
+ source: event.source,
336
+ origin: event.origin,
229
337
  expected: messageOrigin,
230
- data: messageEvent.data,
338
+ data: event.data,
231
339
  });
232
340
  return;
233
341
  }
234
- // Validate event source
235
- if (messageEvent.source !== authWindow) {
236
- Logger.warn("Message from unexpected source", {
237
- source: messageEvent.source,
238
- origin: messageEvent.origin,
239
- expected: messageOrigin,
240
- data: messageEvent.data,
241
- });
242
- return;
243
- }
244
- // Ignore heartbeat messages
245
- if (messageEvent.data?.type === "heartbeat") {
342
+ // Handle heartbeat messages (reset idle timeout)
343
+ if (event.data?.type === "heartbeat") {
246
344
  Logger.debug("Received heartbeat message");
247
345
  resetIdleTimeout();
248
346
  return;
249
347
  }
250
- // ✅ Validate payload
251
- const tokenMsg = ProfileSchema.safeParse(messageEvent.data);
252
- if (tokenMsg.success) {
348
+ // Process authentication messages
349
+ processAuthenticationMessage(event.data);
350
+ };
351
+ /**
352
+ * Process and validate authentication message payloads
353
+ */
354
+ const processAuthenticationMessage = (data) => {
355
+ // Success case: Valid profile received
356
+ const profileValidation = ProfileSchema.safeParse(data);
357
+ if (profileValidation.success) {
253
358
  Logger.info("Authentication successful");
254
359
  cleanupAndClose();
255
- resolve(tokenMsg.data);
360
+ resolve(profileValidation.data);
256
361
  return;
257
362
  }
258
- const authFailureMsg = AuthFailureMessageSchema.safeParse(messageEvent.data);
259
- if (authFailureMsg.success) {
363
+ // Authentication failure case
364
+ const authFailureValidation = AuthFailureMessageSchema.safeParse(data);
365
+ if (authFailureValidation.success) {
366
+ const { error, errorCode, errorDetails } = authFailureValidation.data;
260
367
  Logger.warn("Authentication failure received", {
261
- errorDetails: authFailureMsg.data.errorDetails,
262
- error: authFailureMsg.data.error,
263
- errorCode: authFailureMsg.data.errorCode,
368
+ error,
369
+ errorCode,
370
+ errorDetails,
264
371
  });
265
- cleanupAndClose(new CAMSError(exports.CAMSErrorType.API_VALIDATION_ERROR, "Authentication failed: " + authFailureMsg.data.error));
372
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.API_VALIDATION_ERROR, `Authentication failed: ${error}${errorCode ? ` (${errorCode})` : ""}`));
266
373
  return;
267
374
  }
268
- const errorMsg = ErrorMessageSchema.safeParse(messageEvent.data);
269
- if (errorMsg.success) {
375
+ // Generic error case
376
+ const errorValidation = ErrorMessageSchema.safeParse(data);
377
+ if (errorValidation.success) {
270
378
  Logger.warn("Authentication error received", {
271
- error: errorMsg.data.error,
379
+ error: errorValidation.data.error,
272
380
  });
273
- cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication failed: " + errorMsg.data.error));
381
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, `Authentication failed: ${errorValidation.data.error}`));
274
382
  return;
275
383
  }
384
+ // Invalid message format
276
385
  Logger.error("Invalid message format received", {
277
- messageData: messageEvent.data,
278
- dataType: typeof messageEvent.data,
279
- tokenValidationError: tokenMsg.error
280
- ? tokenMsg.error.issues
281
- : undefined,
282
- errorValidationError: errorMsg.error
283
- ? errorMsg.error.issues
284
- : undefined,
386
+ messageData: data,
387
+ dataType: typeof data,
388
+ profileValidationError: profileValidation.error?.issues,
389
+ authFailureValidationError: authFailureValidation.error?.issues,
390
+ errorValidationError: errorValidation.error?.issues,
285
391
  });
286
392
  cleanupAndClose(new CAMSError(exports.CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
287
393
  };
288
- const cleanupAndClose = (error) => {
289
- cleanup();
290
- try {
291
- if (authWindow && !authWindow.closed) {
292
- authWindow.close();
293
- }
294
- }
295
- catch {
296
- // Ignore close errors
394
+ // Main authentication flow execution
395
+ try {
396
+ // Open popup window
397
+ const { left, top } = getPopupPosition(windowWidth, windowHeight);
398
+ const secureWindowName = generateSecureWindowName();
399
+ Logger.debug("Opening popup window", {
400
+ width: windowWidth,
401
+ height: windowHeight,
402
+ left,
403
+ top,
404
+ });
405
+ authWindow = window.open(validatedUrl.toString(), secureWindowName, `width=${windowWidth},height=${windowHeight},left=${left},top=${top},${WINDOW_FEATURES}`);
406
+ // Check for popup blocking
407
+ if (!authWindow) {
408
+ Logger.error("Popup window blocked or failed to open");
409
+ reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
410
+ return;
297
411
  }
298
- if (error)
299
- reject(error);
300
- };
301
- const resetIdleTimeout = () => {
302
- // Timeout handler
303
- if (idleTimeoutId)
304
- originalClearTimeout(idleTimeoutId);
305
- Logger.debug("Resetting idle timeout", { idleTimeout });
306
- idleTimeoutId = originalSetTimeout(() => {
307
- Logger.warn("Authentication idle timeout reached", { idleTimeout });
308
- cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timed out due to inactivity after ${idleTimeout}ms`));
309
- }, idleTimeout);
310
- };
311
- Logger.debug("Setting auth timeout", { authTimeout });
312
- authTimeoutId = originalSetTimeout(() => {
313
- Logger.warn("Authentication auth timeout reached", { authTimeout });
314
- cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication process exceeded auth time limit of ${authTimeout}ms`));
315
- }, authTimeout);
316
- resetIdleTimeout();
317
- // Use exponential backoff for popup closure checking
318
- let pollInterval = 1000; // Start with 1 second
319
- const maxPollInterval = 5000; // Max 5 seconds
320
- const checkClosed = () => {
321
- if (authWindow?.closed) {
322
- Logger.info("Authentication window closed by user");
323
- cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
412
+ // Check for immediate closure (aggressive popup blockers)
413
+ if (authWindow.closed) {
414
+ Logger.error("Popup immediately closed by blocker");
415
+ reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
324
416
  return;
325
417
  }
326
- // Exponential backoff: increase interval up to max
327
- pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);
328
- checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);
329
- };
330
- checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);
331
- try {
332
- if (originalAddEventListener) {
333
- originalAddEventListener.call(window, "message", listener);
334
- Logger.debug("Message listener attached");
418
+ Logger.debug("Popup window opened successfully");
419
+ // Set up message listener
420
+ removeMessageListener = addMessageListener(handleMessage);
421
+ Logger.debug("Message listener attached");
422
+ // Set up timeouts
423
+ Logger.debug("Setting authentication timeout", { authTimeout });
424
+ authTimeoutId = NativeFunctions.setTimeout(() => {
425
+ Logger.warn("Authentication timeout reached", { authTimeout });
426
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication process exceeded time limit of ${authTimeout}ms`));
427
+ }, authTimeout);
428
+ resetIdleTimeout();
429
+ setupClosureDetection();
430
+ // Focus popup for better UX
431
+ try {
432
+ authWindow.focus();
335
433
  }
336
- else {
337
- throw new Error("addEventListener not available");
434
+ catch (error) {
435
+ Logger.debug("Could not focus popup window (cross-origin restriction)", error);
338
436
  }
339
437
  }
340
438
  catch (error) {
341
- Logger.error("Failed to attach message listener", {
439
+ Logger.error("Failed to initialize authentication popup", {
342
440
  error: error instanceof Error ? error.message : "Unknown error",
343
441
  });
344
442
  cleanup();
345
- reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " +
443
+ reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to initialize authentication: " +
346
444
  (error instanceof Error ? error.message : "Unknown error")));
347
- return;
348
- }
349
- // Add focus to the popup for better UX
350
- try {
351
- if (authWindow && !authWindow.closed) {
352
- authWindow.focus();
353
- }
354
- }
355
- catch {
356
- // Ignore focus errors (cross-origin restrictions)
357
445
  }
358
446
  });
359
447
  }