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