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