@nibssplc/cams-sdk 0.0.1-beta.3 → 0.0.1-beta.30

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.cjs.js CHANGED
@@ -10,229 +10,401 @@ exports.CAMSErrorType = void 0;
10
10
  CAMSErrorType["USER_CANCELLED"] = "USER_CANCELLED";
11
11
  CAMSErrorType["INVALID_URL"] = "INVALID_URL";
12
12
  CAMSErrorType["MAX_RETRIES_EXCEEDED"] = "MAX_RETRIES_EXCEEDED";
13
+ CAMSErrorType["API_VALIDATION_ERROR"] = "VALIDATION_ERROR";
13
14
  })(exports.CAMSErrorType || (exports.CAMSErrorType = {}));
14
15
  class CAMSError extends Error {
16
+ type;
15
17
  constructor(type, message) {
16
18
  super(message);
17
19
  this.type = type;
18
- this.name = 'CAMSError';
20
+ this.name = this.constructor.name;
19
21
  }
20
22
  }
21
23
 
22
- // Validate the returned token - Base64 format with minimum 20 chars
23
- const TokenMessageSchema = zod.z.object({
24
- access_token: zod.z.string().regex(/^[A-Za-z0-9+/]{20,}={0,2}$/, "Invalid NIBSS CAMS token format"),
24
+ // Validate the returned token - non-empty string
25
+ const ProfileSchema = zod.z.object({
26
+ type: zod.z.literal("AUTH_SUCCESS"),
27
+ userProfile: zod.z
28
+ .object({
29
+ name: zod.z.string(),
30
+ email: zod.z.email(),
31
+ mfaIsEnabled: zod.z.boolean(),
32
+ message: zod.z.string(),
33
+ isAuthenticated: zod.z.boolean(),
34
+ userType: zod.z.enum(["SUPER_ADMIN", "ADMIN", "USER"]),
35
+ redirectURL: zod.z.url().optional(),
36
+ tokens: zod.z.object({
37
+ Nonce: zod.z.string(),
38
+ Bearer: zod.z.string(),
39
+ }),
40
+ }),
25
41
  });
26
42
  const ErrorMessageSchema = zod.z.object({
27
- error: zod.z.string(),
28
- });
29
- const TokenSchema = zod.z.object({
30
- access_token: zod.z.string(),
31
- refresh_token: zod.z.string().optional(),
32
- expires_in: zod.z.number(), // in seconds
33
- token_type: zod.z.string().default("Bearer"),
34
- id_token: zod.z.string().optional(),
43
+ error: zod.z.string().min(1, "Error message cannot be empty"),
35
44
  });
36
- const ProfileSchema = zod.z.object({
37
- sub: zod.z.string(), // user ID
38
- name: zod.z.string().optional(),
39
- email: zod.z.email({ message: "Invalid email address" }).optional(),
40
- given_name: zod.z.string().optional(),
41
- family_name: zod.z.string().optional(),
42
- roles: zod.z.array(zod.z.string()).optional(),
45
+ const AuthFailureMessageSchema = zod.z.object({
46
+ type: zod.z.literal("AUTH_FAILURE"),
47
+ error: zod.z.string().min(1, "Error message cannot be empty"),
48
+ errorCode: zod.z.string(),
49
+ errorDetails: zod.z.object().or(zod.z.any()),
43
50
  });
44
- // URL validation schema - only HTTPS for production security
45
- const URLSchema = zod.z.string().url().refine((url) => url.startsWith('https://'), { message: "Only HTTPS URLs are allowed" });
51
+ const URLSchema = zod.z.url();
46
52
 
53
+ exports.LogLevel = void 0;
54
+ (function (LogLevel) {
55
+ LogLevel[LogLevel["ERROR"] = 0] = "ERROR";
56
+ LogLevel[LogLevel["WARN"] = 1] = "WARN";
57
+ LogLevel[LogLevel["INFO"] = 2] = "INFO";
58
+ LogLevel[LogLevel["DEBUG"] = 3] = "DEBUG";
59
+ })(exports.LogLevel || (exports.LogLevel = {}));
60
+ class Logger {
61
+ static level = exports.LogLevel.WARN;
62
+ static prefix = '[CAMS-SDK]';
63
+ static isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';
64
+ static setLevel(level) {
65
+ Logger.level = level;
66
+ }
67
+ static sanitizeForLog(input) {
68
+ if (typeof input === 'string') {
69
+ // Remove newlines and control characters to prevent log injection
70
+ return input.replace(/[\r\n\t]/g, ' ').replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '');
71
+ }
72
+ if (typeof input === 'object' && input !== null) {
73
+ const sanitized = {};
74
+ for (const [key, value] of Object.entries(input)) {
75
+ sanitized[Logger.sanitizeForLog(key)] = Logger.sanitizeForLog(value);
76
+ }
77
+ return sanitized;
78
+ }
79
+ return input;
80
+ }
81
+ static error(message, context) {
82
+ if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.ERROR) {
83
+ console.error(`${Logger.prefix} ERROR:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
84
+ }
85
+ }
86
+ static warn(message, context) {
87
+ if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.WARN) {
88
+ console.warn(`${Logger.prefix} WARN:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
89
+ }
90
+ }
91
+ static info(message, context) {
92
+ if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.INFO) {
93
+ console.info(`${Logger.prefix} INFO:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
94
+ }
95
+ }
96
+ static debug(message, context) {
97
+ if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.DEBUG) {
98
+ console.debug(`${Logger.prefix} DEBUG:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
99
+ }
100
+ }
101
+ }
102
+
103
+ // Capture original functions to prevent tampering
104
+ const originalWindowOpen = window.open;
105
+ const originalAddEventListener = window.addEventListener;
106
+ const originalRemoveEventListener = window.removeEventListener;
107
+ const originalSetTimeout = window.setTimeout;
108
+ const originalClearTimeout = window.clearTimeout;
109
+ // Generate random window name to prevent targeting
110
+ const generateSecureWindowName = () => `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;
47
111
  function validateConfig(config) {
48
- var _a;
49
- // Validate URL format
112
+ // Validate URL format and parse once
50
113
  const urlValidation = URLSchema.safeParse(config.camsUrl);
51
114
  if (!urlValidation.success) {
52
- throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'Invalid CAMS URL format');
115
+ throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Invalid CAMS URL format");
53
116
  }
54
117
  // Domain validation is mandatory for security
55
- if (!((_a = config.allowedDomains) === null || _a === void 0 ? void 0 : _a.length)) {
56
- throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');
57
- }
58
- const url = new URL(config.camsUrl); // URLSchema already validated this
59
- const isAllowed = config.allowedDomains.some(domain => url.hostname === domain || url.hostname.endsWith('.' + domain));
60
- if (!isAllowed) {
61
- throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'URL not in allowed domains list');
118
+ if (!config.messageOrigin) {
119
+ throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Message Origin must be specified for security");
62
120
  }
121
+ const url = new URL(config.camsUrl);
122
+ return url;
63
123
  }
64
124
  function openCAMSPopUpLogin(config) {
65
125
  return new Promise((resolve, reject) => {
126
+ if (config.debug)
127
+ Logger.setLevel(exports.LogLevel.DEBUG);
128
+ Logger.info("Starting CAMS authentication", { url: config.camsUrl });
129
+ let validatedUrl;
66
130
  try {
67
- validateConfig(config);
131
+ validatedUrl = validateConfig(config);
132
+ Logger.debug("Config validation passed");
68
133
  }
69
134
  catch (error) {
135
+ Logger.error("Config validation failed", {
136
+ error: error instanceof Error ? error.message : "Unknown error",
137
+ });
70
138
  reject(error);
71
139
  return;
72
140
  }
73
- const { camsUrl, allowedOrigin, windowHeight, windowWidth, timeout = 300000 } = config;
141
+ const { messageOrigin, windowHeight, windowWidth, authTimeout = 300000, // 5 minutes as a final failsafe
142
+ idleTimeout = 120000, // 2 minutes of inactivity
143
+ } = config;
74
144
  let authWindow;
75
- let timeoutId = null;
145
+ let authTimeoutId = null;
146
+ let idleTimeoutId = null;
76
147
  let checkClosedInterval = null;
77
148
  try {
78
- authWindow = window.open(camsUrl, "NIBSS CAMS Login", `width=${windowWidth},height=${windowHeight}`);
149
+ Logger.debug("Opening popup window", {
150
+ width: windowWidth,
151
+ height: windowHeight,
152
+ });
153
+ // Center the popup window
154
+ const left = (window.screen.width - windowWidth) / 2;
155
+ const top = (window.screen.height - windowHeight) / 2;
156
+ const secureWindowName = generateSecureWindowName();
157
+ authWindow = originalWindowOpen.call(window, validatedUrl.toString(), secureWindowName, `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes`);
79
158
  }
80
159
  catch (error) {
81
- reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window: " + (error instanceof Error ? error.message : "Unknown error")));
160
+ Logger.error("Failed to open popup window", {
161
+ error: error instanceof Error ? error.message : "Unknown error",
162
+ });
163
+ reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
82
164
  return;
83
165
  }
84
166
  if (!authWindow) {
85
- reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window. Please allow popups."));
167
+ Logger.error("Popup window blocked");
168
+ reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
86
169
  return;
87
170
  }
171
+ // Only check for immediate closure (true popup blocking)
172
+ if (authWindow.closed) {
173
+ Logger.error("Popup immediately closed by blocker");
174
+ reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
175
+ return;
176
+ }
177
+ Logger.debug("Popup window opened successfully");
88
178
  const cleanup = () => {
89
- window.removeEventListener("message", listener);
90
- if (timeoutId)
91
- clearTimeout(timeoutId);
179
+ originalRemoveEventListener.call(window, "message", listener);
180
+ if (idleTimeoutId)
181
+ originalClearTimeout(idleTimeoutId);
182
+ if (authTimeoutId)
183
+ originalClearTimeout(authTimeoutId);
92
184
  if (checkClosedInterval)
93
- clearInterval(checkClosedInterval);
185
+ originalClearTimeout(checkClosedInterval);
186
+ idleTimeoutId = null;
187
+ authTimeoutId = null;
188
+ checkClosedInterval = null;
94
189
  };
95
- const cleanupAndClose = (error) => {
96
- cleanup();
97
- try {
98
- if (authWindow && !authWindow.closed) {
99
- authWindow.close();
100
- }
190
+ const listener = (event) => {
191
+ const messageEvent = event;
192
+ Logger.debug("Received message", {
193
+ origin: messageEvent.origin,
194
+ expectedOrigin: messageOrigin,
195
+ data: messageEvent.data,
196
+ });
197
+ const originUrl = new URL(messageEvent.origin);
198
+ const expectedHostname = messageOrigin.startsWith("http")
199
+ ? new URL(messageOrigin).hostname
200
+ : messageOrigin;
201
+ // Allow Microsoft redirect domains for Azure AD authentication
202
+ const isMicrosoftDomain = originUrl.hostname.endsWith(".microsoft.com") ||
203
+ originUrl.hostname.endsWith(".microsoftonline.com") ||
204
+ originUrl.hostname.endsWith(".live.com");
205
+ const isAllowedOrigin = originUrl.hostname === expectedHostname ||
206
+ originUrl.hostname.endsWith("." + expectedHostname) ||
207
+ isMicrosoftDomain;
208
+ if (!isAllowedOrigin) {
209
+ Logger.warn("Blocked message from unauthorized origin", {
210
+ origin: messageEvent.origin,
211
+ expected: messageOrigin,
212
+ data: messageEvent.data,
213
+ });
214
+ return;
101
215
  }
102
- catch {
103
- // Ignore close errors
216
+ // Validate event source
217
+ if (messageEvent.source !== authWindow) {
218
+ Logger.warn("Message from unexpected source", {
219
+ source: messageEvent.source,
220
+ origin: messageEvent.origin,
221
+ expected: messageOrigin,
222
+ data: messageEvent.data,
223
+ });
224
+ return;
104
225
  }
105
- if (error)
106
- reject(error);
107
- };
108
- const listener = (event) => {
109
- if (event.origin !== allowedOrigin) {
110
- // Sanitize origin for logging to prevent log injection
111
- const sanitizedOrigin = event.origin.replace(/[\r\n]/g, '');
112
- console.warn("Blocked message from origin:", sanitizedOrigin);
226
+ // Validate event source
227
+ if (messageEvent.source !== authWindow) {
228
+ Logger.warn("Message from unexpected source", {
229
+ source: messageEvent.source,
230
+ origin: messageEvent.origin,
231
+ expected: messageOrigin,
232
+ data: messageEvent.data,
233
+ });
234
+ return;
235
+ }
236
+ // Ignore heartbeat messages
237
+ if (messageEvent.data?.type === "heartbeat") {
238
+ Logger.debug("Received heartbeat message");
239
+ resetIdleTimeout();
113
240
  return;
114
241
  }
115
242
  // ✅ Validate payload
116
- const tokenMsg = TokenMessageSchema.safeParse(event.data);
243
+ const tokenMsg = ProfileSchema.safeParse(messageEvent.data);
117
244
  if (tokenMsg.success) {
245
+ Logger.info("Authentication successful");
118
246
  cleanupAndClose();
119
- resolve({ token: tokenMsg.data.access_token });
247
+ resolve(tokenMsg.data);
248
+ return;
249
+ }
250
+ const authFailureMsg = AuthFailureMessageSchema.safeParse(messageEvent.data);
251
+ if (authFailureMsg.success) {
252
+ Logger.warn("Authentication failure received", {
253
+ errorDetails: authFailureMsg.data.errorDetails,
254
+ error: authFailureMsg.data.error,
255
+ errorCode: authFailureMsg.data.errorCode,
256
+ });
257
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.API_VALIDATION_ERROR, "Authentication failed: " + authFailureMsg.data.error));
120
258
  return;
121
259
  }
122
- const errorMsg = ErrorMessageSchema.safeParse(event.data);
260
+ const errorMsg = ErrorMessageSchema.safeParse(messageEvent.data);
123
261
  if (errorMsg.success) {
262
+ Logger.warn("Authentication error received", {
263
+ error: errorMsg.data.error,
264
+ });
124
265
  cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication failed: " + errorMsg.data.error));
125
266
  return;
126
267
  }
268
+ Logger.error("Invalid message format received", {
269
+ messageData: messageEvent.data,
270
+ dataType: typeof messageEvent.data,
271
+ tokenValidationError: tokenMsg.error
272
+ ? tokenMsg.error.issues
273
+ : undefined,
274
+ errorValidationError: errorMsg.error
275
+ ? errorMsg.error.issues
276
+ : undefined,
277
+ });
127
278
  cleanupAndClose(new CAMSError(exports.CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
128
279
  };
129
- // Timeout handler
130
- timeoutId = setTimeout(() => {
131
- cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));
132
- }, timeout);
133
- checkClosedInterval = setInterval(() => {
134
- if (authWindow && authWindow.closed) {
280
+ const cleanupAndClose = (error) => {
281
+ cleanup();
282
+ try {
283
+ if (authWindow && !authWindow.closed) {
284
+ authWindow.close();
285
+ }
286
+ }
287
+ catch {
288
+ // Ignore close errors
289
+ }
290
+ if (error)
291
+ reject(error);
292
+ };
293
+ const resetIdleTimeout = () => {
294
+ // Timeout handler
295
+ if (idleTimeoutId)
296
+ originalClearTimeout(idleTimeoutId);
297
+ Logger.debug("Resetting idle timeout", { idleTimeout });
298
+ idleTimeoutId = originalSetTimeout(() => {
299
+ Logger.warn("Authentication idle timeout reached", { idleTimeout });
300
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timed out due to inactivity after ${idleTimeout}ms`));
301
+ }, idleTimeout);
302
+ };
303
+ Logger.debug("Setting auth timeout", { authTimeout });
304
+ authTimeoutId = originalSetTimeout(() => {
305
+ Logger.warn("Authentication auth timeout reached", { authTimeout });
306
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication process exceeded auth time limit of ${authTimeout}ms`));
307
+ }, authTimeout);
308
+ resetIdleTimeout();
309
+ // Use exponential backoff for popup closure checking
310
+ let pollInterval = 1000; // Start with 1 second
311
+ const maxPollInterval = 5000; // Max 5 seconds
312
+ const checkClosed = () => {
313
+ if (authWindow?.closed) {
314
+ Logger.info("Authentication window closed by user");
135
315
  cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
316
+ return;
136
317
  }
137
- }, 2000); // Reduced polling frequency
318
+ // Exponential backoff: increase interval up to max
319
+ pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);
320
+ checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);
321
+ };
322
+ checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);
138
323
  try {
139
- window.addEventListener("message", listener);
324
+ originalAddEventListener.call(window, "message", listener);
325
+ Logger.debug("Message listener attached");
140
326
  }
141
327
  catch (error) {
328
+ Logger.error("Failed to attach message listener", {
329
+ error: error instanceof Error ? error.message : "Unknown error",
330
+ });
142
331
  cleanup();
143
- reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " + (error instanceof Error ? error.message : "Unknown error")));
332
+ reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " +
333
+ (error instanceof Error ? error.message : "Unknown error")));
144
334
  return;
145
335
  }
146
- });
147
- }
148
-
149
- class TokenManager {
150
- constructor(storage = sessionStorage, storageKey = "cams_token") {
151
- this.storage = storage;
152
- this.token = null;
153
- this.storageKey = storageKey;
154
- }
155
- setToken(token) {
156
- const parsed = TokenSchema.parse(token);
157
- this.token = parsed;
158
- this.storage.setItem(this.storageKey, JSON.stringify(parsed));
159
- }
160
- loadToken() {
161
- if (this.token)
162
- return this.token;
163
- const raw = this.storage.getItem(this.storageKey);
164
- if (!raw)
165
- return null;
336
+ // Add focus to the popup for better UX
166
337
  try {
167
- const parsed = JSON.parse(raw);
168
- try {
169
- this.token = TokenSchema.parse(parsed);
170
- return this.token;
171
- }
172
- catch (validationError) {
173
- console.warn('Token validation failed:', validationError instanceof Error ? validationError.message : 'Unknown error');
174
- this.storage.removeItem(this.storageKey);
175
- return null;
338
+ if (authWindow && !authWindow.closed) {
339
+ authWindow.focus();
176
340
  }
177
341
  }
178
- catch (parseError) {
179
- console.warn('Failed to parse stored token JSON:', parseError instanceof Error ? parseError.message : 'Unknown error');
180
- this.storage.removeItem(this.storageKey);
181
- return null;
342
+ catch {
343
+ // Ignore focus errors (cross-origin restrictions)
182
344
  }
345
+ });
346
+ }
347
+
348
+ class CAMSSessionManager {
349
+ storage;
350
+ keyPrefix;
351
+ events;
352
+ token = null;
353
+ profile = null;
354
+ constructor(storage = null, keyPrefix, events = {}) {
355
+ this.storage = storage || getDefaultStorage();
356
+ this.keyPrefix = keyPrefix ?? "CAMS-SDK";
357
+ this.events = events;
183
358
  }
184
- clearToken() {
185
- this.token = null;
186
- this.storage.removeItem(this.storageKey);
359
+ setItem(key, value) {
360
+ this.storage.setItem(`${this.keyPrefix}:${key}`, value);
187
361
  }
188
- getAccessToken() {
189
- var _a;
190
- const token = this.loadToken();
191
- return (_a = token === null || token === void 0 ? void 0 : token.access_token) !== null && _a !== void 0 ? _a : null;
362
+ getItem(key) {
363
+ return this.storage.getItem(`${this.keyPrefix}:${key}`);
192
364
  }
193
- isExpired() {
194
- const token = this.loadToken();
195
- if (!token)
196
- return true;
197
- // JWT expiration check if available
198
- if (token.id_token) {
199
- try {
200
- const parts = token.id_token.split(".");
201
- if (parts.length < 3)
202
- return true; // Invalid JWT format
203
- const payload = JSON.parse(atob(parts[1]));
204
- const exp = payload.exp * 1000;
205
- return Date.now() > exp;
206
- }
207
- catch (error) {
208
- console.warn('Failed to parse JWT token:', error instanceof Error ? error.message : 'Unknown error');
209
- return true;
210
- }
211
- }
212
- // Fallback: return true for safety when expiration cannot be determined
213
- return true;
365
+ removeItem(key) {
366
+ this.storage.removeItem(`${this.keyPrefix}:${key}`);
214
367
  }
215
- }
216
-
217
- class CAMSSession {
218
- constructor(storage = sessionStorage, storageKey, events = {}) {
219
- this.tokenManager = new TokenManager(storage, storageKey);
220
- this.events = events;
368
+ clear() {
369
+ // clear only CAMS-prefixed items
370
+ Object.keys(this.storage).forEach((k) => {
371
+ if (k.startsWith(this.keyPrefix)) {
372
+ this.storage.removeItem(k);
373
+ }
374
+ });
221
375
  }
222
376
  async login(config) {
223
- var _a, _b, _c, _d, _e, _f, _g;
224
377
  try {
225
- (_b = (_a = this.events).onAuthStart) === null || _b === void 0 ? void 0 : _b.call(_a);
378
+ Logger.info("Session login started");
379
+ if (this.events.onAuthStart)
380
+ this.events.onAuthStart();
226
381
  let attempts = 0;
227
- const maxAttempts = ((_c = config.retryAttempts) !== null && _c !== void 0 ? _c : 0) + 1;
382
+ const maxAttempts = (config.retryAttempts ?? 0) + 1;
383
+ Logger.debug("Login retry configuration", { maxAttempts });
228
384
  while (attempts < maxAttempts) {
229
385
  try {
386
+ attempts++;
387
+ Logger.debug("Login attempt", { attempt: attempts, maxAttempts });
388
+ // Add exponential backoff delay for retries
389
+ if (attempts > 1) {
390
+ const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay
391
+ Logger.debug("Retry delay", { delay });
392
+ await new Promise((resolve) => setTimeout(resolve, delay));
393
+ }
230
394
  const response = await openCAMSPopUpLogin(config);
231
- (_e = (_d = this.events).onAuthSuccess) === null || _e === void 0 ? void 0 : _e.call(_d, response);
395
+ Logger.debug("Login Response", response);
396
+ this.profile = response;
397
+ this.setToken(response.userProfile.tokens.Bearer);
398
+ Logger.info("Session login successful");
399
+ if (this.events.onAuthSuccess)
400
+ this.events.onAuthSuccess(response);
232
401
  return response;
233
402
  }
234
403
  catch (error) {
235
- attempts++;
404
+ Logger.warn("Login attempt failed", {
405
+ attempt: attempts,
406
+ error: error instanceof Error ? error.message : "Unknown error",
407
+ });
236
408
  if (attempts >= maxAttempts || !(error instanceof CAMSError)) {
237
409
  throw error;
238
410
  }
@@ -240,81 +412,165 @@ class CAMSSession {
240
412
  if (![exports.CAMSErrorType.TIMEOUT, exports.CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {
241
413
  throw error;
242
414
  }
415
+ Logger.info("Retrying login", { nextAttempt: attempts + 1 });
243
416
  }
244
417
  }
245
- throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED, 'Max retry attempts exceeded');
418
+ throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED, "Max retry attempts exceeded");
246
419
  }
247
420
  catch (error) {
248
- const camsError = error instanceof CAMSError ? error :
249
- new CAMSError(exports.CAMSErrorType.USER_CANCELLED, error instanceof Error ? error.message : 'Unknown error');
250
- (_g = (_f = this.events).onAuthError) === null || _g === void 0 ? void 0 : _g.call(_f, camsError);
421
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
422
+ const camsError = error instanceof CAMSError
423
+ ? error
424
+ : new CAMSError(exports.CAMSErrorType.USER_CANCELLED, errorMessage);
425
+ Logger.error("Session login failed", {
426
+ error: camsError.message,
427
+ type: camsError.type,
428
+ });
429
+ if (this.events.onAuthError)
430
+ this.events.onAuthError(camsError);
251
431
  throw camsError;
252
432
  }
253
433
  }
254
434
  async logout() {
255
- this.tokenManager.clearToken();
435
+ Logger.info("Session logout");
436
+ this.clearToken();
256
437
  }
257
- isAuthenticated() {
258
- var _a, _b;
259
- const token = this.tokenManager.loadToken();
438
+ setToken(token) {
439
+ this.token = token;
440
+ this.storage.setItem(this.keyPrefix, token);
441
+ Logger.debug("Token stored", { storageKey: this.keyPrefix });
442
+ }
443
+ getAccessToken() {
444
+ // Return cached token if available, avoiding redundant storage access
445
+ if (this.token)
446
+ return this.token;
447
+ const raw = this.storage.getItem(this.keyPrefix);
448
+ if (!raw)
449
+ return null;
450
+ this.token = raw;
451
+ Logger.debug("Token loaded from storage");
452
+ return this.token;
453
+ }
454
+ clearToken() {
455
+ this.token = null;
456
+ this.storage.removeItem(this.keyPrefix);
457
+ Logger.debug("Token cleared");
458
+ }
459
+ isExpired() {
460
+ const token = this.getAccessToken();
260
461
  if (!token)
261
- return false;
262
- if (this.tokenManager.isExpired()) {
263
- (_b = (_a = this.events).onTokenExpired) === null || _b === void 0 ? void 0 : _b.call(_a);
264
- return false;
462
+ return true;
463
+ try {
464
+ const parts = token.split(".");
465
+ if (parts.length < 3)
466
+ return true; // Invalid JWT format
467
+ const payload = JSON.parse(atob(parts[1]));
468
+ if (typeof payload.exp !== "number")
469
+ return true;
470
+ const exp = payload.exp * 1000;
471
+ return Date.now() > exp;
472
+ }
473
+ catch (error) {
474
+ Logger.warn("Failed to parse JWT token", {
475
+ error: error instanceof Error ? error.message : "Unknown error",
476
+ });
477
+ return true;
265
478
  }
266
- return true;
267
479
  }
268
- getAccessToken() {
269
- var _a, _b;
270
- const token = this.tokenManager.loadToken();
480
+ isPaddedExpired() {
481
+ const token = this.getAccessToken();
271
482
  if (!token)
272
- return null;
273
- if (this.tokenManager.isExpired()) {
274
- (_b = (_a = this.events).onTokenExpired) === null || _b === void 0 ? void 0 : _b.call(_a);
275
- return null;
483
+ return true;
484
+ try {
485
+ const parts = token.split(".");
486
+ if (parts.length < 3)
487
+ return true; // Invalid JWT format
488
+ const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
489
+ const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=");
490
+ const payload = JSON.parse(atob(padded));
491
+ if (typeof payload.exp !== "number")
492
+ return true;
493
+ const exp = payload.exp * 1000;
494
+ return Date.now() > exp;
495
+ }
496
+ catch (error) {
497
+ Logger.warn("Failed to parse JWT token", {
498
+ error: error instanceof Error ? error.message : "Unknown error",
499
+ });
500
+ return true;
501
+ }
502
+ }
503
+ checkTokenExpiration() {
504
+ if (this.isExpired()) {
505
+ Logger.info("Token expired");
506
+ if (this.events.onTokenExpired)
507
+ this.events.onTokenExpired();
508
+ return true;
276
509
  }
277
- return token.access_token;
510
+ return false;
511
+ }
512
+ isAuthenticated() {
513
+ const token = this.getAccessToken();
514
+ if (!token) {
515
+ Logger.debug("No token found");
516
+ return false;
517
+ }
518
+ if (this.checkTokenExpiration()) {
519
+ return false;
520
+ }
521
+ Logger.debug("Token is valid");
522
+ return true;
278
523
  }
279
524
  decodeBase64Url(str) {
280
- // Convert base64url to base64
281
- str = str.replace(/-/g, '+').replace(/_/g, '/');
525
+ // Work with a copy to avoid mutating input
526
+ let result = str.replace(/-/g, "+").replace(/_/g, "/");
282
527
  // Add padding if needed
283
- while (str.length % 4) {
284
- str += '=';
528
+ while (result.length % 4) {
529
+ result += "=";
285
530
  }
286
- return atob(str);
531
+ return atob(result);
287
532
  }
288
533
  async getProfile() {
289
- const storedToken = this.tokenManager.loadToken();
290
- if (!(storedToken === null || storedToken === void 0 ? void 0 : storedToken.id_token))
534
+ const storedToken = this.getAccessToken();
535
+ if (!storedToken)
536
+ return null;
537
+ // Check token expiration before processing
538
+ if (this.checkTokenExpiration()) {
291
539
  return null;
292
- try {
293
- const parts = storedToken.id_token.split('.');
294
- if (parts.length >= 3) { // JWT has header.payload.signature format
295
- try {
296
- const payload = JSON.parse(this.decodeBase64Url(parts[1]));
297
- return ProfileSchema.parse(payload);
298
- }
299
- catch (decodeError) {
300
- console.warn('Failed to decode JWT payload:', decodeError instanceof Error ? decodeError.message : 'Unknown error');
301
- }
302
- }
303
- }
304
- catch (error) {
305
- console.warn('Failed to extract profile from token:', error instanceof Error ? error.message : 'Unknown error');
306
540
  }
541
+ return this.profile;
542
+ }
543
+ getSessionError() {
307
544
  return null;
308
545
  }
309
546
  }
547
+ // 🔹 Safe fallback for Node/SSR
548
+ function getDefaultStorage() {
549
+ if (typeof window !== "undefined" && window.localStorage) {
550
+ return window.localStorage;
551
+ }
552
+ const memoryStore = {};
553
+ return {
554
+ getItem: (key) => (key in memoryStore ? memoryStore[key] : null),
555
+ setItem: (key, value) => {
556
+ memoryStore[key] = value;
557
+ },
558
+ removeItem: (key) => {
559
+ delete memoryStore[key];
560
+ },
561
+ key: (i) => Object.keys(memoryStore)[i] ?? null,
562
+ get length() {
563
+ return Object.keys(memoryStore).length;
564
+ },
565
+ };
566
+ }
310
567
 
568
+ exports.AuthFailureMessageSchema = AuthFailureMessageSchema;
311
569
  exports.CAMSError = CAMSError;
312
- exports.CAMSSession = CAMSSession;
570
+ exports.CAMSSessionManager = CAMSSessionManager;
313
571
  exports.ErrorMessageSchema = ErrorMessageSchema;
572
+ exports.Logger = Logger;
314
573
  exports.ProfileSchema = ProfileSchema;
315
- exports.TokenManager = TokenManager;
316
- exports.TokenMessageSchema = TokenMessageSchema;
317
- exports.TokenSchema = TokenSchema;
318
574
  exports.URLSchema = URLSchema;
319
575
  exports.openCAMSPopUpLogin = openCAMSPopUpLogin;
320
576
  exports.validateConfig = validateConfig;