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

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