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