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