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