@nibssplc/cams-sdk 0.0.1-beta.12 → 0.0.1-beta.14

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
@@ -12,18 +12,25 @@
12
12
  CAMSErrorType["USER_CANCELLED"] = "USER_CANCELLED";
13
13
  CAMSErrorType["INVALID_URL"] = "INVALID_URL";
14
14
  CAMSErrorType["MAX_RETRIES_EXCEEDED"] = "MAX_RETRIES_EXCEEDED";
15
+ CAMSErrorType["API_VALIDATION_ERROR"] = "API_VALIDATION_ERROR";
15
16
  })(exports.CAMSErrorType || (exports.CAMSErrorType = {}));
16
17
  class CAMSError extends Error {
18
+ type;
17
19
  constructor(type, message) {
18
20
  super(message);
19
21
  this.type = type;
20
- this.name = 'CAMSError';
22
+ this.name = this.constructor.name;
21
23
  }
22
24
  }
23
25
 
24
- // Validate the returned token - Base64 format with minimum 20 chars
26
+ // Validate the returned token - non-empty string
25
27
  const TokenMessageSchema = zod.z.object({
26
- access_token: zod.z.string().min(1, "NIBSS CAMS Access token cannot be empty"),
28
+ type: zod.z.literal("AUTH_SUCCESS"),
29
+ accessToken: zod.z.string().min(1, "Access token cannot be empty"),
30
+ user: zod.z.object({
31
+ name: zod.z.string(),
32
+ image: zod.z.string().nullable(),
33
+ }).optional(),
27
34
  });
28
35
  const ErrorMessageSchema = zod.z.object({
29
36
  error: zod.z.string().min(1, "Error message cannot be empty"),
@@ -43,14 +50,7 @@
43
50
  family_name: zod.z.string().optional(),
44
51
  roles: zod.z.array(zod.z.string()).optional(),
45
52
  });
46
- // Matches IPv4 addresses like 192.168.x.x, 10.x.x.x, 172.16–31.x.x
47
- const internalIpRegex = /^(http:\/\/|https:\/\/)((10\.\d{1,3}\.\d{1,3}\.\d{1,3})|(192\.168\.\d{1,3}\.\d{1,3})|(172\.(1[6-9]|2\d|3[0-1])\.\d{1,3}\.\d{1,3}))(:\d+)?$/;
48
- const URLSchema = zod.z.url().refine((url) => url.startsWith("https://") || // normal HTTPS
49
- /^http:\/\/localhost(:\d+)?$/i.test(url) || // localhost
50
- internalIpRegex.test(url), // internal LAN IPs
51
- {
52
- message: "Only HTTPS, http://localhost, or internal IPs (192.168.x.x, 10.x.x.x, 172.16–31.x.x) are allowed",
53
- });
53
+ const URLSchema = zod.z.url();
54
54
 
55
55
  exports.LogLevel = void 0;
56
56
  (function (LogLevel) {
@@ -60,185 +60,256 @@
60
60
  LogLevel[LogLevel["DEBUG"] = 3] = "DEBUG";
61
61
  })(exports.LogLevel || (exports.LogLevel = {}));
62
62
  class Logger {
63
+ static level = exports.LogLevel.WARN;
64
+ static prefix = '[CAMS-SDK]';
65
+ static isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';
63
66
  static setLevel(level) {
64
67
  Logger.level = level;
65
68
  }
69
+ static sanitizeForLog(input) {
70
+ if (typeof input === 'string') {
71
+ // Remove newlines and control characters to prevent log injection
72
+ return input.replace(/[\r\n\t]/g, ' ').replace(/[\x00-\x1F\x7F]/g, '');
73
+ }
74
+ if (typeof input === 'object' && input !== null) {
75
+ const sanitized = {};
76
+ for (const [key, value] of Object.entries(input)) {
77
+ sanitized[Logger.sanitizeForLog(key)] = Logger.sanitizeForLog(value);
78
+ }
79
+ return sanitized;
80
+ }
81
+ return input;
82
+ }
66
83
  static error(message, context) {
67
84
  if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.ERROR) {
68
- console.error(`${Logger.prefix} ERROR:`, message, context || '');
85
+ console.error(`${Logger.prefix} ERROR:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
69
86
  }
70
87
  }
71
88
  static warn(message, context) {
72
89
  if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.WARN) {
73
- console.warn(`${Logger.prefix} WARN:`, message, context || '');
90
+ console.warn(`${Logger.prefix} WARN:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
74
91
  }
75
92
  }
76
93
  static info(message, context) {
77
94
  if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.INFO) {
78
- console.info(`${Logger.prefix} INFO:`, message, context || '');
95
+ console.info(`${Logger.prefix} INFO:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
79
96
  }
80
97
  }
81
98
  static debug(message, context) {
82
99
  if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.DEBUG) {
83
- console.debug(`${Logger.prefix} DEBUG:`, message, context || '');
100
+ console.debug(`${Logger.prefix} DEBUG:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
84
101
  }
85
102
  }
86
103
  }
87
- Logger.level = exports.LogLevel.WARN;
88
- Logger.prefix = '[CAMS-SDK]';
89
- Logger.isTestEnv = typeof process !== 'undefined' && process.env?.NODE_ENV === 'test';
90
104
 
91
105
  function validateConfig(config) {
92
- // Validate URL format
106
+ // Validate URL format and parse once
93
107
  const urlValidation = URLSchema.safeParse(config.camsUrl);
94
108
  if (!urlValidation.success) {
95
- throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'Invalid CAMS URL format');
109
+ throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Invalid CAMS URL format");
96
110
  }
97
111
  // Domain validation is mandatory for security
98
- if (!config.allowedDomains?.length) {
99
- throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');
100
- }
101
- const url = new URL(config.camsUrl); // URLSchema already validated this
102
- const isAllowed = config.allowedDomains.some(domain => url.hostname === domain || url.hostname.endsWith('.' + domain));
103
- if (!isAllowed) {
104
- throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'URL not in allowed domains list');
112
+ if (!config.messageOrigin) {
113
+ throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Message Origin must be specified for security");
105
114
  }
115
+ const url = new URL(config.camsUrl);
116
+ return url;
106
117
  }
107
118
  function openCAMSPopUpLogin(config) {
108
119
  return new Promise((resolve, reject) => {
109
120
  if (config.debug)
110
121
  Logger.setLevel(exports.LogLevel.DEBUG);
111
- Logger.info('Starting CAMS authentication', { url: config.camsUrl });
122
+ Logger.info("Starting CAMS authentication", { url: config.camsUrl });
123
+ let validatedUrl;
112
124
  try {
113
- validateConfig(config);
114
- Logger.debug('Config validation passed');
125
+ validatedUrl = validateConfig(config);
126
+ Logger.debug("Config validation passed");
115
127
  }
116
128
  catch (error) {
117
- Logger.error('Config validation failed', { error: error instanceof Error ? error.message : 'Unknown error' });
129
+ Logger.error("Config validation failed", {
130
+ error: error instanceof Error ? error.message : "Unknown error",
131
+ });
118
132
  reject(error);
119
133
  return;
120
134
  }
121
- const { camsUrl, allowedOrigin, windowHeight, windowWidth, timeout = 300000 } = config;
135
+ const { messageOrigin, windowHeight, windowWidth, authTimeout = 300000, // 5 minutes as a final failsafe
136
+ idleTimeout = 60000, // 1 minute of inactivity
137
+ } = config;
122
138
  let authWindow;
123
- let timeoutId = null;
139
+ let authTimeoutId = null;
140
+ let idleTimeoutId = null;
124
141
  let checkClosedInterval = null;
125
142
  try {
126
- Logger.debug('Opening popup window', { width: windowWidth, height: windowHeight });
127
- authWindow = window.open(camsUrl, "NIBSS CAMS Login", `width=${windowWidth},height=${windowHeight}`);
143
+ Logger.debug("Opening popup window", {
144
+ width: windowWidth,
145
+ height: windowHeight,
146
+ });
147
+ // Center the popup window
148
+ const left = (window.screen.width - windowWidth) / 2;
149
+ const top = (window.screen.height - windowHeight) / 2;
150
+ authWindow = window.open(validatedUrl.toString(), "_blank", `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes`);
128
151
  }
129
152
  catch (error) {
130
- Logger.error('Failed to open popup window', { error: error instanceof Error ? error.message : 'Unknown error' });
131
- reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window: " + (error instanceof Error ? error.message : "Unknown error")));
153
+ Logger.error("Failed to open popup window", {
154
+ error: error instanceof Error ? error.message : "Unknown error",
155
+ });
156
+ reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window: " +
157
+ (error instanceof Error ? error.message : "Unknown error")));
132
158
  return;
133
159
  }
134
160
  if (!authWindow) {
135
- Logger.error('Popup window blocked');
161
+ Logger.error("Popup window blocked");
136
162
  reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window. Please allow popups."));
137
163
  return;
138
164
  }
139
- Logger.debug('Popup window opened successfully');
165
+ Logger.debug("Popup window opened successfully");
140
166
  const cleanup = () => {
141
167
  window.removeEventListener("message", listener);
142
- if (timeoutId)
143
- clearTimeout(timeoutId);
168
+ if (idleTimeoutId)
169
+ clearTimeout(idleTimeoutId);
170
+ if (authTimeoutId)
171
+ clearTimeout(authTimeoutId);
144
172
  if (checkClosedInterval)
145
- clearInterval(checkClosedInterval);
146
- };
147
- const cleanupAndClose = (error) => {
148
- cleanup();
149
- try {
150
- if (authWindow && !authWindow.closed) {
151
- authWindow.close();
152
- }
153
- }
154
- catch {
155
- // Ignore close errors
156
- }
157
- if (error)
158
- reject(error);
173
+ clearTimeout(checkClosedInterval);
174
+ idleTimeoutId = null;
175
+ authTimeoutId = null;
176
+ checkClosedInterval = null;
159
177
  };
160
178
  const listener = (event) => {
161
- Logger.debug('Received message', { origin: event.origin, expectedOrigin: allowedOrigin, data: event.data });
162
- if (event.origin !== allowedOrigin) {
163
- Logger.warn('Blocked message from unauthorized origin', { origin: event.origin, expected: allowedOrigin });
179
+ Logger.debug("Received message", {
180
+ origin: event.origin,
181
+ expectedOrigin: messageOrigin,
182
+ data: event.data,
183
+ });
184
+ const originUrl = new URL(event.origin);
185
+ const isAllowedOrigin = originUrl.hostname === messageOrigin ||
186
+ originUrl.hostname.endsWith("." + messageOrigin);
187
+ if (!isAllowedOrigin) {
188
+ Logger.warn("Blocked message from unauthorized origin", {
189
+ origin: event.origin,
190
+ expected: messageOrigin,
191
+ });
164
192
  return;
165
193
  }
166
194
  // ✅ Validate payload
167
195
  const tokenMsg = TokenMessageSchema.safeParse(event.data);
168
196
  if (tokenMsg.success) {
169
- Logger.info('Authentication successful');
197
+ Logger.info("Authentication successful");
170
198
  cleanupAndClose();
171
- resolve({ token: tokenMsg.data.access_token });
199
+ resolve({ token: tokenMsg.data.accessToken });
172
200
  return;
173
201
  }
174
202
  const errorMsg = ErrorMessageSchema.safeParse(event.data);
175
203
  if (errorMsg.success) {
176
- Logger.warn('Authentication error received', { error: errorMsg.data.error });
204
+ Logger.warn("Authentication error received", {
205
+ error: errorMsg.data.error,
206
+ });
177
207
  cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication failed: " + errorMsg.data.error));
178
208
  return;
179
209
  }
180
- Logger.error('Invalid message format received', {
210
+ Logger.error("Invalid message format received", {
181
211
  messageData: event.data,
182
212
  dataType: typeof event.data,
183
- tokenValidationError: tokenMsg.error?.issues,
184
- errorValidationError: errorMsg.error?.issues
213
+ tokenValidationError: tokenMsg.error
214
+ ? tokenMsg.error.issues
215
+ : undefined,
216
+ errorValidationError: errorMsg.error
217
+ ? errorMsg.error.issues
218
+ : undefined,
185
219
  });
186
220
  cleanupAndClose(new CAMSError(exports.CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
187
221
  };
188
- // Timeout handler
189
- Logger.debug('Setting timeout', { timeout });
190
- timeoutId = setTimeout(() => {
191
- Logger.warn('Authentication timeout', { timeout });
192
- cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));
193
- }, timeout);
194
- checkClosedInterval = setInterval(() => {
195
- if (authWindow && authWindow.closed) {
196
- Logger.info('Authentication window closed by user');
222
+ const cleanupAndClose = (error) => {
223
+ cleanup();
224
+ try {
225
+ if (authWindow && !authWindow.closed) {
226
+ authWindow.close();
227
+ }
228
+ }
229
+ catch {
230
+ // Ignore close errors
231
+ }
232
+ if (error)
233
+ reject(error);
234
+ };
235
+ const resetIdleTimeout = () => {
236
+ // Timeout handler
237
+ if (idleTimeoutId)
238
+ clearTimeout(idleTimeoutId);
239
+ Logger.debug("Resetting idle timeout", { idleTimeout });
240
+ idleTimeoutId = setTimeout(() => {
241
+ Logger.warn("Authentication idle timeout reached", { idleTimeout });
242
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timed out due to inactivity after ${idleTimeout}ms`));
243
+ }, idleTimeout);
244
+ };
245
+ Logger.debug("Setting auth timeout", { authTimeout });
246
+ authTimeoutId = setTimeout(() => {
247
+ Logger.warn("Authentication auth timeout reached", { authTimeout });
248
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication process exceeded auth time limit of ${authTimeout}ms`));
249
+ }, authTimeout);
250
+ resetIdleTimeout();
251
+ // Use exponential backoff for popup closure checking
252
+ let pollInterval = 1000; // Start with 1 second
253
+ const maxPollInterval = 5000; // Max 5 seconds
254
+ const checkClosed = () => {
255
+ if (authWindow?.closed) {
256
+ Logger.info("Authentication window closed by user");
197
257
  cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
258
+ return;
198
259
  }
199
- }, 2000); // Reduced polling frequency
260
+ // Exponential backoff: increase interval up to max
261
+ pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);
262
+ checkClosedInterval = setTimeout(checkClosed, pollInterval);
263
+ };
264
+ checkClosedInterval = setTimeout(checkClosed, pollInterval);
200
265
  try {
201
266
  window.addEventListener("message", listener);
267
+ Logger.debug("Message listener attached");
202
268
  }
203
269
  catch (error) {
270
+ Logger.error("Failed to attach message listener", {
271
+ error: error instanceof Error ? error.message : "Unknown error",
272
+ });
204
273
  cleanup();
205
- reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " + (error instanceof Error ? error.message : "Unknown error")));
274
+ reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " +
275
+ (error instanceof Error ? error.message : "Unknown error")));
206
276
  return;
207
277
  }
278
+ // Add focus to the popup for better UX
279
+ try {
280
+ if (authWindow) {
281
+ authWindow.focus();
282
+ }
283
+ }
284
+ catch {
285
+ // Ignore focus errors (cross-origin restrictions)
286
+ }
208
287
  });
209
288
  }
210
289
 
211
290
  class TokenManager {
291
+ storage;
292
+ token = null;
293
+ storageKey;
212
294
  constructor(storage = sessionStorage, storageKey) {
213
295
  this.storage = storage;
214
- this.token = null;
215
296
  this.storageKey = storageKey || "cams_token";
216
297
  }
217
298
  setToken(token) {
218
- const parsed = TokenMessageSchema.parse(token);
219
- this.storage.setItem(this.storageKey, parsed.access_token);
299
+ this.token = token;
300
+ this.storage.setItem(this.storageKey, token);
220
301
  Logger.debug("Token stored", { storageKey: this.storageKey });
221
302
  }
222
303
  loadToken() {
304
+ // Return cached token if available
223
305
  if (this.token)
224
306
  return this.token;
225
307
  const raw = this.storage.getItem(this.storageKey);
226
308
  if (!raw)
227
309
  return null;
228
- try {
229
- this.token = TokenMessageSchema.parse(raw).access_token;
230
- Logger.debug("Token loaded from storage");
231
- return this.token;
232
- }
233
- catch (validationError) {
234
- Logger.warn("Token validation failed", {
235
- error: validationError instanceof Error
236
- ? validationError.message
237
- : "Unknown error",
238
- });
239
- this.storage.removeItem(this.storageKey);
240
- return null;
241
- }
310
+ this.token = raw;
311
+ Logger.debug("Token loaded from storage");
312
+ return this.token;
242
313
  }
243
314
  clearToken() {
244
315
  this.token = null;
@@ -246,38 +317,37 @@
246
317
  Logger.debug("Token cleared");
247
318
  }
248
319
  getAccessToken() {
249
- const token = this.loadToken();
250
- return token;
320
+ // Return cached token if available, avoiding redundant storage access
321
+ if (this.token)
322
+ return this.token;
323
+ return this.loadToken();
251
324
  }
252
325
  isExpired() {
253
326
  const token = this.loadToken();
254
327
  if (!token)
255
328
  return true;
256
- // JWT expiration check if available
257
- if (token) {
258
- try {
259
- const parts = token.split(".");
260
- if (parts.length < 3)
261
- return true; // Invalid JWT format
262
- const payload = JSON.parse(atob(parts[1]));
263
- if (typeof payload.exp !== "number")
264
- return true;
265
- const exp = payload.exp * 1000;
266
- return Date.now() > exp;
267
- }
268
- catch (error) {
269
- Logger.warn("Failed to parse JWT token", {
270
- error: error instanceof Error ? error.message : "Unknown error",
271
- });
329
+ try {
330
+ const parts = token.split(".");
331
+ if (parts.length < 3)
332
+ return true; // Invalid JWT format
333
+ const payload = JSON.parse(atob(parts[1]));
334
+ if (typeof payload.exp !== "number")
272
335
  return true;
273
- }
336
+ const exp = payload.exp * 1000;
337
+ return Date.now() > exp;
338
+ }
339
+ catch (error) {
340
+ Logger.warn("Failed to parse JWT token", {
341
+ error: error instanceof Error ? error.message : "Unknown error",
342
+ });
343
+ return true;
274
344
  }
275
- // Fallback: return true for safety when expiration cannot be determined
276
- return true;
277
345
  }
278
346
  }
279
347
 
280
- class CAMSSession {
348
+ class CAMSSessionManager {
349
+ tokenManager;
350
+ events;
281
351
  constructor(storage = sessionStorage, storageKey, events = {}) {
282
352
  this.tokenManager = new TokenManager(storage, storageKey);
283
353
  this.events = events;
@@ -285,17 +355,27 @@
285
355
  async login(config) {
286
356
  try {
287
357
  Logger.info('Session login started');
288
- this.events.onAuthStart && this.events.onAuthStart();
358
+ if (this.events.onAuthStart)
359
+ this.events.onAuthStart();
289
360
  let attempts = 0;
290
- const maxAttempts = (config.retryAttempts ?? 0) + 1;
361
+ const maxAttempts = (config.retryAttempts !== undefined ? config.retryAttempts : 0) + 1;
291
362
  Logger.debug('Login retry configuration', { maxAttempts });
292
363
  while (attempts < maxAttempts) {
293
364
  try {
294
365
  attempts++;
295
366
  Logger.debug('Login attempt', { attempt: attempts, maxAttempts });
367
+ // Add exponential backoff delay for retries
368
+ if (attempts > 1) {
369
+ const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay
370
+ Logger.debug('Retry delay', { delay });
371
+ await new Promise(resolve => setTimeout(resolve, delay));
372
+ }
296
373
  const response = await openCAMSPopUpLogin(config);
374
+ Logger.debug('Login Response', response);
375
+ this.tokenManager.setToken(response.token);
297
376
  Logger.info('Session login successful');
298
- this.events.onAuthSuccess && this.events.onAuthSuccess(response);
377
+ if (this.events.onAuthSuccess)
378
+ this.events.onAuthSuccess(response);
299
379
  return response;
300
380
  }
301
381
  catch (error) {
@@ -313,10 +393,12 @@
313
393
  throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED, 'Max retry attempts exceeded');
314
394
  }
315
395
  catch (error) {
396
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
316
397
  const camsError = error instanceof CAMSError ? error :
317
- new CAMSError(exports.CAMSErrorType.USER_CANCELLED, error instanceof Error ? error.message : 'Unknown error');
398
+ new CAMSError(exports.CAMSErrorType.USER_CANCELLED, errorMessage);
318
399
  Logger.error('Session login failed', { error: camsError.message, type: camsError.type });
319
- this.events.onAuthError && this.events.onAuthError(camsError);
400
+ if (this.events.onAuthError)
401
+ this.events.onAuthError(camsError);
320
402
  throw camsError;
321
403
  }
322
404
  }
@@ -324,15 +406,22 @@
324
406
  Logger.info('Session logout');
325
407
  this.tokenManager.clearToken();
326
408
  }
409
+ checkTokenExpiration() {
410
+ if (this.tokenManager.isExpired()) {
411
+ Logger.info('Token expired');
412
+ if (this.events.onTokenExpired)
413
+ this.events.onTokenExpired();
414
+ return true;
415
+ }
416
+ return false;
417
+ }
327
418
  isAuthenticated() {
328
419
  const token = this.tokenManager.loadToken();
329
420
  if (!token) {
330
421
  Logger.debug('No token found');
331
422
  return false;
332
423
  }
333
- if (this.tokenManager.isExpired()) {
334
- Logger.info('Token expired');
335
- this.events.onTokenExpired?.();
424
+ if (this.checkTokenExpiration()) {
336
425
  return false;
337
426
  }
338
427
  Logger.debug('Token is valid');
@@ -342,25 +431,28 @@
342
431
  const token = this.tokenManager.loadToken();
343
432
  if (!token)
344
433
  return null;
345
- if (this.tokenManager.isExpired()) {
346
- this.events.onTokenExpired?.();
434
+ if (this.checkTokenExpiration()) {
347
435
  return null;
348
436
  }
349
437
  return token;
350
438
  }
351
439
  decodeBase64Url(str) {
352
- // Convert base64url to base64
353
- str = str.replace(/-/g, '+').replace(/_/g, '/');
440
+ // Work with a copy to avoid mutating input
441
+ let result = str.replace(/-/g, '+').replace(/_/g, '/');
354
442
  // Add padding if needed
355
- while (str.length % 4) {
356
- str += '=';
443
+ while (result.length % 4) {
444
+ result += '=';
357
445
  }
358
- return atob(str);
446
+ return atob(result);
359
447
  }
360
448
  async getProfile() {
361
449
  const storedToken = this.tokenManager.loadToken();
362
450
  if (!storedToken)
363
451
  return null;
452
+ // Check token expiration before processing
453
+ if (this.checkTokenExpiration()) {
454
+ return null;
455
+ }
364
456
  try {
365
457
  const parts = storedToken.split('.');
366
458
  if (parts.length >= 3) { // JWT has header.payload.signature format
@@ -381,7 +473,7 @@
381
473
  }
382
474
 
383
475
  exports.CAMSError = CAMSError;
384
- exports.CAMSSession = CAMSSession;
476
+ exports.CAMSSessionManager = CAMSSessionManager;
385
477
  exports.ErrorMessageSchema = ErrorMessageSchema;
386
478
  exports.Logger = Logger;
387
479
  exports.ProfileSchema = ProfileSchema;