@nibssplc/cams-sdk 0.0.1-beta.2 → 0.0.1-beta.20

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