@nibssplc/cams-sdk 0.0.1-beta.2 → 0.0.1-beta.21
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 +107 -18
- package/dist/auth.d.ts +1 -1
- package/dist/index.cjs.js +418 -159
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.esm.js +416 -158
- package/dist/index.esm.js.map +1 -1
- package/dist/index.umd.js +418 -159
- package/dist/index.umd.js.map +1 -1
- package/dist/logger.d.ts +20 -0
- package/dist/sessionManager.d.ts +37 -0
- package/dist/types.d.ts +6 -4
- package/dist/validators.d.ts +13 -2
- package/package.json +13 -4
- package/dist/session.d.ts +0 -19
- package/dist/tokenManager.d.ts +0 -12
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 =
|
|
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
|
-
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,340 @@ const ProfileSchema = z.object({
|
|
|
39
51
|
family_name: z.string().optional(),
|
|
40
52
|
roles: z.array(z.string()).optional(),
|
|
41
53
|
});
|
|
42
|
-
|
|
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
|
-
|
|
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,
|
|
118
|
+
throw new CAMSError(CAMSErrorType.INVALID_URL, "Invalid CAMS URL format");
|
|
51
119
|
}
|
|
52
120
|
// Domain validation is mandatory for security
|
|
53
|
-
if (!
|
|
54
|
-
throw new CAMSError(CAMSErrorType.INVALID_URL,
|
|
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 {
|
|
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
|
|
148
|
+
let authTimeoutId = null;
|
|
149
|
+
let idleTimeoutId = null;
|
|
74
150
|
let checkClosedInterval = null;
|
|
75
151
|
try {
|
|
76
|
-
|
|
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
|
-
|
|
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
|
-
|
|
88
|
-
if (
|
|
89
|
-
|
|
177
|
+
originalRemoveEventListener.call(window, "message", listener);
|
|
178
|
+
if (idleTimeoutId)
|
|
179
|
+
originalClearTimeout(idleTimeoutId);
|
|
180
|
+
if (authTimeoutId)
|
|
181
|
+
originalClearTimeout(authTimeoutId);
|
|
90
182
|
if (checkClosedInterval)
|
|
91
|
-
|
|
183
|
+
originalClearTimeout(checkClosedInterval);
|
|
184
|
+
idleTimeoutId = null;
|
|
185
|
+
authTimeoutId = null;
|
|
186
|
+
checkClosedInterval = null;
|
|
92
187
|
};
|
|
93
|
-
const
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
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
|
-
|
|
101
|
-
|
|
214
|
+
// Validate event source
|
|
215
|
+
if (messageEvent.source !== authWindow) {
|
|
216
|
+
Logger.warn("Message from unexpected source", { source: messageEvent.source });
|
|
217
|
+
return;
|
|
102
218
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
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);
|
|
219
|
+
// Ignore heartbeat messages
|
|
220
|
+
if (messageEvent.data?.type === 'heartbeat') {
|
|
221
|
+
Logger.debug("Received heartbeat message");
|
|
222
|
+
resetIdleTimeout();
|
|
111
223
|
return;
|
|
112
224
|
}
|
|
113
225
|
// ✅ Validate payload
|
|
114
|
-
const tokenMsg = TokenMessageSchema.safeParse(
|
|
226
|
+
const tokenMsg = TokenMessageSchema.safeParse(messageEvent.data);
|
|
115
227
|
if (tokenMsg.success) {
|
|
228
|
+
Logger.info("Authentication successful");
|
|
116
229
|
cleanupAndClose();
|
|
117
|
-
resolve({ token: tokenMsg.data.
|
|
230
|
+
resolve({ token: tokenMsg.data.accessToken });
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
const authFailureMsg = AuthFailureMessageSchema.safeParse(messageEvent.data);
|
|
234
|
+
if (authFailureMsg.success) {
|
|
235
|
+
Logger.warn("Authentication failure received", {
|
|
236
|
+
error: authFailureMsg.data.error,
|
|
237
|
+
errorCode: authFailureMsg.data.errorCode,
|
|
238
|
+
});
|
|
239
|
+
cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, "Authentication failed: " + authFailureMsg.data.error));
|
|
118
240
|
return;
|
|
119
241
|
}
|
|
120
|
-
const errorMsg = ErrorMessageSchema.safeParse(
|
|
242
|
+
const errorMsg = ErrorMessageSchema.safeParse(messageEvent.data);
|
|
121
243
|
if (errorMsg.success) {
|
|
244
|
+
Logger.warn("Authentication error received", {
|
|
245
|
+
error: errorMsg.data.error,
|
|
246
|
+
});
|
|
122
247
|
cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, "Authentication failed: " + errorMsg.data.error));
|
|
123
248
|
return;
|
|
124
249
|
}
|
|
250
|
+
Logger.error("Invalid message format received", {
|
|
251
|
+
messageData: messageEvent.data,
|
|
252
|
+
dataType: typeof messageEvent.data,
|
|
253
|
+
tokenValidationError: tokenMsg.error
|
|
254
|
+
? tokenMsg.error.issues
|
|
255
|
+
: undefined,
|
|
256
|
+
errorValidationError: errorMsg.error
|
|
257
|
+
? errorMsg.error.issues
|
|
258
|
+
: undefined,
|
|
259
|
+
});
|
|
125
260
|
cleanupAndClose(new CAMSError(CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
|
|
126
261
|
};
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
262
|
+
const cleanupAndClose = (error) => {
|
|
263
|
+
cleanup();
|
|
264
|
+
try {
|
|
265
|
+
if (authWindow && !authWindow.closed) {
|
|
266
|
+
authWindow.close();
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
catch {
|
|
270
|
+
// Ignore close errors
|
|
271
|
+
}
|
|
272
|
+
if (error)
|
|
273
|
+
reject(error);
|
|
274
|
+
};
|
|
275
|
+
const resetIdleTimeout = () => {
|
|
276
|
+
// Timeout handler
|
|
277
|
+
if (idleTimeoutId)
|
|
278
|
+
originalClearTimeout(idleTimeoutId);
|
|
279
|
+
Logger.debug("Resetting idle timeout", { idleTimeout });
|
|
280
|
+
idleTimeoutId = originalSetTimeout(() => {
|
|
281
|
+
Logger.warn("Authentication idle timeout reached", { idleTimeout });
|
|
282
|
+
cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication timed out due to inactivity after ${idleTimeout}ms`));
|
|
283
|
+
}, idleTimeout);
|
|
284
|
+
};
|
|
285
|
+
Logger.debug("Setting auth timeout", { authTimeout });
|
|
286
|
+
authTimeoutId = originalSetTimeout(() => {
|
|
287
|
+
Logger.warn("Authentication auth timeout reached", { authTimeout });
|
|
288
|
+
cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication process exceeded auth time limit of ${authTimeout}ms`));
|
|
289
|
+
}, authTimeout);
|
|
290
|
+
resetIdleTimeout();
|
|
291
|
+
// Use exponential backoff for popup closure checking
|
|
292
|
+
let pollInterval = 1000; // Start with 1 second
|
|
293
|
+
const maxPollInterval = 5000; // Max 5 seconds
|
|
294
|
+
const checkClosed = () => {
|
|
295
|
+
if (authWindow?.closed) {
|
|
296
|
+
Logger.info("Authentication window closed by user");
|
|
133
297
|
cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
|
|
298
|
+
return;
|
|
134
299
|
}
|
|
135
|
-
|
|
300
|
+
// Exponential backoff: increase interval up to max
|
|
301
|
+
pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);
|
|
302
|
+
checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);
|
|
303
|
+
};
|
|
304
|
+
checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);
|
|
136
305
|
try {
|
|
137
|
-
|
|
306
|
+
originalAddEventListener.call(window, "message", listener);
|
|
307
|
+
Logger.debug("Message listener attached");
|
|
138
308
|
}
|
|
139
309
|
catch (error) {
|
|
310
|
+
Logger.error("Failed to attach message listener", {
|
|
311
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
312
|
+
});
|
|
140
313
|
cleanup();
|
|
141
|
-
reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " +
|
|
314
|
+
reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " +
|
|
315
|
+
(error instanceof Error ? error.message : "Unknown error")));
|
|
142
316
|
return;
|
|
143
317
|
}
|
|
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;
|
|
318
|
+
// Add focus to the popup for better UX
|
|
164
319
|
try {
|
|
165
|
-
|
|
166
|
-
|
|
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;
|
|
320
|
+
if (authWindow) {
|
|
321
|
+
authWindow.focus();
|
|
174
322
|
}
|
|
175
323
|
}
|
|
176
|
-
catch
|
|
177
|
-
|
|
178
|
-
this.storage.removeItem(this.storageKey);
|
|
179
|
-
return null;
|
|
324
|
+
catch {
|
|
325
|
+
// Ignore focus errors (cross-origin restrictions)
|
|
180
326
|
}
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
class CAMSSessionManager {
|
|
331
|
+
storage;
|
|
332
|
+
keyPrefix;
|
|
333
|
+
events;
|
|
334
|
+
token = null;
|
|
335
|
+
constructor(storage = null, keyPrefix, events = {}) {
|
|
336
|
+
this.storage = storage || getDefaultStorage();
|
|
337
|
+
this.keyPrefix = keyPrefix ?? "CAMS-SDK";
|
|
338
|
+
this.events = events;
|
|
181
339
|
}
|
|
182
|
-
|
|
183
|
-
this.
|
|
184
|
-
this.storage.removeItem(this.storageKey);
|
|
340
|
+
setItem(key, value) {
|
|
341
|
+
this.storage.setItem(`${this.keyPrefix}:${key}`, value);
|
|
185
342
|
}
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
const token = this.loadToken();
|
|
189
|
-
return (_a = token === null || token === void 0 ? void 0 : token.access_token) !== null && _a !== void 0 ? _a : null;
|
|
343
|
+
getItem(key) {
|
|
344
|
+
return this.storage.getItem(`${this.keyPrefix}:${key}`);
|
|
190
345
|
}
|
|
191
|
-
|
|
192
|
-
|
|
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;
|
|
346
|
+
removeItem(key) {
|
|
347
|
+
this.storage.removeItem(`${this.keyPrefix}:${key}`);
|
|
212
348
|
}
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
349
|
+
clear() {
|
|
350
|
+
// clear only CAMS-prefixed items
|
|
351
|
+
Object.keys(this.storage).forEach((k) => {
|
|
352
|
+
if (k.startsWith(this.keyPrefix)) {
|
|
353
|
+
this.storage.removeItem(k);
|
|
354
|
+
}
|
|
355
|
+
});
|
|
219
356
|
}
|
|
220
357
|
async login(config) {
|
|
221
|
-
var _a, _b, _c, _d, _e, _f, _g;
|
|
222
358
|
try {
|
|
223
|
-
(
|
|
359
|
+
Logger.info("Session login started");
|
|
360
|
+
if (this.events.onAuthStart)
|
|
361
|
+
this.events.onAuthStart();
|
|
224
362
|
let attempts = 0;
|
|
225
|
-
const maxAttempts = (
|
|
363
|
+
const maxAttempts = (config.retryAttempts ?? 0) + 1;
|
|
364
|
+
Logger.debug("Login retry configuration", { maxAttempts });
|
|
226
365
|
while (attempts < maxAttempts) {
|
|
227
366
|
try {
|
|
367
|
+
attempts++;
|
|
368
|
+
Logger.debug("Login attempt", { attempt: attempts, maxAttempts });
|
|
369
|
+
// Add exponential backoff delay for retries
|
|
370
|
+
if (attempts > 1) {
|
|
371
|
+
const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay
|
|
372
|
+
Logger.debug("Retry delay", { delay });
|
|
373
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
374
|
+
}
|
|
228
375
|
const response = await openCAMSPopUpLogin(config);
|
|
229
|
-
(
|
|
376
|
+
Logger.debug("Login Response", response);
|
|
377
|
+
this.setToken(response.token);
|
|
378
|
+
Logger.info("Session login successful");
|
|
379
|
+
if (this.events.onAuthSuccess)
|
|
380
|
+
this.events.onAuthSuccess(response);
|
|
230
381
|
return response;
|
|
231
382
|
}
|
|
232
383
|
catch (error) {
|
|
233
|
-
|
|
384
|
+
Logger.warn("Login attempt failed", {
|
|
385
|
+
attempt: attempts,
|
|
386
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
387
|
+
});
|
|
234
388
|
if (attempts >= maxAttempts || !(error instanceof CAMSError)) {
|
|
235
389
|
throw error;
|
|
236
390
|
}
|
|
@@ -238,73 +392,177 @@ class CAMSSession {
|
|
|
238
392
|
if (![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {
|
|
239
393
|
throw error;
|
|
240
394
|
}
|
|
395
|
+
Logger.info("Retrying login", { nextAttempt: attempts + 1 });
|
|
241
396
|
}
|
|
242
397
|
}
|
|
243
|
-
throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED,
|
|
398
|
+
throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, "Max retry attempts exceeded");
|
|
244
399
|
}
|
|
245
400
|
catch (error) {
|
|
246
|
-
const
|
|
247
|
-
|
|
248
|
-
|
|
401
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
402
|
+
const camsError = error instanceof CAMSError
|
|
403
|
+
? error
|
|
404
|
+
: new CAMSError(CAMSErrorType.USER_CANCELLED, errorMessage);
|
|
405
|
+
Logger.error("Session login failed", {
|
|
406
|
+
error: camsError.message,
|
|
407
|
+
type: camsError.type,
|
|
408
|
+
});
|
|
409
|
+
if (this.events.onAuthError)
|
|
410
|
+
this.events.onAuthError(camsError);
|
|
249
411
|
throw camsError;
|
|
250
412
|
}
|
|
251
413
|
}
|
|
252
414
|
async logout() {
|
|
253
|
-
|
|
415
|
+
Logger.info("Session logout");
|
|
416
|
+
this.clearToken();
|
|
254
417
|
}
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
418
|
+
setToken(token) {
|
|
419
|
+
this.token = token;
|
|
420
|
+
this.storage.setItem(this.keyPrefix, token);
|
|
421
|
+
Logger.debug("Token stored", { storageKey: this.keyPrefix });
|
|
422
|
+
}
|
|
423
|
+
getAccessToken() {
|
|
424
|
+
// Return cached token if available, avoiding redundant storage access
|
|
425
|
+
if (this.token)
|
|
426
|
+
return this.token;
|
|
427
|
+
const raw = this.storage.getItem(this.keyPrefix);
|
|
428
|
+
if (!raw)
|
|
429
|
+
return null;
|
|
430
|
+
this.token = raw;
|
|
431
|
+
Logger.debug("Token loaded from storage");
|
|
432
|
+
return this.token;
|
|
433
|
+
}
|
|
434
|
+
clearToken() {
|
|
435
|
+
this.token = null;
|
|
436
|
+
this.storage.removeItem(this.keyPrefix);
|
|
437
|
+
Logger.debug("Token cleared");
|
|
438
|
+
}
|
|
439
|
+
isExpired() {
|
|
440
|
+
const token = this.getAccessToken();
|
|
258
441
|
if (!token)
|
|
259
|
-
return
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
442
|
+
return true;
|
|
443
|
+
try {
|
|
444
|
+
const parts = token.split(".");
|
|
445
|
+
if (parts.length < 3)
|
|
446
|
+
return true; // Invalid JWT format
|
|
447
|
+
const payload = JSON.parse(atob(parts[1]));
|
|
448
|
+
if (typeof payload.exp !== "number")
|
|
449
|
+
return true;
|
|
450
|
+
const exp = payload.exp * 1000;
|
|
451
|
+
return Date.now() > exp;
|
|
452
|
+
}
|
|
453
|
+
catch (error) {
|
|
454
|
+
Logger.warn("Failed to parse JWT token", {
|
|
455
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
456
|
+
});
|
|
457
|
+
return true;
|
|
263
458
|
}
|
|
264
|
-
return true;
|
|
265
459
|
}
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
const token = this.tokenManager.loadToken();
|
|
460
|
+
isPaddedExpired() {
|
|
461
|
+
const token = this.getAccessToken();
|
|
269
462
|
if (!token)
|
|
270
|
-
return
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
463
|
+
return true;
|
|
464
|
+
try {
|
|
465
|
+
const parts = token.split(".");
|
|
466
|
+
if (parts.length < 3)
|
|
467
|
+
return true; // Invalid JWT format
|
|
468
|
+
const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
469
|
+
const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=");
|
|
470
|
+
const payload = JSON.parse(atob(padded));
|
|
471
|
+
if (typeof payload.exp !== "number")
|
|
472
|
+
return true;
|
|
473
|
+
const exp = payload.exp * 1000;
|
|
474
|
+
return Date.now() > exp;
|
|
274
475
|
}
|
|
275
|
-
|
|
476
|
+
catch (error) {
|
|
477
|
+
Logger.warn("Failed to parse JWT token", {
|
|
478
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
479
|
+
});
|
|
480
|
+
return true;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
checkTokenExpiration() {
|
|
484
|
+
if (this.isExpired()) {
|
|
485
|
+
Logger.info("Token expired");
|
|
486
|
+
if (this.events.onTokenExpired)
|
|
487
|
+
this.events.onTokenExpired();
|
|
488
|
+
return true;
|
|
489
|
+
}
|
|
490
|
+
return false;
|
|
491
|
+
}
|
|
492
|
+
isAuthenticated() {
|
|
493
|
+
const token = this.getAccessToken();
|
|
494
|
+
if (!token) {
|
|
495
|
+
Logger.debug("No token found");
|
|
496
|
+
return false;
|
|
497
|
+
}
|
|
498
|
+
if (this.checkTokenExpiration()) {
|
|
499
|
+
return false;
|
|
500
|
+
}
|
|
501
|
+
Logger.debug("Token is valid");
|
|
502
|
+
return true;
|
|
276
503
|
}
|
|
277
504
|
decodeBase64Url(str) {
|
|
278
|
-
//
|
|
279
|
-
|
|
505
|
+
// Work with a copy to avoid mutating input
|
|
506
|
+
let result = str.replace(/-/g, "+").replace(/_/g, "/");
|
|
280
507
|
// Add padding if needed
|
|
281
|
-
while (
|
|
282
|
-
|
|
508
|
+
while (result.length % 4) {
|
|
509
|
+
result += "=";
|
|
283
510
|
}
|
|
284
|
-
return atob(
|
|
511
|
+
return atob(result);
|
|
285
512
|
}
|
|
286
513
|
async getProfile() {
|
|
287
|
-
const storedToken = this.
|
|
288
|
-
if (!
|
|
514
|
+
const storedToken = this.getAccessToken();
|
|
515
|
+
if (!storedToken)
|
|
289
516
|
return null;
|
|
517
|
+
// Check token expiration before processing
|
|
518
|
+
if (this.checkTokenExpiration()) {
|
|
519
|
+
return null;
|
|
520
|
+
}
|
|
290
521
|
try {
|
|
291
|
-
const parts = storedToken.
|
|
292
|
-
if (parts.length >= 3) {
|
|
522
|
+
const parts = storedToken.split(".");
|
|
523
|
+
if (parts.length >= 3) {
|
|
524
|
+
// JWT has header.payload.signature format
|
|
293
525
|
try {
|
|
294
526
|
const payload = JSON.parse(this.decodeBase64Url(parts[1]));
|
|
295
527
|
return ProfileSchema.parse(payload);
|
|
296
528
|
}
|
|
297
529
|
catch (decodeError) {
|
|
298
|
-
|
|
530
|
+
Logger.warn("Failed to decode JWT payload", {
|
|
531
|
+
error: decodeError instanceof Error
|
|
532
|
+
? decodeError.message
|
|
533
|
+
: "Unknown error",
|
|
534
|
+
});
|
|
299
535
|
}
|
|
300
536
|
}
|
|
301
537
|
}
|
|
302
538
|
catch (error) {
|
|
303
|
-
|
|
539
|
+
Logger.warn("Failed to extract profile from token", {
|
|
540
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
541
|
+
});
|
|
304
542
|
}
|
|
305
543
|
return null;
|
|
306
544
|
}
|
|
307
545
|
}
|
|
546
|
+
// 🔹 Safe fallback for Node/SSR
|
|
547
|
+
function getDefaultStorage() {
|
|
548
|
+
if (typeof window !== "undefined" && window.localStorage) {
|
|
549
|
+
return window.localStorage;
|
|
550
|
+
}
|
|
551
|
+
const memoryStore = {};
|
|
552
|
+
return {
|
|
553
|
+
getItem: (key) => (key in memoryStore ? memoryStore[key] : null),
|
|
554
|
+
setItem: (key, value) => {
|
|
555
|
+
memoryStore[key] = value;
|
|
556
|
+
},
|
|
557
|
+
removeItem: (key) => {
|
|
558
|
+
delete memoryStore[key];
|
|
559
|
+
},
|
|
560
|
+
key: (i) => Object.keys(memoryStore)[i] ?? null,
|
|
561
|
+
get length() {
|
|
562
|
+
return Object.keys(memoryStore).length;
|
|
563
|
+
},
|
|
564
|
+
};
|
|
565
|
+
}
|
|
308
566
|
|
|
309
|
-
export { CAMSError, CAMSErrorType,
|
|
567
|
+
export { AuthFailureMessageSchema, CAMSError, CAMSErrorType, CAMSSessionManager, ErrorMessageSchema, LogLevel, Logger, ProfileSchema, TokenMessageSchema, TokenSchema, URLSchema, openCAMSPopUpLogin, validateConfig };
|
|
310
568
|
//# sourceMappingURL=index.esm.js.map
|