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