@nibssplc/cams-sdk 0.0.1-beta.4 → 0.0.1-beta.40
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 +91 -87
- package/dist/MFAAuth.d.ts +35 -0
- package/dist/auth.d.ts +18 -3
- package/dist/index.cjs.js +695 -197
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.esm.js +690 -194
- package/dist/index.esm.js.map +1 -1
- package/dist/index.umd.js +695 -197
- package/dist/index.umd.js.map +1 -1
- package/dist/logger.d.ts +19 -0
- package/dist/sessionManager.d.ts +47 -0
- package/dist/types.d.ts +7 -10
- package/dist/validators.d.ts +26 -20
- package/package.json +23 -5
- package/dist/session.d.ts +0 -19
- package/dist/tokenManager.d.ts +0 -12
package/dist/index.umd.js
CHANGED
|
@@ -12,229 +12,547 @@
|
|
|
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").or(zod.z.literal("AUTH_FAILURE")),
|
|
29
|
+
userProfile: zod.z.object({
|
|
30
|
+
name: zod.z.string(),
|
|
31
|
+
email: zod.z.email(),
|
|
32
|
+
mfaIsEnabled: zod.z.boolean(),
|
|
33
|
+
message: zod.z.string(),
|
|
34
|
+
isAuthenticated: zod.z.boolean(),
|
|
35
|
+
userType: zod.z.enum(["SUPER_ADMIN", "ADMIN", "USER"]),
|
|
36
|
+
tokens: zod.z.object({
|
|
37
|
+
Nonce: zod.z.string(),
|
|
38
|
+
Bearer: zod.z.string(),
|
|
39
|
+
}),
|
|
40
|
+
}),
|
|
27
41
|
});
|
|
28
42
|
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(),
|
|
43
|
+
error: zod.z.string().min(1, "Error message cannot be empty"),
|
|
37
44
|
});
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
family_name: zod.z.string().optional(),
|
|
44
|
-
roles: zod.z.array(zod.z.string()).optional(),
|
|
45
|
+
const AuthFailureMessageSchema = zod.z.object({
|
|
46
|
+
type: zod.z.literal("AUTH_FAILURE"),
|
|
47
|
+
error: zod.z.string().min(1, "Error message cannot be empty"),
|
|
48
|
+
errorCode: zod.z.string(),
|
|
49
|
+
errorDetails: zod.z.object().or(zod.z.any()),
|
|
45
50
|
});
|
|
46
|
-
|
|
47
|
-
|
|
51
|
+
const URLSchema = zod.z.url();
|
|
52
|
+
|
|
53
|
+
exports.LogLevel = void 0;
|
|
54
|
+
(function (LogLevel) {
|
|
55
|
+
LogLevel[LogLevel["ERROR"] = 0] = "ERROR";
|
|
56
|
+
LogLevel[LogLevel["WARN"] = 1] = "WARN";
|
|
57
|
+
LogLevel[LogLevel["INFO"] = 2] = "INFO";
|
|
58
|
+
LogLevel[LogLevel["DEBUG"] = 3] = "DEBUG";
|
|
59
|
+
})(exports.LogLevel || (exports.LogLevel = {}));
|
|
60
|
+
class Logger {
|
|
61
|
+
static level = exports.LogLevel.DEBUG;
|
|
62
|
+
static prefix = '[CAMS-SDK]';
|
|
63
|
+
static isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';
|
|
64
|
+
static setLevel(level) {
|
|
65
|
+
Logger.level = level;
|
|
66
|
+
}
|
|
67
|
+
static error(message, context) {
|
|
68
|
+
if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.ERROR) {
|
|
69
|
+
console.error(`${Logger.prefix} ERROR:`, message, context || '');
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
static warn(message, context) {
|
|
73
|
+
if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.WARN) {
|
|
74
|
+
console.warn(`${Logger.prefix} WARN:`, message, context || '');
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
static info(message, context) {
|
|
78
|
+
if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.INFO) {
|
|
79
|
+
console.info(`${Logger.prefix} INFO:`, message, context || '');
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
static debug(message, context) {
|
|
83
|
+
if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.DEBUG) {
|
|
84
|
+
console.debug(`${Logger.prefix} DEBUG:`, message, context || '');
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
48
88
|
|
|
89
|
+
// Constants
|
|
90
|
+
const DEFAULT_AUTH_TIMEOUT = 300000; // 5 minutes
|
|
91
|
+
const DEFAULT_IDLE_TIMEOUT = 120000; // 2 minutes
|
|
92
|
+
const INITIAL_POLL_INTERVAL = 1000;
|
|
93
|
+
const MAX_POLL_INTERVAL = 5000;
|
|
94
|
+
const WINDOW_FEATURES = "scrollbars=yes,resizable=yes";
|
|
95
|
+
// Default allowed Microsoft domains for Azure AD redirects
|
|
96
|
+
const DEFAULT_MICROSOFT_DOMAINS = [
|
|
97
|
+
".microsoft.com",
|
|
98
|
+
".microsoftonline.com",
|
|
99
|
+
".live.com",
|
|
100
|
+
"login.microsoftonline.com"
|
|
101
|
+
];
|
|
102
|
+
// Secure reference to native functions
|
|
103
|
+
const NativeFunctions = {
|
|
104
|
+
addEventListener: typeof window !== "undefined" ? window.addEventListener : null,
|
|
105
|
+
removeEventListener: typeof window !== "undefined" ? window.removeEventListener : null,
|
|
106
|
+
setTimeout: typeof window !== "undefined" ? window.setTimeout : setTimeout,
|
|
107
|
+
clearTimeout: typeof window !== "undefined" ? window.clearTimeout : clearTimeout,
|
|
108
|
+
};
|
|
109
|
+
/**
|
|
110
|
+
* Generate a secure random window name to prevent targeting
|
|
111
|
+
*/
|
|
112
|
+
const generateSecureWindowName = () => `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;
|
|
113
|
+
/**
|
|
114
|
+
* Detect if current window is a popup to prevent recursive popups
|
|
115
|
+
*/
|
|
116
|
+
const isPopupWindow = () => {
|
|
117
|
+
if (typeof window === "undefined")
|
|
118
|
+
return false;
|
|
119
|
+
try {
|
|
120
|
+
return window.opener !== null && window.opener !== window;
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* Safely close a window with error handling for cross-origin restrictions
|
|
128
|
+
*/
|
|
129
|
+
const safeWindowClose = (window) => {
|
|
130
|
+
if (!window)
|
|
131
|
+
return;
|
|
132
|
+
try {
|
|
133
|
+
if (!window.closed) {
|
|
134
|
+
window.close();
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
Logger.debug("Error closing window (cross-origin restriction)", {
|
|
139
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
/**
|
|
144
|
+
* Center popup window on screen
|
|
145
|
+
*/
|
|
146
|
+
const getPopupPosition = (width, height) => {
|
|
147
|
+
if (typeof window === "undefined")
|
|
148
|
+
return { left: 0, top: 0 };
|
|
149
|
+
const left = Math.max(0, (window.screen.width - width) / 2);
|
|
150
|
+
const top = Math.max(0, (window.screen.height - height) / 2);
|
|
151
|
+
return { left, top };
|
|
152
|
+
};
|
|
153
|
+
/**
|
|
154
|
+
* Validate origin against expected domain with support for subdomains and Microsoft redirects
|
|
155
|
+
*/
|
|
156
|
+
const isValidOrigin = (eventOrigin, expectedOrigin, microsoftDomains = DEFAULT_MICROSOFT_DOMAINS) => {
|
|
157
|
+
try {
|
|
158
|
+
const originUrl = new URL(eventOrigin);
|
|
159
|
+
const expectedHostname = expectedOrigin.startsWith("http")
|
|
160
|
+
? new URL(expectedOrigin).hostname
|
|
161
|
+
: expectedOrigin;
|
|
162
|
+
// Check Microsoft domains for Azure AD redirects
|
|
163
|
+
const isMicrosoftDomain = microsoftDomains.some(domain => originUrl.hostname === domain || originUrl.hostname.endsWith(domain));
|
|
164
|
+
// Allow exact match, subdomains, or Microsoft domains
|
|
165
|
+
return (originUrl.hostname === expectedHostname ||
|
|
166
|
+
originUrl.hostname.endsWith("." + expectedHostname) ||
|
|
167
|
+
isMicrosoftDomain);
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
/**
|
|
174
|
+
* Safely check if window is closed with cross-origin handling
|
|
175
|
+
*/
|
|
176
|
+
const isWindowClosed = (window) => {
|
|
177
|
+
if (!window)
|
|
178
|
+
return true;
|
|
179
|
+
try {
|
|
180
|
+
return window.closed;
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
// Cross-origin error means we can't access the property
|
|
184
|
+
// This typically happens when redirected to external auth providers
|
|
185
|
+
Logger.debug("Cannot access window.closed due to cross-origin restrictions - assuming window is still open", error);
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
/**
|
|
190
|
+
* Safely add message event listener with error handling
|
|
191
|
+
*/
|
|
192
|
+
const addMessageListener = (listener) => {
|
|
193
|
+
if (!NativeFunctions.addEventListener) {
|
|
194
|
+
throw new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Message listener not available in current environment");
|
|
195
|
+
}
|
|
196
|
+
const wrappedListener = (event) => {
|
|
197
|
+
try {
|
|
198
|
+
listener(event);
|
|
199
|
+
}
|
|
200
|
+
catch (error) {
|
|
201
|
+
Logger.error("Error in message listener", {
|
|
202
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
NativeFunctions.addEventListener.call(window, "message", wrappedListener);
|
|
207
|
+
return () => {
|
|
208
|
+
if (NativeFunctions.removeEventListener) {
|
|
209
|
+
NativeFunctions.removeEventListener.call(window, "message", wrappedListener);
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
};
|
|
213
|
+
/**
|
|
214
|
+
* Validate configuration and return parsed URL
|
|
215
|
+
*/
|
|
49
216
|
function validateConfig(config) {
|
|
50
|
-
var _a;
|
|
51
|
-
// Validate URL format
|
|
52
217
|
const urlValidation = URLSchema.safeParse(config.camsUrl);
|
|
53
218
|
if (!urlValidation.success) {
|
|
54
|
-
throw new CAMSError(exports.CAMSErrorType.INVALID_URL,
|
|
55
|
-
}
|
|
56
|
-
// Domain validation is mandatory for security
|
|
57
|
-
if (!((_a = config.allowedDomains) === null || _a === void 0 ? void 0 : _a.length)) {
|
|
58
|
-
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');
|
|
219
|
+
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Invalid CAMS URL format");
|
|
59
220
|
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
if (!isAllowed) {
|
|
63
|
-
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'URL not in allowed domains list');
|
|
221
|
+
if (!config.messageOrigin) {
|
|
222
|
+
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Message Origin must be specified for security");
|
|
64
223
|
}
|
|
224
|
+
return new URL(config.camsUrl);
|
|
65
225
|
}
|
|
226
|
+
/**
|
|
227
|
+
* Open CAMS authentication popup and handle the authentication flow
|
|
228
|
+
*/
|
|
66
229
|
function openCAMSPopUpLogin(config) {
|
|
67
230
|
return new Promise((resolve, reject) => {
|
|
68
|
-
|
|
69
|
-
|
|
231
|
+
// Environment validation
|
|
232
|
+
if (typeof window === "undefined") {
|
|
233
|
+
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Cannot open popup in server-side environment"));
|
|
234
|
+
return;
|
|
70
235
|
}
|
|
71
|
-
|
|
72
|
-
|
|
236
|
+
if (isPopupWindow()) {
|
|
237
|
+
Logger.warn("Attempted to open popup from within popup window");
|
|
238
|
+
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Cannot open authentication popup from within popup window"));
|
|
73
239
|
return;
|
|
74
240
|
}
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
241
|
+
// Initialize logging
|
|
242
|
+
if (config.debug)
|
|
243
|
+
Logger.setLevel(exports.LogLevel.DEBUG);
|
|
244
|
+
Logger.info("Starting CAMS authentication", { url: config.camsUrl });
|
|
245
|
+
// Validate configuration
|
|
246
|
+
let validatedUrl;
|
|
79
247
|
try {
|
|
80
|
-
|
|
248
|
+
validatedUrl = validateConfig(config);
|
|
249
|
+
Logger.debug("Configuration validation passed");
|
|
81
250
|
}
|
|
82
251
|
catch (error) {
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window. Please allow popups."));
|
|
252
|
+
Logger.error("Configuration validation failed", {
|
|
253
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
254
|
+
});
|
|
255
|
+
reject(error);
|
|
88
256
|
return;
|
|
89
257
|
}
|
|
258
|
+
// Extract configuration with defaults
|
|
259
|
+
const { messageOrigin, windowHeight = 600, windowWidth = 500, authTimeout = DEFAULT_AUTH_TIMEOUT, idleTimeout = DEFAULT_IDLE_TIMEOUT, allowedRedirectDomains = DEFAULT_MICROSOFT_DOMAINS, } = config;
|
|
260
|
+
// State management
|
|
261
|
+
let authWindow = null;
|
|
262
|
+
let authTimeoutId = null;
|
|
263
|
+
let idleTimeoutId = null;
|
|
264
|
+
let checkClosedInterval = null;
|
|
265
|
+
let removeMessageListener = null;
|
|
266
|
+
let hasReceivedValidMessage = false;
|
|
267
|
+
/**
|
|
268
|
+
* Clean up all resources and timeouts
|
|
269
|
+
*/
|
|
90
270
|
const cleanup = () => {
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
271
|
+
if (removeMessageListener) {
|
|
272
|
+
removeMessageListener();
|
|
273
|
+
removeMessageListener = null;
|
|
274
|
+
}
|
|
275
|
+
if (idleTimeoutId)
|
|
276
|
+
NativeFunctions.clearTimeout(idleTimeoutId);
|
|
277
|
+
if (authTimeoutId)
|
|
278
|
+
NativeFunctions.clearTimeout(authTimeoutId);
|
|
94
279
|
if (checkClosedInterval)
|
|
95
|
-
|
|
280
|
+
NativeFunctions.clearTimeout(checkClosedInterval);
|
|
281
|
+
idleTimeoutId = null;
|
|
282
|
+
authTimeoutId = null;
|
|
283
|
+
checkClosedInterval = null;
|
|
96
284
|
};
|
|
285
|
+
/**
|
|
286
|
+
* Clean up and close the popup window, then reject with error
|
|
287
|
+
*/
|
|
97
288
|
const cleanupAndClose = (error) => {
|
|
98
289
|
cleanup();
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
290
|
+
safeWindowClose(authWindow);
|
|
291
|
+
if (error) {
|
|
292
|
+
reject(error);
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
/**
|
|
296
|
+
* Reset idle timeout on user activity
|
|
297
|
+
*/
|
|
298
|
+
const resetIdleTimeout = () => {
|
|
299
|
+
if (idleTimeoutId)
|
|
300
|
+
NativeFunctions.clearTimeout(idleTimeoutId);
|
|
301
|
+
Logger.debug("Resetting idle timeout", { idleTimeout });
|
|
302
|
+
idleTimeoutId = NativeFunctions.setTimeout(() => {
|
|
303
|
+
Logger.warn("Authentication idle timeout reached", { idleTimeout });
|
|
304
|
+
cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timed out due to inactivity after ${idleTimeout}ms`));
|
|
305
|
+
}, idleTimeout);
|
|
306
|
+
};
|
|
307
|
+
/**
|
|
308
|
+
* Set up popup window closure detection with cross-origin handling
|
|
309
|
+
*/
|
|
310
|
+
const setupClosureDetection = () => {
|
|
311
|
+
let pollInterval = INITIAL_POLL_INTERVAL;
|
|
312
|
+
let consecutiveCrossOriginErrors = 0;
|
|
313
|
+
const MAX_CROSS_ORIGIN_ERRORS = 10; // Allow some cross-origin redirects
|
|
314
|
+
const checkClosed = () => {
|
|
315
|
+
const isClosed = isWindowClosed(authWindow);
|
|
316
|
+
if (isClosed) {
|
|
317
|
+
// Only treat as user cancellation if we haven't received any valid messages
|
|
318
|
+
// This prevents false positives when Microsoft redirects cause cross-origin errors
|
|
319
|
+
if (!hasReceivedValidMessage) {
|
|
320
|
+
Logger.info("Authentication window closed by user before any successful communication");
|
|
321
|
+
cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
|
|
322
|
+
}
|
|
323
|
+
else {
|
|
324
|
+
Logger.info("Authentication window closed after successful communication - likely completed flow");
|
|
325
|
+
// Don't reject here - wait for the actual message or timeout
|
|
326
|
+
}
|
|
327
|
+
return;
|
|
102
328
|
}
|
|
329
|
+
// If we get a cross-origin error, count it but don't immediately fail
|
|
330
|
+
// This is normal during redirects to external auth providers
|
|
331
|
+
if (authWindow && !isClosed) {
|
|
332
|
+
try {
|
|
333
|
+
// Try to access a property to see if we get cross-origin error
|
|
334
|
+
const test = authWindow.location;
|
|
335
|
+
consecutiveCrossOriginErrors = 0; // Reset counter if no error
|
|
336
|
+
}
|
|
337
|
+
catch (error) {
|
|
338
|
+
consecutiveCrossOriginErrors++;
|
|
339
|
+
Logger.debug(`Cross-origin redirect detected (${consecutiveCrossOriginErrors}/${MAX_CROSS_ORIGIN_ERRORS})`, error);
|
|
340
|
+
// Only fail if we get too many consecutive cross-origin errors without any valid messages
|
|
341
|
+
if (consecutiveCrossOriginErrors >= MAX_CROSS_ORIGIN_ERRORS && !hasReceivedValidMessage) {
|
|
342
|
+
Logger.error("Too many consecutive cross-origin errors - possible navigation issue");
|
|
343
|
+
cleanupAndClose(new CAMSError(exports.CAMSErrorType.INVALID_ORIGIN, "Authentication failed due to navigation issues"));
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
// Exponential backoff with maximum limit
|
|
349
|
+
pollInterval = Math.min(pollInterval * 1.2, MAX_POLL_INTERVAL);
|
|
350
|
+
checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);
|
|
351
|
+
};
|
|
352
|
+
checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);
|
|
353
|
+
};
|
|
354
|
+
/**
|
|
355
|
+
* Handle incoming message events from the popup
|
|
356
|
+
*/
|
|
357
|
+
const handleMessage = (event) => {
|
|
358
|
+
Logger.debug("Received message", {
|
|
359
|
+
origin: event.origin,
|
|
360
|
+
expectedOrigin: messageOrigin,
|
|
361
|
+
data: event.data,
|
|
362
|
+
});
|
|
363
|
+
// Security: Validate origin
|
|
364
|
+
if (!isValidOrigin(event.origin, messageOrigin, allowedRedirectDomains)) {
|
|
365
|
+
Logger.warn("Blocked message from unauthorized origin", {
|
|
366
|
+
origin: event.origin,
|
|
367
|
+
expected: messageOrigin,
|
|
368
|
+
data: event.data,
|
|
369
|
+
});
|
|
370
|
+
return;
|
|
103
371
|
}
|
|
104
|
-
|
|
105
|
-
|
|
372
|
+
// Security: Validate message source
|
|
373
|
+
if (event.source !== authWindow) {
|
|
374
|
+
Logger.warn("Message from unexpected source", {
|
|
375
|
+
source: event.source,
|
|
376
|
+
origin: event.origin,
|
|
377
|
+
expected: messageOrigin,
|
|
378
|
+
data: event.data,
|
|
379
|
+
});
|
|
380
|
+
return;
|
|
106
381
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
const sanitizedOrigin = event.origin.replace(/[\r\n]/g, '');
|
|
114
|
-
console.warn("Blocked message from origin:", sanitizedOrigin);
|
|
382
|
+
// Mark that we've received a valid message (prevents false closure detection)
|
|
383
|
+
hasReceivedValidMessage = true;
|
|
384
|
+
// Handle heartbeat messages (reset idle timeout)
|
|
385
|
+
if (event.data?.type === "heartbeat") {
|
|
386
|
+
Logger.debug("Received heartbeat message");
|
|
387
|
+
resetIdleTimeout();
|
|
115
388
|
return;
|
|
116
389
|
}
|
|
117
|
-
//
|
|
118
|
-
|
|
119
|
-
|
|
390
|
+
// Process authentication messages
|
|
391
|
+
processAuthenticationMessage(event.data);
|
|
392
|
+
};
|
|
393
|
+
/**
|
|
394
|
+
* Process and validate authentication message payloads
|
|
395
|
+
*/
|
|
396
|
+
const processAuthenticationMessage = (data) => {
|
|
397
|
+
// Success case: Valid profile received
|
|
398
|
+
const profileValidation = ProfileSchema.safeParse(data);
|
|
399
|
+
if (profileValidation.success) {
|
|
400
|
+
Logger.info("Authentication successful");
|
|
120
401
|
cleanupAndClose();
|
|
121
|
-
resolve(
|
|
402
|
+
resolve(profileValidation.data);
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
// Authentication failure case
|
|
406
|
+
const authFailureValidation = AuthFailureMessageSchema.safeParse(data);
|
|
407
|
+
if (authFailureValidation.success) {
|
|
408
|
+
const { error, errorCode, errorDetails } = authFailureValidation.data;
|
|
409
|
+
Logger.warn("Authentication failure received", {
|
|
410
|
+
error,
|
|
411
|
+
errorCode,
|
|
412
|
+
errorDetails,
|
|
413
|
+
});
|
|
414
|
+
cleanupAndClose(new CAMSError(exports.CAMSErrorType.API_VALIDATION_ERROR, `Authentication failed: ${error}${errorCode ? ` (${errorCode})` : ''}`));
|
|
122
415
|
return;
|
|
123
416
|
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
417
|
+
// Generic error case
|
|
418
|
+
const errorValidation = ErrorMessageSchema.safeParse(data);
|
|
419
|
+
if (errorValidation.success) {
|
|
420
|
+
Logger.warn("Authentication error received", {
|
|
421
|
+
error: errorValidation.data.error,
|
|
422
|
+
});
|
|
423
|
+
cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, `Authentication failed: ${errorValidation.data.error}`));
|
|
127
424
|
return;
|
|
128
425
|
}
|
|
426
|
+
// Invalid message format
|
|
427
|
+
Logger.error("Invalid message format received", {
|
|
428
|
+
messageData: data,
|
|
429
|
+
dataType: typeof data,
|
|
430
|
+
profileValidationError: profileValidation.error?.issues,
|
|
431
|
+
authFailureValidationError: authFailureValidation.error?.issues,
|
|
432
|
+
errorValidationError: errorValidation.error?.issues,
|
|
433
|
+
});
|
|
129
434
|
cleanupAndClose(new CAMSError(exports.CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
|
|
130
435
|
};
|
|
131
|
-
//
|
|
132
|
-
timeoutId = setTimeout(() => {
|
|
133
|
-
cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));
|
|
134
|
-
}, timeout);
|
|
135
|
-
checkClosedInterval = setInterval(() => {
|
|
136
|
-
if (authWindow && authWindow.closed) {
|
|
137
|
-
cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
|
|
138
|
-
}
|
|
139
|
-
}, 2000); // Reduced polling frequency
|
|
436
|
+
// Main authentication flow execution
|
|
140
437
|
try {
|
|
141
|
-
window
|
|
438
|
+
// Open popup window
|
|
439
|
+
const { left, top } = getPopupPosition(windowWidth, windowHeight);
|
|
440
|
+
const secureWindowName = generateSecureWindowName();
|
|
441
|
+
Logger.debug("Opening popup window", {
|
|
442
|
+
width: windowWidth,
|
|
443
|
+
height: windowHeight,
|
|
444
|
+
left,
|
|
445
|
+
top,
|
|
446
|
+
});
|
|
447
|
+
authWindow = window.open(validatedUrl.toString(), secureWindowName, `width=${windowWidth},height=${windowHeight},left=${left},top=${top},${WINDOW_FEATURES}`);
|
|
448
|
+
// Check for popup blocking
|
|
449
|
+
if (!authWindow) {
|
|
450
|
+
Logger.error("Popup window blocked or failed to open");
|
|
451
|
+
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
// Check for immediate closure (aggressive popup blockers)
|
|
455
|
+
if (isWindowClosed(authWindow)) {
|
|
456
|
+
Logger.error("Popup immediately closed by blocker");
|
|
457
|
+
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
Logger.debug("Popup window opened successfully");
|
|
461
|
+
// Set up message listener
|
|
462
|
+
removeMessageListener = addMessageListener(handleMessage);
|
|
463
|
+
Logger.debug("Message listener attached");
|
|
464
|
+
// Set up timeouts
|
|
465
|
+
Logger.debug("Setting authentication timeout", { authTimeout });
|
|
466
|
+
authTimeoutId = NativeFunctions.setTimeout(() => {
|
|
467
|
+
Logger.warn("Authentication timeout reached", { authTimeout });
|
|
468
|
+
cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication process exceeded time limit of ${authTimeout}ms`));
|
|
469
|
+
}, authTimeout);
|
|
470
|
+
resetIdleTimeout();
|
|
471
|
+
setupClosureDetection();
|
|
472
|
+
// Focus popup for better UX
|
|
473
|
+
try {
|
|
474
|
+
authWindow.focus();
|
|
475
|
+
}
|
|
476
|
+
catch (error) {
|
|
477
|
+
Logger.debug("Could not focus popup window (cross-origin restriction)");
|
|
478
|
+
}
|
|
142
479
|
}
|
|
143
480
|
catch (error) {
|
|
481
|
+
Logger.error("Failed to initialize authentication popup", {
|
|
482
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
483
|
+
});
|
|
144
484
|
cleanup();
|
|
145
|
-
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to
|
|
146
|
-
|
|
485
|
+
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to initialize authentication: " +
|
|
486
|
+
(error instanceof Error ? error.message : "Unknown error")));
|
|
147
487
|
}
|
|
148
488
|
});
|
|
149
489
|
}
|
|
150
490
|
|
|
151
|
-
class
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
this.
|
|
160
|
-
this.
|
|
491
|
+
class CAMSSessionManager {
|
|
492
|
+
storage;
|
|
493
|
+
keyPrefix;
|
|
494
|
+
events;
|
|
495
|
+
token = null;
|
|
496
|
+
profile = null;
|
|
497
|
+
constructor(storage = null, keyPrefix, events = {}) {
|
|
498
|
+
this.storage = storage || getDefaultStorage();
|
|
499
|
+
this.keyPrefix = keyPrefix ?? "CAMS-SDK";
|
|
500
|
+
this.events = events;
|
|
161
501
|
}
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
return this.token;
|
|
165
|
-
const raw = this.storage.getItem(this.storageKey);
|
|
166
|
-
if (!raw)
|
|
167
|
-
return null;
|
|
168
|
-
try {
|
|
169
|
-
const parsed = JSON.parse(raw);
|
|
170
|
-
try {
|
|
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;
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
catch (parseError) {
|
|
181
|
-
console.warn('Failed to parse stored token JSON:', parseError instanceof Error ? parseError.message : 'Unknown error');
|
|
182
|
-
this.storage.removeItem(this.storageKey);
|
|
183
|
-
return null;
|
|
184
|
-
}
|
|
502
|
+
setItem(key, value) {
|
|
503
|
+
this.storage.setItem(`${this.keyPrefix}:${key}`, value);
|
|
185
504
|
}
|
|
186
|
-
|
|
187
|
-
this.
|
|
188
|
-
this.storage.removeItem(this.storageKey);
|
|
505
|
+
getItem(key) {
|
|
506
|
+
return this.storage.getItem(`${this.keyPrefix}:${key}`);
|
|
189
507
|
}
|
|
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;
|
|
508
|
+
removeItem(key) {
|
|
509
|
+
this.storage.removeItem(`${this.keyPrefix}:${key}`);
|
|
194
510
|
}
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
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;
|
|
511
|
+
clear() {
|
|
512
|
+
// clear only CAMS-prefixed items
|
|
513
|
+
Object.keys(this.storage).forEach((k) => {
|
|
514
|
+
if (k.startsWith(this.keyPrefix)) {
|
|
515
|
+
this.storage.removeItem(k);
|
|
212
516
|
}
|
|
213
|
-
}
|
|
214
|
-
// Fallback: return true for safety when expiration cannot be determined
|
|
215
|
-
return true;
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
class CAMSSession {
|
|
220
|
-
constructor(storage = sessionStorage, storageKey, events = {}) {
|
|
221
|
-
this.tokenManager = new TokenManager(storage, storageKey);
|
|
222
|
-
this.events = events;
|
|
517
|
+
});
|
|
223
518
|
}
|
|
224
519
|
async login(config) {
|
|
225
|
-
var _a, _b, _c, _d, _e, _f, _g;
|
|
226
520
|
try {
|
|
227
|
-
(
|
|
521
|
+
Logger.info("Session login started");
|
|
522
|
+
// If we're in a popup, don't attempt to open another popup
|
|
523
|
+
if (isPopupWindow()) {
|
|
524
|
+
Logger.warn("Cannot initiate login from popup window");
|
|
525
|
+
throw new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Cannot initiate authentication from within popup window");
|
|
526
|
+
}
|
|
527
|
+
if (this.events.onAuthStart)
|
|
528
|
+
this.events.onAuthStart();
|
|
228
529
|
let attempts = 0;
|
|
229
|
-
const maxAttempts = (
|
|
530
|
+
const maxAttempts = (config.retryAttempts ?? 0) + 1;
|
|
531
|
+
Logger.debug("Login retry configuration", { maxAttempts });
|
|
230
532
|
while (attempts < maxAttempts) {
|
|
231
533
|
try {
|
|
534
|
+
attempts++;
|
|
535
|
+
Logger.debug("Login attempt", { attempt: attempts, maxAttempts });
|
|
536
|
+
// Add exponential backoff delay for retries
|
|
537
|
+
if (attempts > 1) {
|
|
538
|
+
const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay
|
|
539
|
+
Logger.debug("Retry delay", { delay });
|
|
540
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
541
|
+
}
|
|
232
542
|
const response = await openCAMSPopUpLogin(config);
|
|
233
|
-
(
|
|
543
|
+
Logger.debug("Login Response", response);
|
|
544
|
+
this.profile = response;
|
|
545
|
+
this.setToken(response.userProfile.tokens.Bearer);
|
|
546
|
+
Logger.info("Session login successful");
|
|
547
|
+
if (this.events.onAuthSuccess)
|
|
548
|
+
this.events.onAuthSuccess(response);
|
|
234
549
|
return response;
|
|
235
550
|
}
|
|
236
551
|
catch (error) {
|
|
237
|
-
|
|
552
|
+
Logger.warn("Login attempt failed", {
|
|
553
|
+
attempt: attempts,
|
|
554
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
555
|
+
});
|
|
238
556
|
if (attempts >= maxAttempts || !(error instanceof CAMSError)) {
|
|
239
557
|
throw error;
|
|
240
558
|
}
|
|
@@ -242,82 +560,262 @@
|
|
|
242
560
|
if (![exports.CAMSErrorType.TIMEOUT, exports.CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {
|
|
243
561
|
throw error;
|
|
244
562
|
}
|
|
563
|
+
Logger.info("Retrying login", { nextAttempt: attempts + 1 });
|
|
245
564
|
}
|
|
246
565
|
}
|
|
247
|
-
throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED,
|
|
566
|
+
throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED, "Max retry attempts exceeded");
|
|
248
567
|
}
|
|
249
568
|
catch (error) {
|
|
250
|
-
const
|
|
251
|
-
|
|
252
|
-
|
|
569
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
570
|
+
const camsError = error instanceof CAMSError
|
|
571
|
+
? error
|
|
572
|
+
: new CAMSError(exports.CAMSErrorType.USER_CANCELLED, errorMessage);
|
|
573
|
+
Logger.error("Session login failed", {
|
|
574
|
+
error: camsError.message,
|
|
575
|
+
type: camsError.type,
|
|
576
|
+
});
|
|
577
|
+
if (this.events.onAuthError)
|
|
578
|
+
this.events.onAuthError(camsError);
|
|
253
579
|
throw camsError;
|
|
254
580
|
}
|
|
255
581
|
}
|
|
256
582
|
async logout() {
|
|
257
|
-
|
|
583
|
+
Logger.info("Session logout");
|
|
584
|
+
this.clearToken();
|
|
258
585
|
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
586
|
+
setToken(token) {
|
|
587
|
+
this.token = token;
|
|
588
|
+
this.storage.setItem(this.keyPrefix, token);
|
|
589
|
+
Logger.debug("Token stored", { storageKey: this.keyPrefix });
|
|
590
|
+
}
|
|
591
|
+
getAccessToken() {
|
|
592
|
+
// Return cached token if available, avoiding redundant storage access
|
|
593
|
+
if (this.token)
|
|
594
|
+
return this.token;
|
|
595
|
+
const raw = this.storage.getItem(this.keyPrefix);
|
|
596
|
+
if (!raw)
|
|
597
|
+
return null;
|
|
598
|
+
this.token = raw;
|
|
599
|
+
Logger.debug("Token loaded from storage");
|
|
600
|
+
return this.token;
|
|
601
|
+
}
|
|
602
|
+
clearToken() {
|
|
603
|
+
this.token = null;
|
|
604
|
+
this.storage.removeItem(this.keyPrefix);
|
|
605
|
+
Logger.debug("Token cleared");
|
|
606
|
+
}
|
|
607
|
+
isExpired() {
|
|
608
|
+
const token = this.getAccessToken();
|
|
609
|
+
if (!token)
|
|
610
|
+
return true;
|
|
611
|
+
try {
|
|
612
|
+
const parts = token.split(".");
|
|
613
|
+
if (parts.length < 3)
|
|
614
|
+
return true; // Invalid JWT format
|
|
615
|
+
const payload = JSON.parse(atob(parts[1]));
|
|
616
|
+
if (typeof payload.exp !== "number")
|
|
617
|
+
return true;
|
|
618
|
+
const exp = payload.exp * 1000;
|
|
619
|
+
return Date.now() > exp;
|
|
620
|
+
}
|
|
621
|
+
catch (error) {
|
|
622
|
+
Logger.warn("Failed to parse JWT token", {
|
|
623
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
624
|
+
});
|
|
625
|
+
return true;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
isPaddedExpired() {
|
|
629
|
+
const token = this.getAccessToken();
|
|
262
630
|
if (!token)
|
|
631
|
+
return true;
|
|
632
|
+
try {
|
|
633
|
+
const parts = token.split(".");
|
|
634
|
+
if (parts.length < 3)
|
|
635
|
+
return true; // Invalid JWT format
|
|
636
|
+
const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
637
|
+
const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=");
|
|
638
|
+
const payload = JSON.parse(atob(padded));
|
|
639
|
+
if (typeof payload.exp !== "number")
|
|
640
|
+
return true;
|
|
641
|
+
const exp = payload.exp * 1000;
|
|
642
|
+
return Date.now() > exp;
|
|
643
|
+
}
|
|
644
|
+
catch (error) {
|
|
645
|
+
Logger.warn("Failed to parse JWT token", {
|
|
646
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
647
|
+
});
|
|
648
|
+
return true;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
checkTokenExpiration() {
|
|
652
|
+
if (this.isExpired()) {
|
|
653
|
+
Logger.info("Token expired");
|
|
654
|
+
if (this.events.onTokenExpired)
|
|
655
|
+
this.events.onTokenExpired();
|
|
656
|
+
return true;
|
|
657
|
+
}
|
|
658
|
+
return false;
|
|
659
|
+
}
|
|
660
|
+
isAuthenticated() {
|
|
661
|
+
const token = this.getAccessToken();
|
|
662
|
+
if (!token) {
|
|
663
|
+
Logger.debug("No token found");
|
|
263
664
|
return false;
|
|
264
|
-
|
|
265
|
-
|
|
665
|
+
}
|
|
666
|
+
if (this.checkTokenExpiration()) {
|
|
266
667
|
return false;
|
|
267
668
|
}
|
|
669
|
+
Logger.debug("Token is valid");
|
|
268
670
|
return true;
|
|
269
671
|
}
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
if (!token)
|
|
672
|
+
async getProfile() {
|
|
673
|
+
const storedToken = this.getAccessToken();
|
|
674
|
+
if (!storedToken)
|
|
274
675
|
return null;
|
|
275
|
-
|
|
276
|
-
|
|
676
|
+
// Check token expiration before processing
|
|
677
|
+
if (this.checkTokenExpiration()) {
|
|
277
678
|
return null;
|
|
278
679
|
}
|
|
279
|
-
return
|
|
680
|
+
return this.profile;
|
|
681
|
+
}
|
|
682
|
+
getSessionError() {
|
|
683
|
+
return null;
|
|
684
|
+
}
|
|
685
|
+
/**
|
|
686
|
+
* Complete authentication in popup window
|
|
687
|
+
* This should be called by popup apps when authentication is successful
|
|
688
|
+
*/
|
|
689
|
+
completePopupAuth(profile, targetOrigin) {
|
|
690
|
+
if (!isPopupWindow()) {
|
|
691
|
+
Logger.warn("completePopupAuth called outside of popup window");
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
try {
|
|
695
|
+
// Store the authentication data locally in the popup
|
|
696
|
+
this.profile = profile;
|
|
697
|
+
this.setToken(profile.userProfile.tokens.Bearer);
|
|
698
|
+
Logger.info("Authentication completed in popup, forwarding to parent");
|
|
699
|
+
}
|
|
700
|
+
catch (error) {
|
|
701
|
+
Logger.error("Failed to complete popup authentication", {
|
|
702
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
703
|
+
});
|
|
704
|
+
}
|
|
280
705
|
}
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
706
|
+
/**
|
|
707
|
+
* Report authentication error in popup window
|
|
708
|
+
*/
|
|
709
|
+
errorPopupAuth(error, targetOrigin) {
|
|
710
|
+
if (!isPopupWindow()) {
|
|
711
|
+
Logger.warn("errorPopupAuth called outside of popup window");
|
|
712
|
+
return;
|
|
287
713
|
}
|
|
288
|
-
|
|
714
|
+
Logger.warn("Reporting authentication error from popup");
|
|
289
715
|
}
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
716
|
+
}
|
|
717
|
+
// 🔹 Safe fallback for Node/SSR
|
|
718
|
+
function getDefaultStorage() {
|
|
719
|
+
if (typeof window !== "undefined" && window.localStorage) {
|
|
720
|
+
return window.localStorage;
|
|
721
|
+
}
|
|
722
|
+
const memoryStore = {};
|
|
723
|
+
return {
|
|
724
|
+
getItem: (key) => (key in memoryStore ? memoryStore[key] : null),
|
|
725
|
+
setItem: (key, value) => {
|
|
726
|
+
memoryStore[key] = value;
|
|
727
|
+
},
|
|
728
|
+
removeItem: (key) => {
|
|
729
|
+
delete memoryStore[key];
|
|
730
|
+
},
|
|
731
|
+
key: (i) => Object.keys(memoryStore)[i] ?? null,
|
|
732
|
+
get length() {
|
|
733
|
+
return Object.keys(memoryStore).length;
|
|
734
|
+
},
|
|
735
|
+
};
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
class CAMSMFAAuthenticator {
|
|
739
|
+
config;
|
|
740
|
+
attemptCount = 0;
|
|
741
|
+
maxAttempts = 3;
|
|
742
|
+
constructor(config) {
|
|
743
|
+
this.config = config;
|
|
744
|
+
}
|
|
745
|
+
async sendEmailOTP() {
|
|
294
746
|
try {
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
747
|
+
Logger.debug("Sending Email OTP");
|
|
748
|
+
// Implementation would call your API to send email OTP
|
|
749
|
+
// For now, return true as placeholder
|
|
750
|
+
return true;
|
|
751
|
+
}
|
|
752
|
+
catch (error) {
|
|
753
|
+
Logger.error("Failed to send Email OTP", { error });
|
|
754
|
+
return false;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
async verifyOTP(code, type) {
|
|
758
|
+
if (this.attemptCount >= this.maxAttempts) {
|
|
759
|
+
throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED, "Maximum MFA attempts exceeded");
|
|
760
|
+
}
|
|
761
|
+
this.attemptCount++;
|
|
762
|
+
try {
|
|
763
|
+
Logger.debug("Verifying MFA code", { type, attempt: this.attemptCount });
|
|
764
|
+
const response = await fetch(this.config.apiEndpoint || '/api/auth/verify-mfa', {
|
|
765
|
+
method: 'POST',
|
|
766
|
+
headers: {
|
|
767
|
+
'Content-Type': 'application/json',
|
|
768
|
+
'Authorization': `Bearer ${this.config.accessToken}`,
|
|
769
|
+
},
|
|
770
|
+
body: JSON.stringify({
|
|
771
|
+
provider: this.config.provider,
|
|
772
|
+
accessToken: this.config.accessToken,
|
|
773
|
+
idToken: this.config.idToken,
|
|
774
|
+
authenticationType: type,
|
|
775
|
+
MFACode: code,
|
|
776
|
+
appCode: this.config.appCode,
|
|
777
|
+
}),
|
|
778
|
+
});
|
|
779
|
+
if (!response.ok) {
|
|
780
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
781
|
+
}
|
|
782
|
+
const data = await response.json();
|
|
783
|
+
console.log("MFA Response >>>", data);
|
|
784
|
+
if (data.isAuthenticated) {
|
|
785
|
+
Logger.info("MFA verification successful");
|
|
786
|
+
this.resetAttempts();
|
|
787
|
+
return data;
|
|
788
|
+
}
|
|
789
|
+
else {
|
|
790
|
+
throw new CAMSError(exports.CAMSErrorType.API_VALIDATION_ERROR, data.message || "MFA verification failed");
|
|
304
791
|
}
|
|
305
792
|
}
|
|
306
793
|
catch (error) {
|
|
307
|
-
|
|
794
|
+
Logger.error("MFA verification failed", { error, attempt: this.attemptCount });
|
|
795
|
+
if (error instanceof CAMSError) {
|
|
796
|
+
throw error;
|
|
797
|
+
}
|
|
798
|
+
throw new CAMSError(exports.CAMSErrorType.API_VALIDATION_ERROR, `MFA verification failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
308
799
|
}
|
|
309
|
-
|
|
800
|
+
}
|
|
801
|
+
getRemainingAttempts() {
|
|
802
|
+
return Math.max(0, this.maxAttempts - this.attemptCount);
|
|
803
|
+
}
|
|
804
|
+
resetAttempts() {
|
|
805
|
+
this.attemptCount = 0;
|
|
310
806
|
}
|
|
311
807
|
}
|
|
312
808
|
|
|
809
|
+
exports.AuthFailureMessageSchema = AuthFailureMessageSchema;
|
|
313
810
|
exports.CAMSError = CAMSError;
|
|
314
|
-
exports.
|
|
811
|
+
exports.CAMSMFAAuthenticator = CAMSMFAAuthenticator;
|
|
812
|
+
exports.CAMSSessionManager = CAMSSessionManager;
|
|
315
813
|
exports.ErrorMessageSchema = ErrorMessageSchema;
|
|
814
|
+
exports.Logger = Logger;
|
|
316
815
|
exports.ProfileSchema = ProfileSchema;
|
|
317
|
-
exports.TokenManager = TokenManager;
|
|
318
|
-
exports.TokenMessageSchema = TokenMessageSchema;
|
|
319
|
-
exports.TokenSchema = TokenSchema;
|
|
320
816
|
exports.URLSchema = URLSchema;
|
|
817
|
+
exports.generateSecureWindowName = generateSecureWindowName;
|
|
818
|
+
exports.isPopupWindow = isPopupWindow;
|
|
321
819
|
exports.openCAMSPopUpLogin = openCAMSPopUpLogin;
|
|
322
820
|
exports.validateConfig = validateConfig;
|
|
323
821
|
|