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