@nibssplc/cams-sdk 0.0.1-beta.6 → 0.0.1-beta.62
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 +21 -0
- package/dist/auth.d.ts +18 -3
- package/dist/index.cjs.js +807 -197
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +5 -5
- package/dist/index.esm.js +800 -194
- package/dist/index.esm.js.map +1 -1
- package/dist/index.umd.js +809 -201
- package/dist/index.umd.js.map +1 -1
- package/dist/lib/Axiosinstance.d.ts +1 -0
- package/dist/lib/DeviceID.d.ts +4 -0
- package/dist/logger.d.ts +19 -0
- package/dist/sessionManager.d.ts +47 -0
- package/dist/types.d.ts +54 -8
- package/dist/validators.d.ts +27 -20
- package/package.json +25 -6
- package/dist/session.d.ts +0 -19
- package/dist/tokenManager.d.ts +0 -12
package/dist/index.umd.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
(function (global, factory) {
|
|
2
|
-
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('zod')) :
|
|
3
|
-
typeof define === 'function' && define.amd ? define(['exports', 'zod'], factory) :
|
|
4
|
-
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.CAMS = {}, global.zod));
|
|
5
|
-
})(this, (function (exports, zod) { 'use strict';
|
|
2
|
+
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('zod'), require('axios'), require('https')) :
|
|
3
|
+
typeof define === 'function' && define.amd ? define(['exports', 'zod', 'axios', 'https'], factory) :
|
|
4
|
+
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.CAMS = {}, global.zod, global.axios, global.https));
|
|
5
|
+
})(this, (function (exports, zod, axios, https) { 'use strict';
|
|
6
6
|
|
|
7
7
|
exports.CAMSErrorType = void 0;
|
|
8
8
|
(function (CAMSErrorType) {
|
|
@@ -12,229 +12,538 @@
|
|
|
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
|
+
roles: zod.z.array(zod.z.string()).optional(),
|
|
37
|
+
tokens: zod.z.object({
|
|
38
|
+
Nonce: zod.z.string(),
|
|
39
|
+
Bearer: zod.z.string(),
|
|
40
|
+
}),
|
|
41
|
+
}),
|
|
27
42
|
});
|
|
28
43
|
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(),
|
|
44
|
+
error: zod.z.string().min(1, "Error message cannot be empty"),
|
|
37
45
|
});
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
family_name: zod.z.string().optional(),
|
|
44
|
-
roles: zod.z.array(zod.z.string()).optional(),
|
|
46
|
+
const AuthFailureMessageSchema = zod.z.object({
|
|
47
|
+
type: zod.z.literal("AUTH_FAILURE"),
|
|
48
|
+
error: zod.z.string().min(1, "Error message cannot be empty"),
|
|
49
|
+
errorCode: zod.z.string(),
|
|
50
|
+
errorDetails: zod.z.object().or(zod.z.any()),
|
|
45
51
|
});
|
|
46
|
-
|
|
47
|
-
const URLSchema = zod.z.string().url().refine((url) => url.startsWith('https://'), { message: "Only HTTPS URLs are allowed" });
|
|
52
|
+
const URLSchema = zod.z.url();
|
|
48
53
|
|
|
54
|
+
exports.LogLevel = void 0;
|
|
55
|
+
(function (LogLevel) {
|
|
56
|
+
LogLevel[LogLevel["ERROR"] = 0] = "ERROR";
|
|
57
|
+
LogLevel[LogLevel["WARN"] = 1] = "WARN";
|
|
58
|
+
LogLevel[LogLevel["INFO"] = 2] = "INFO";
|
|
59
|
+
LogLevel[LogLevel["DEBUG"] = 3] = "DEBUG";
|
|
60
|
+
})(exports.LogLevel || (exports.LogLevel = {}));
|
|
61
|
+
class Logger {
|
|
62
|
+
static level = exports.LogLevel.DEBUG;
|
|
63
|
+
static prefix = '[CAMS-SDK]';
|
|
64
|
+
static isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';
|
|
65
|
+
static setLevel(level) {
|
|
66
|
+
Logger.level = level;
|
|
67
|
+
}
|
|
68
|
+
static error(message, context) {
|
|
69
|
+
if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.ERROR) {
|
|
70
|
+
console.error(`${Logger.prefix} ERROR:`, message, context || '');
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
static warn(message, context) {
|
|
74
|
+
if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.WARN) {
|
|
75
|
+
console.warn(`${Logger.prefix} WARN:`, message, context || '');
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
static info(message, context) {
|
|
79
|
+
if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.INFO) {
|
|
80
|
+
console.info(`${Logger.prefix} INFO:`, message, context || '');
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
static debug(message, context) {
|
|
84
|
+
if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.DEBUG) {
|
|
85
|
+
console.debug(`${Logger.prefix} DEBUG:`, message, context || '');
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Constants
|
|
91
|
+
const DEFAULT_AUTH_TIMEOUT = 300000; // 5 minutes
|
|
92
|
+
const DEFAULT_IDLE_TIMEOUT = 120000; // 2 minutes
|
|
93
|
+
const INITIAL_POLL_INTERVAL = 1000;
|
|
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 with proper binding
|
|
103
|
+
const NativeFunctions = {
|
|
104
|
+
addEventListener: typeof window !== "undefined" ? window.addEventListener.bind(window) : null,
|
|
105
|
+
removeEventListener: typeof window !== "undefined" ? window.removeEventListener.bind(window) : null,
|
|
106
|
+
setTimeout: typeof window !== "undefined" && window.setTimeout ? window.setTimeout.bind(window) : setTimeout,
|
|
107
|
+
clearTimeout: typeof window !== "undefined" && window.clearTimeout ? window.clearTimeout.bind(window) : 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
|
+
// Skip popup detection in test environments
|
|
120
|
+
if (typeof process !== "undefined" && process.env && process.env.NODE_ENV === "test") {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
return window.opener !== null && window.opener !== window;
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
/**
|
|
131
|
+
* Safely close a window with error handling for cross-origin restrictions
|
|
132
|
+
*/
|
|
133
|
+
const safeWindowClose = (window) => {
|
|
134
|
+
if (!window)
|
|
135
|
+
return;
|
|
136
|
+
try {
|
|
137
|
+
if (!window.closed) {
|
|
138
|
+
window.close();
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
Logger.debug("Error closing window (cross-origin restriction)", {
|
|
143
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
/**
|
|
148
|
+
* Center popup window on screen
|
|
149
|
+
*/
|
|
150
|
+
const getPopupPosition = (width, height) => {
|
|
151
|
+
if (typeof window === "undefined")
|
|
152
|
+
return { left: 0, top: 0 };
|
|
153
|
+
const left = Math.max(0, (window.screen.width - width) / 2);
|
|
154
|
+
const top = Math.max(0, (window.screen.height - height) / 2);
|
|
155
|
+
return { left, top };
|
|
156
|
+
};
|
|
157
|
+
/**
|
|
158
|
+
* Validate origin against expected domain with support for subdomains and Microsoft redirects
|
|
159
|
+
*/
|
|
160
|
+
const isValidOrigin = (eventOrigin, expectedOrigin, microsoftDomains = DEFAULT_MICROSOFT_DOMAINS) => {
|
|
161
|
+
try {
|
|
162
|
+
const originUrl = new URL(eventOrigin);
|
|
163
|
+
const expectedHostname = expectedOrigin.startsWith("http")
|
|
164
|
+
? new URL(expectedOrigin).hostname
|
|
165
|
+
: expectedOrigin;
|
|
166
|
+
// Check Microsoft domains for Azure AD redirects
|
|
167
|
+
const isMicrosoftDomain = microsoftDomains.some(domain => originUrl.hostname === domain || originUrl.hostname.endsWith(domain));
|
|
168
|
+
// Allow exact match, subdomains, or Microsoft domains
|
|
169
|
+
return (originUrl.hostname === expectedHostname ||
|
|
170
|
+
originUrl.hostname.endsWith("." + expectedHostname) ||
|
|
171
|
+
isMicrosoftDomain);
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
/**
|
|
178
|
+
* Safely check if window is closed with cross-origin handling
|
|
179
|
+
*/
|
|
180
|
+
const isWindowClosed = (window) => {
|
|
181
|
+
if (!window)
|
|
182
|
+
return true;
|
|
183
|
+
try {
|
|
184
|
+
return window.closed;
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
// Cross-origin error means we can't access the property
|
|
188
|
+
// This typically happens when redirected to external auth providers
|
|
189
|
+
Logger.debug("Cannot access window.closed due to cross-origin restrictions - assuming window is still open", error);
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
/**
|
|
194
|
+
* Safely add message event listener with error handling
|
|
195
|
+
*/
|
|
196
|
+
const addMessageListener = (listener) => {
|
|
197
|
+
if (!NativeFunctions.addEventListener) {
|
|
198
|
+
throw new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Message listener not available in current environment");
|
|
199
|
+
}
|
|
200
|
+
const wrappedListener = (event) => {
|
|
201
|
+
try {
|
|
202
|
+
listener(event);
|
|
203
|
+
}
|
|
204
|
+
catch (error) {
|
|
205
|
+
Logger.error("Error in message listener", {
|
|
206
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
NativeFunctions.addEventListener("message", wrappedListener);
|
|
211
|
+
return () => {
|
|
212
|
+
if (NativeFunctions.removeEventListener) {
|
|
213
|
+
NativeFunctions.removeEventListener("message", wrappedListener);
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
};
|
|
217
|
+
/**
|
|
218
|
+
* Validate configuration and return parsed URL
|
|
219
|
+
*/
|
|
49
220
|
function validateConfig(config) {
|
|
50
|
-
var _a;
|
|
51
|
-
// Validate URL format
|
|
52
221
|
const urlValidation = URLSchema.safeParse(config.camsUrl);
|
|
53
222
|
if (!urlValidation.success) {
|
|
54
|
-
throw new CAMSError(exports.CAMSErrorType.INVALID_URL,
|
|
223
|
+
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Invalid CAMS URL format");
|
|
55
224
|
}
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');
|
|
59
|
-
}
|
|
60
|
-
const url = new URL(config.camsUrl); // URLSchema already validated this
|
|
61
|
-
const isAllowed = config.allowedDomains.some(domain => url.hostname === domain || url.hostname.endsWith('.' + domain));
|
|
62
|
-
if (!isAllowed) {
|
|
63
|
-
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'URL not in allowed domains list');
|
|
225
|
+
if (!config.messageOrigin) {
|
|
226
|
+
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Message Origin must be specified for security");
|
|
64
227
|
}
|
|
228
|
+
return new URL(config.camsUrl);
|
|
65
229
|
}
|
|
230
|
+
/**
|
|
231
|
+
* Open CAMS authentication popup and handle the authentication flow
|
|
232
|
+
*/
|
|
66
233
|
function openCAMSPopUpLogin(config) {
|
|
67
234
|
return new Promise((resolve, reject) => {
|
|
68
|
-
|
|
69
|
-
|
|
235
|
+
// Environment validation
|
|
236
|
+
if (typeof window === "undefined") {
|
|
237
|
+
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Cannot open popup in server-side environment"));
|
|
238
|
+
return;
|
|
70
239
|
}
|
|
71
|
-
|
|
72
|
-
|
|
240
|
+
if (isPopupWindow()) {
|
|
241
|
+
Logger.warn("Attempted to open popup from within popup window");
|
|
242
|
+
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Cannot open authentication popup from within popup window"));
|
|
73
243
|
return;
|
|
74
244
|
}
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
245
|
+
// Initialize logging
|
|
246
|
+
if (config.debug)
|
|
247
|
+
Logger.setLevel(exports.LogLevel.DEBUG);
|
|
248
|
+
Logger.info("Starting CAMS authentication", { url: config.camsUrl });
|
|
249
|
+
// Validate configuration
|
|
250
|
+
let validatedUrl;
|
|
79
251
|
try {
|
|
80
|
-
|
|
252
|
+
validatedUrl = validateConfig(config);
|
|
253
|
+
Logger.debug("Configuration validation passed");
|
|
81
254
|
}
|
|
82
255
|
catch (error) {
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window. Please allow popups."));
|
|
256
|
+
Logger.error("Configuration validation failed", {
|
|
257
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
258
|
+
});
|
|
259
|
+
reject(error);
|
|
88
260
|
return;
|
|
89
261
|
}
|
|
262
|
+
// Extract configuration with defaults
|
|
263
|
+
const { messageOrigin, windowHeight = 600, windowWidth = 500, authTimeout = DEFAULT_AUTH_TIMEOUT, idleTimeout = DEFAULT_IDLE_TIMEOUT, allowedRedirectDomains = [...DEFAULT_MICROSOFT_DOMAINS, messageOrigin], } = config;
|
|
264
|
+
// State management
|
|
265
|
+
let authWindow = null;
|
|
266
|
+
let authTimeoutId = null;
|
|
267
|
+
let idleTimeoutId = null;
|
|
268
|
+
let checkClosedInterval = null;
|
|
269
|
+
let removeMessageListener = null;
|
|
270
|
+
let hasReceivedValidMessage = false;
|
|
271
|
+
/**
|
|
272
|
+
* Clean up all resources and timeouts
|
|
273
|
+
*/
|
|
90
274
|
const cleanup = () => {
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
275
|
+
if (removeMessageListener) {
|
|
276
|
+
removeMessageListener();
|
|
277
|
+
removeMessageListener = null;
|
|
278
|
+
}
|
|
279
|
+
if (idleTimeoutId)
|
|
280
|
+
NativeFunctions.clearTimeout(idleTimeoutId);
|
|
281
|
+
if (authTimeoutId)
|
|
282
|
+
NativeFunctions.clearTimeout(authTimeoutId);
|
|
94
283
|
if (checkClosedInterval)
|
|
95
|
-
|
|
284
|
+
NativeFunctions.clearTimeout(checkClosedInterval);
|
|
285
|
+
idleTimeoutId = null;
|
|
286
|
+
authTimeoutId = null;
|
|
287
|
+
checkClosedInterval = null;
|
|
96
288
|
};
|
|
289
|
+
/**
|
|
290
|
+
* Clean up and close the popup window, then reject with error
|
|
291
|
+
*/
|
|
97
292
|
const cleanupAndClose = (error) => {
|
|
98
293
|
cleanup();
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
294
|
+
safeWindowClose(authWindow);
|
|
295
|
+
if (error) {
|
|
296
|
+
reject(error);
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
/**
|
|
300
|
+
* Reset idle timeout on user activity
|
|
301
|
+
*/
|
|
302
|
+
const resetIdleTimeout = () => {
|
|
303
|
+
if (idleTimeoutId)
|
|
304
|
+
NativeFunctions.clearTimeout(idleTimeoutId);
|
|
305
|
+
Logger.debug("Resetting idle timeout", { idleTimeout });
|
|
306
|
+
idleTimeoutId = NativeFunctions.setTimeout(() => {
|
|
307
|
+
Logger.warn("Authentication idle timeout reached", { idleTimeout });
|
|
308
|
+
cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timed out due to inactivity after ${idleTimeout}ms`));
|
|
309
|
+
}, idleTimeout);
|
|
310
|
+
};
|
|
311
|
+
/**
|
|
312
|
+
* Set up popup window closure detection with cross-origin handling
|
|
313
|
+
*/
|
|
314
|
+
const setupClosureDetection = () => {
|
|
315
|
+
let pollInterval = INITIAL_POLL_INTERVAL;
|
|
316
|
+
const checkClosed = () => {
|
|
317
|
+
// Skip closure detection when on Microsoft domains
|
|
318
|
+
if (authWindow) {
|
|
319
|
+
try {
|
|
320
|
+
const currentUrl = authWindow.location.href;
|
|
321
|
+
const isMicrosoftDomain = allowedRedirectDomains.some(domain => currentUrl.includes(domain));
|
|
322
|
+
if (isMicrosoftDomain) {
|
|
323
|
+
Logger.debug("Skipping closure check - on Microsoft domain");
|
|
324
|
+
checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
catch (error) {
|
|
329
|
+
// Cross-origin error - assume we're on Microsoft domain and skip check
|
|
330
|
+
Logger.debug("Cross-origin error - skipping closure check");
|
|
331
|
+
checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
102
334
|
}
|
|
335
|
+
const isClosed = isWindowClosed(authWindow);
|
|
336
|
+
if (isClosed && !hasReceivedValidMessage) {
|
|
337
|
+
Logger.info("Authentication window closed by user");
|
|
338
|
+
cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);
|
|
342
|
+
};
|
|
343
|
+
checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);
|
|
344
|
+
};
|
|
345
|
+
/**
|
|
346
|
+
* Handle incoming message events from the popup
|
|
347
|
+
*/
|
|
348
|
+
const handleMessage = (event) => {
|
|
349
|
+
Logger.debug("Received message", {
|
|
350
|
+
origin: event.origin,
|
|
351
|
+
expectedOrigin: messageOrigin,
|
|
352
|
+
data: event.data,
|
|
353
|
+
});
|
|
354
|
+
// Security: Validate origin
|
|
355
|
+
if (!isValidOrigin(event.origin, messageOrigin, allowedRedirectDomains)) {
|
|
356
|
+
Logger.warn("Blocked message from unauthorized origin", {
|
|
357
|
+
origin: event.origin,
|
|
358
|
+
expected: messageOrigin,
|
|
359
|
+
data: event.data,
|
|
360
|
+
});
|
|
361
|
+
return;
|
|
103
362
|
}
|
|
104
|
-
|
|
105
|
-
|
|
363
|
+
// Security: Validate message source
|
|
364
|
+
if (event.source !== authWindow) {
|
|
365
|
+
Logger.warn("Message from unexpected source", {
|
|
366
|
+
source: event.source,
|
|
367
|
+
origin: event.origin,
|
|
368
|
+
expected: messageOrigin,
|
|
369
|
+
data: event.data,
|
|
370
|
+
});
|
|
371
|
+
return;
|
|
106
372
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
const sanitizedOrigin = event.origin.replace(/[\r\n]/g, '');
|
|
114
|
-
console.warn("Blocked message from origin:", sanitizedOrigin);
|
|
373
|
+
// Mark that we've received a valid message (prevents false closure detection)
|
|
374
|
+
hasReceivedValidMessage = true;
|
|
375
|
+
// Handle heartbeat messages (reset idle timeout)
|
|
376
|
+
if (event.data?.type === "heartbeat") {
|
|
377
|
+
Logger.debug("Received heartbeat message");
|
|
378
|
+
resetIdleTimeout();
|
|
115
379
|
return;
|
|
116
380
|
}
|
|
117
|
-
//
|
|
118
|
-
|
|
119
|
-
|
|
381
|
+
// Process authentication messages
|
|
382
|
+
processAuthenticationMessage(event.data);
|
|
383
|
+
};
|
|
384
|
+
/**
|
|
385
|
+
* Process and validate authentication message payloads
|
|
386
|
+
*/
|
|
387
|
+
const processAuthenticationMessage = (data) => {
|
|
388
|
+
// Success case: Valid profile received
|
|
389
|
+
const profileValidation = ProfileSchema.safeParse(data);
|
|
390
|
+
if (profileValidation.success) {
|
|
391
|
+
Logger.info("Authentication successful");
|
|
120
392
|
cleanupAndClose();
|
|
121
|
-
resolve(
|
|
393
|
+
resolve(profileValidation.data);
|
|
122
394
|
return;
|
|
123
395
|
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
396
|
+
// Authentication failure case
|
|
397
|
+
const authFailureValidation = AuthFailureMessageSchema.safeParse(data);
|
|
398
|
+
if (authFailureValidation.success) {
|
|
399
|
+
const { error, errorCode, errorDetails } = authFailureValidation.data;
|
|
400
|
+
Logger.warn("Authentication failure received", {
|
|
401
|
+
error,
|
|
402
|
+
errorCode,
|
|
403
|
+
errorDetails,
|
|
404
|
+
});
|
|
405
|
+
cleanupAndClose(new CAMSError(exports.CAMSErrorType.API_VALIDATION_ERROR, `Authentication failed: ${error}${errorCode ? ` (${errorCode})` : ''}`));
|
|
127
406
|
return;
|
|
128
407
|
}
|
|
408
|
+
// Generic error case
|
|
409
|
+
const errorValidation = ErrorMessageSchema.safeParse(data);
|
|
410
|
+
if (errorValidation.success) {
|
|
411
|
+
Logger.warn("Authentication error received", {
|
|
412
|
+
error: errorValidation.data.error,
|
|
413
|
+
});
|
|
414
|
+
cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, `Authentication failed: ${errorValidation.data.error}`));
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
// Invalid message format
|
|
418
|
+
Logger.error("Invalid message format received", {
|
|
419
|
+
messageData: data,
|
|
420
|
+
dataType: typeof data,
|
|
421
|
+
profileValidationError: profileValidation.error?.issues,
|
|
422
|
+
authFailureValidationError: authFailureValidation.error?.issues,
|
|
423
|
+
errorValidationError: errorValidation.error?.issues,
|
|
424
|
+
});
|
|
129
425
|
cleanupAndClose(new CAMSError(exports.CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
|
|
130
426
|
};
|
|
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
|
|
427
|
+
// Main authentication flow execution
|
|
140
428
|
try {
|
|
141
|
-
window
|
|
429
|
+
// Open popup window
|
|
430
|
+
const { left, top } = getPopupPosition(windowWidth, windowHeight);
|
|
431
|
+
const secureWindowName = generateSecureWindowName();
|
|
432
|
+
Logger.debug("Opening popup window", {
|
|
433
|
+
width: windowWidth,
|
|
434
|
+
height: windowHeight,
|
|
435
|
+
left,
|
|
436
|
+
top,
|
|
437
|
+
});
|
|
438
|
+
authWindow = window.open(validatedUrl.toString(), secureWindowName, `width=${windowWidth},height=${windowHeight},left=${left},top=${top},${WINDOW_FEATURES}`);
|
|
439
|
+
// Check for popup blocking
|
|
440
|
+
if (!authWindow) {
|
|
441
|
+
Logger.error("Popup window blocked or failed to open");
|
|
442
|
+
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
// Check for immediate closure (aggressive popup blockers)
|
|
446
|
+
if (isWindowClosed(authWindow)) {
|
|
447
|
+
Logger.error("Popup immediately closed by blocker");
|
|
448
|
+
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
Logger.debug("Popup window opened successfully");
|
|
452
|
+
// Set up message listener
|
|
453
|
+
removeMessageListener = addMessageListener(handleMessage);
|
|
454
|
+
Logger.debug("Message listener attached");
|
|
455
|
+
// Set up timeouts
|
|
456
|
+
Logger.debug("Setting authentication timeout", { authTimeout });
|
|
457
|
+
authTimeoutId = NativeFunctions.setTimeout(() => {
|
|
458
|
+
Logger.warn("Authentication timeout reached", { authTimeout });
|
|
459
|
+
cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication process exceeded time limit of ${authTimeout}ms`));
|
|
460
|
+
}, authTimeout);
|
|
461
|
+
resetIdleTimeout();
|
|
462
|
+
setupClosureDetection();
|
|
463
|
+
// Focus popup for better UX
|
|
464
|
+
try {
|
|
465
|
+
authWindow.focus();
|
|
466
|
+
}
|
|
467
|
+
catch (error) {
|
|
468
|
+
Logger.debug("Could not focus popup window (cross-origin restriction)");
|
|
469
|
+
}
|
|
142
470
|
}
|
|
143
471
|
catch (error) {
|
|
472
|
+
Logger.error("Failed to initialize authentication popup", {
|
|
473
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
474
|
+
});
|
|
144
475
|
cleanup();
|
|
145
|
-
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to
|
|
146
|
-
|
|
476
|
+
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to initialize authentication: " +
|
|
477
|
+
(error instanceof Error ? error.message : "Unknown error")));
|
|
147
478
|
}
|
|
148
479
|
});
|
|
149
480
|
}
|
|
150
481
|
|
|
151
|
-
class
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
482
|
+
class CAMSSessionManager {
|
|
483
|
+
storage;
|
|
484
|
+
keyPrefix;
|
|
485
|
+
events;
|
|
486
|
+
token = null;
|
|
487
|
+
profile = null;
|
|
488
|
+
constructor(storage = null, keyPrefix, events = {}) {
|
|
489
|
+
this.storage = storage || getDefaultStorage();
|
|
490
|
+
this.keyPrefix = keyPrefix ?? "CAMS-SDK";
|
|
491
|
+
this.events = events;
|
|
156
492
|
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
this.token = parsed;
|
|
160
|
-
this.storage.setItem(this.storageKey, JSON.stringify(parsed));
|
|
493
|
+
setItem(key, value) {
|
|
494
|
+
this.storage.setItem(`${this.keyPrefix}:${key}`, value);
|
|
161
495
|
}
|
|
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
|
-
}
|
|
185
|
-
}
|
|
186
|
-
clearToken() {
|
|
187
|
-
this.token = null;
|
|
188
|
-
this.storage.removeItem(this.storageKey);
|
|
496
|
+
getItem(key) {
|
|
497
|
+
return this.storage.getItem(`${this.keyPrefix}:${key}`);
|
|
189
498
|
}
|
|
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;
|
|
499
|
+
removeItem(key) {
|
|
500
|
+
this.storage.removeItem(`${this.keyPrefix}:${key}`);
|
|
194
501
|
}
|
|
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;
|
|
502
|
+
clear() {
|
|
503
|
+
// clear only CAMS-prefixed items
|
|
504
|
+
Object.keys(this.storage).forEach((k) => {
|
|
505
|
+
if (k.startsWith(this.keyPrefix)) {
|
|
506
|
+
this.storage.removeItem(k);
|
|
212
507
|
}
|
|
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;
|
|
508
|
+
});
|
|
223
509
|
}
|
|
224
510
|
async login(config) {
|
|
225
|
-
var _a, _b, _c, _d, _e, _f, _g;
|
|
226
511
|
try {
|
|
227
|
-
(
|
|
512
|
+
Logger.info("Session login started");
|
|
513
|
+
// If we're in a popup, don't attempt to open another popup
|
|
514
|
+
if (isPopupWindow()) {
|
|
515
|
+
Logger.warn("Cannot initiate login from popup window");
|
|
516
|
+
throw new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Cannot initiate authentication from within popup window");
|
|
517
|
+
}
|
|
518
|
+
if (this.events.onAuthStart)
|
|
519
|
+
this.events.onAuthStart();
|
|
228
520
|
let attempts = 0;
|
|
229
|
-
const maxAttempts = (
|
|
521
|
+
const maxAttempts = (config.retryAttempts ?? 0) + 1;
|
|
522
|
+
Logger.debug("Login retry configuration", { maxAttempts });
|
|
230
523
|
while (attempts < maxAttempts) {
|
|
231
524
|
try {
|
|
525
|
+
attempts++;
|
|
526
|
+
Logger.debug("Login attempt", { attempt: attempts, maxAttempts });
|
|
527
|
+
// Add exponential backoff delay for retries
|
|
528
|
+
if (attempts > 1) {
|
|
529
|
+
const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay
|
|
530
|
+
Logger.debug("Retry delay", { delay });
|
|
531
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
532
|
+
}
|
|
232
533
|
const response = await openCAMSPopUpLogin(config);
|
|
233
|
-
(
|
|
534
|
+
Logger.debug("Login Response", response);
|
|
535
|
+
this.profile = response;
|
|
536
|
+
this.setToken(response.userProfile.tokens.Bearer);
|
|
537
|
+
Logger.info("Session login successful");
|
|
538
|
+
if (this.events.onAuthSuccess)
|
|
539
|
+
this.events.onAuthSuccess(response);
|
|
234
540
|
return response;
|
|
235
541
|
}
|
|
236
542
|
catch (error) {
|
|
237
|
-
|
|
543
|
+
Logger.warn("Login attempt failed", {
|
|
544
|
+
attempt: attempts,
|
|
545
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
546
|
+
});
|
|
238
547
|
if (attempts >= maxAttempts || !(error instanceof CAMSError)) {
|
|
239
548
|
throw error;
|
|
240
549
|
}
|
|
@@ -242,82 +551,381 @@
|
|
|
242
551
|
if (![exports.CAMSErrorType.TIMEOUT, exports.CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {
|
|
243
552
|
throw error;
|
|
244
553
|
}
|
|
554
|
+
Logger.info("Retrying login", { nextAttempt: attempts + 1 });
|
|
245
555
|
}
|
|
246
556
|
}
|
|
247
|
-
throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED,
|
|
557
|
+
throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED, "Max retry attempts exceeded");
|
|
248
558
|
}
|
|
249
559
|
catch (error) {
|
|
250
|
-
const
|
|
251
|
-
|
|
252
|
-
|
|
560
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
561
|
+
const camsError = error instanceof CAMSError
|
|
562
|
+
? error
|
|
563
|
+
: new CAMSError(exports.CAMSErrorType.USER_CANCELLED, errorMessage);
|
|
564
|
+
Logger.error("Session login failed", {
|
|
565
|
+
error: camsError.message,
|
|
566
|
+
type: camsError.type,
|
|
567
|
+
});
|
|
568
|
+
if (this.events.onAuthError)
|
|
569
|
+
this.events.onAuthError(camsError);
|
|
253
570
|
throw camsError;
|
|
254
571
|
}
|
|
255
572
|
}
|
|
256
573
|
async logout() {
|
|
257
|
-
|
|
574
|
+
Logger.info("Session logout");
|
|
575
|
+
this.clearToken();
|
|
258
576
|
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
577
|
+
setToken(token) {
|
|
578
|
+
this.token = token;
|
|
579
|
+
this.storage.setItem(this.keyPrefix, token);
|
|
580
|
+
Logger.debug("Token stored", { storageKey: this.keyPrefix });
|
|
581
|
+
}
|
|
582
|
+
getAccessToken() {
|
|
583
|
+
// Return cached token if available, avoiding redundant storage access
|
|
584
|
+
if (this.token)
|
|
585
|
+
return this.token;
|
|
586
|
+
const raw = this.storage.getItem(this.keyPrefix);
|
|
587
|
+
if (!raw)
|
|
588
|
+
return null;
|
|
589
|
+
this.token = raw;
|
|
590
|
+
Logger.debug("Token loaded from storage");
|
|
591
|
+
return this.token;
|
|
592
|
+
}
|
|
593
|
+
clearToken() {
|
|
594
|
+
this.token = null;
|
|
595
|
+
this.storage.removeItem(this.keyPrefix);
|
|
596
|
+
Logger.debug("Token cleared");
|
|
597
|
+
}
|
|
598
|
+
isExpired() {
|
|
599
|
+
const token = this.getAccessToken();
|
|
262
600
|
if (!token)
|
|
601
|
+
return true;
|
|
602
|
+
try {
|
|
603
|
+
const parts = token.split(".");
|
|
604
|
+
if (parts.length < 3)
|
|
605
|
+
return true; // Invalid JWT format
|
|
606
|
+
const payload = JSON.parse(atob(parts[1]));
|
|
607
|
+
if (typeof payload.exp !== "number")
|
|
608
|
+
return true;
|
|
609
|
+
const exp = payload.exp * 1000;
|
|
610
|
+
return Date.now() > exp;
|
|
611
|
+
}
|
|
612
|
+
catch (error) {
|
|
613
|
+
Logger.warn("Failed to parse JWT token", {
|
|
614
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
615
|
+
});
|
|
616
|
+
return true;
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
isPaddedExpired() {
|
|
620
|
+
const token = this.getAccessToken();
|
|
621
|
+
if (!token)
|
|
622
|
+
return true;
|
|
623
|
+
try {
|
|
624
|
+
const parts = token.split(".");
|
|
625
|
+
if (parts.length < 3)
|
|
626
|
+
return true; // Invalid JWT format
|
|
627
|
+
const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
628
|
+
const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=");
|
|
629
|
+
const payload = JSON.parse(atob(padded));
|
|
630
|
+
if (typeof payload.exp !== "number")
|
|
631
|
+
return true;
|
|
632
|
+
const exp = payload.exp * 1000;
|
|
633
|
+
return Date.now() > exp;
|
|
634
|
+
}
|
|
635
|
+
catch (error) {
|
|
636
|
+
Logger.warn("Failed to parse JWT token", {
|
|
637
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
638
|
+
});
|
|
639
|
+
return true;
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
checkTokenExpiration() {
|
|
643
|
+
if (this.isExpired()) {
|
|
644
|
+
Logger.info("Token expired");
|
|
645
|
+
if (this.events.onTokenExpired)
|
|
646
|
+
this.events.onTokenExpired();
|
|
647
|
+
return true;
|
|
648
|
+
}
|
|
649
|
+
return false;
|
|
650
|
+
}
|
|
651
|
+
isAuthenticated() {
|
|
652
|
+
const token = this.getAccessToken();
|
|
653
|
+
if (!token) {
|
|
654
|
+
Logger.debug("No Token Found");
|
|
263
655
|
return false;
|
|
264
|
-
|
|
265
|
-
|
|
656
|
+
}
|
|
657
|
+
if (this.checkTokenExpiration()) {
|
|
266
658
|
return false;
|
|
267
659
|
}
|
|
660
|
+
Logger.debug("Token is valid");
|
|
268
661
|
return true;
|
|
269
662
|
}
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
if (!token)
|
|
663
|
+
async getProfile() {
|
|
664
|
+
const storedToken = this.getAccessToken();
|
|
665
|
+
if (!storedToken)
|
|
274
666
|
return null;
|
|
275
|
-
|
|
276
|
-
|
|
667
|
+
// Check token expiration before processing
|
|
668
|
+
if (this.checkTokenExpiration()) {
|
|
277
669
|
return null;
|
|
278
670
|
}
|
|
279
|
-
return
|
|
671
|
+
return this.profile;
|
|
280
672
|
}
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
673
|
+
getSessionError() {
|
|
674
|
+
return null;
|
|
675
|
+
}
|
|
676
|
+
/**
|
|
677
|
+
* Complete authentication in popup window
|
|
678
|
+
* This should be called by popup apps when authentication is successful
|
|
679
|
+
*/
|
|
680
|
+
completePopupAuth(profile, targetOrigin) {
|
|
681
|
+
if (!isPopupWindow()) {
|
|
682
|
+
Logger.warn("completePopupAuth called outside of popup window");
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
try {
|
|
686
|
+
// Store the authentication data locally in the popup
|
|
687
|
+
this.profile = profile;
|
|
688
|
+
this.setToken(profile.userProfile.tokens.Bearer);
|
|
689
|
+
Logger.info("Authentication completed in popup, forwarding to parent");
|
|
690
|
+
}
|
|
691
|
+
catch (error) {
|
|
692
|
+
Logger.error("Failed to complete popup authentication", {
|
|
693
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
694
|
+
});
|
|
287
695
|
}
|
|
288
|
-
return atob(str);
|
|
289
696
|
}
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
697
|
+
/**
|
|
698
|
+
* Report authentication error in popup window
|
|
699
|
+
*/
|
|
700
|
+
errorPopupAuth(error, targetOrigin) {
|
|
701
|
+
if (!isPopupWindow()) {
|
|
702
|
+
Logger.warn("errorPopupAuth called outside of popup window");
|
|
703
|
+
return;
|
|
704
|
+
}
|
|
705
|
+
Logger.warn("Reporting authentication error from popup");
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
// 🔹 Safe fallback for Node/SSR
|
|
709
|
+
function getDefaultStorage() {
|
|
710
|
+
if (typeof window !== "undefined" && window.localStorage) {
|
|
711
|
+
return window.localStorage;
|
|
712
|
+
}
|
|
713
|
+
const memoryStore = {};
|
|
714
|
+
return {
|
|
715
|
+
getItem: (key) => (key in memoryStore ? memoryStore[key] : null),
|
|
716
|
+
setItem: (key, value) => {
|
|
717
|
+
memoryStore[key] = value;
|
|
718
|
+
},
|
|
719
|
+
removeItem: (key) => {
|
|
720
|
+
delete memoryStore[key];
|
|
721
|
+
},
|
|
722
|
+
key: (i) => Object.keys(memoryStore)[i] ?? null,
|
|
723
|
+
get length() {
|
|
724
|
+
return Object.keys(memoryStore).length;
|
|
725
|
+
},
|
|
726
|
+
};
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
// Function to parse userAgent and generate a device ID
|
|
730
|
+
const GenerateDeviceId = () => {
|
|
731
|
+
if (typeof window === "undefined" || !window.navigator) {
|
|
732
|
+
return "unknown-device";
|
|
733
|
+
}
|
|
734
|
+
const userAgent = window.navigator.userAgent;
|
|
735
|
+
let deviceId = "";
|
|
736
|
+
// Parse browser, version, OS, and device type
|
|
737
|
+
const browserMatch = Array.from(userAgent.matchAll(/(Chrome|Firefox|Safari|Edge|Opera)\/([\d.]+)/gi));
|
|
738
|
+
const osMatch = Array.from(userAgent.matchAll(/\(([^)]+)\)/g));
|
|
739
|
+
const isMobile = /Mobile|Android|iPhone|iPad/i.test(userAgent);
|
|
740
|
+
// Browser info
|
|
741
|
+
if (browserMatch.length > 0) {
|
|
742
|
+
const [, browserName, browserVersion] = browserMatch[0];
|
|
743
|
+
const majorVersion = browserVersion.split(".")[0];
|
|
744
|
+
deviceId += `${browserName}-${majorVersion}`;
|
|
745
|
+
}
|
|
746
|
+
else {
|
|
747
|
+
deviceId += "UnknownBrowser";
|
|
748
|
+
}
|
|
749
|
+
// OS info
|
|
750
|
+
if (osMatch.length > 0) {
|
|
751
|
+
const osInfo = osMatch[0][1]
|
|
752
|
+
.split(";")[0]
|
|
753
|
+
.trim()
|
|
754
|
+
.replace(/[\s/()]/g, "_");
|
|
755
|
+
deviceId += `_${osInfo}`;
|
|
756
|
+
}
|
|
757
|
+
else {
|
|
758
|
+
deviceId += "_UnknownOS";
|
|
759
|
+
}
|
|
760
|
+
// Device type
|
|
761
|
+
deviceId += isMobile ? "_Mobile" : "_Desktop";
|
|
762
|
+
// Add a simple hash of userAgent for uniqueness
|
|
763
|
+
const hash = btoa(userAgent).slice(0, 8);
|
|
764
|
+
deviceId += `_${hash}`;
|
|
765
|
+
return deviceId.replace(/[^a-zA-Z0-9-_]/g, "_") ?? "unknown-device";
|
|
766
|
+
};
|
|
767
|
+
const APIHeaders = {
|
|
768
|
+
"X-DEVICE-ID": GenerateDeviceId(),
|
|
769
|
+
"X-API-VERSION": "1.0",
|
|
770
|
+
};
|
|
771
|
+
|
|
772
|
+
// Creates an Axios instance with a base URL determined by the environment (production or development).
|
|
773
|
+
const axiosInstance = axios.create({
|
|
774
|
+
httpsAgent: new https.Agent({ rejectUnauthorized: false }),
|
|
775
|
+
headers: {
|
|
776
|
+
"Content-Type": "application/json",
|
|
777
|
+
...APIHeaders,
|
|
778
|
+
},
|
|
779
|
+
});
|
|
780
|
+
// Intercepts outgoing requests to add authorization token, version header, and timeout settings.
|
|
781
|
+
axiosInstance.interceptors.request.use((config) => {
|
|
782
|
+
config.timeout = Number(process.env.NEXT_PUBLIC_API_TIMEOUT ?? 605000);
|
|
783
|
+
config.timeoutErrorMessage = "Operation Timed Out"; // Custom error message for timeouts.
|
|
784
|
+
return config; // Returns the modified request configuration.
|
|
785
|
+
}, (axiosError) => {
|
|
786
|
+
// Handles request errors.
|
|
787
|
+
return {
|
|
788
|
+
status: axiosError.response?.status, // Extracts HTTP status from the error response.
|
|
789
|
+
message: axiosError.message, // Extracts the error message.
|
|
790
|
+
data: axiosError.response?.data, // Extracts response data from the error.
|
|
791
|
+
};
|
|
792
|
+
});
|
|
793
|
+
|
|
794
|
+
class CAMSMFAAuthenticator {
|
|
795
|
+
attemptCount = 0;
|
|
796
|
+
maxAttempts = 3;
|
|
797
|
+
constructor() {
|
|
798
|
+
Logger.info("CAMS MFA Authenticator initialized");
|
|
799
|
+
}
|
|
800
|
+
async GetUserMFAConfig(config) {
|
|
801
|
+
const response = await axios.post(config.APIAuthEndpoint, {
|
|
802
|
+
provider: config.provider,
|
|
803
|
+
accessToken: config.accessToken,
|
|
804
|
+
idToken: config.idToken,
|
|
805
|
+
});
|
|
806
|
+
Logger.debug("GetUserMFAConfig Response", response);
|
|
807
|
+
if (response) {
|
|
808
|
+
return response.data;
|
|
809
|
+
}
|
|
810
|
+
else {
|
|
811
|
+
return {
|
|
812
|
+
isValid: false,
|
|
813
|
+
message: `Failed to retrieve MFA configuration. ${response.statusText}`,
|
|
814
|
+
userInfo: {
|
|
815
|
+
id: 0,
|
|
816
|
+
email: "",
|
|
817
|
+
name: "",
|
|
818
|
+
isMFAEnabled: false,
|
|
819
|
+
},
|
|
820
|
+
};
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
async VerifyMFAOTP(ValidateRequest, MFAEndpoint) {
|
|
824
|
+
if (this.attemptCount >= this.maxAttempts) {
|
|
825
|
+
throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED, "Maximum MFA attempts exceeded");
|
|
826
|
+
}
|
|
827
|
+
this.attemptCount++;
|
|
294
828
|
try {
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
829
|
+
Logger.debug("Verifying User MFA Code", { attempt: this.attemptCount });
|
|
830
|
+
const response = await axiosInstance.post(MFAEndpoint, ValidateRequest);
|
|
831
|
+
if (response.status != 200) {
|
|
832
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
833
|
+
}
|
|
834
|
+
const data = response.data;
|
|
835
|
+
console.log("MFA Response >>>", data);
|
|
836
|
+
if (data.isValid) {
|
|
837
|
+
Logger.info("MFA verification successful");
|
|
838
|
+
this.ResetUserAttempts();
|
|
839
|
+
return data;
|
|
840
|
+
}
|
|
841
|
+
else {
|
|
842
|
+
throw new CAMSError(exports.CAMSErrorType.API_VALIDATION_ERROR, "User Verification failed");
|
|
304
843
|
}
|
|
305
844
|
}
|
|
306
845
|
catch (error) {
|
|
307
|
-
|
|
846
|
+
Logger.error("MFA verification failed", {
|
|
847
|
+
error,
|
|
848
|
+
attempt: this.attemptCount,
|
|
849
|
+
});
|
|
850
|
+
if (error instanceof CAMSError) {
|
|
851
|
+
throw error;
|
|
852
|
+
}
|
|
853
|
+
throw new CAMSError(exports.CAMSErrorType.API_VALIDATION_ERROR, `MFA verification failed: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
308
854
|
}
|
|
309
|
-
|
|
855
|
+
}
|
|
856
|
+
async LoginADCredentials({ username, password, MFACode }, appCode, CredentialsAuthEndpoint) {
|
|
857
|
+
const response = await axiosInstance.post(CredentialsAuthEndpoint, { username, password, MFACode });
|
|
858
|
+
// Implement your AD login logic here
|
|
859
|
+
console.log("AD Login:", { username, password, MFACode });
|
|
860
|
+
// Example: await adLoginService(username, password, mfaCode);
|
|
861
|
+
return response.data;
|
|
862
|
+
}
|
|
863
|
+
async HandleFIDOLogin(RetrieveAuthChallengeEndpoint, AuthChallengeVerifyEndpoint, authenticate) {
|
|
864
|
+
try {
|
|
865
|
+
// 1. Fetch authentication challenge from your server
|
|
866
|
+
console.log("Requesting authentication challenge from server...");
|
|
867
|
+
const { data: options } = await axiosInstance.post(RetrieveAuthChallengeEndpoint, {});
|
|
868
|
+
console.log("Received challenge:", options);
|
|
869
|
+
// 2. Call the SDK to trigger the browser's passkey authentication UI
|
|
870
|
+
console.log("Calling SDK authenticate function...");
|
|
871
|
+
const assertionResponse = await authenticate({
|
|
872
|
+
...options,
|
|
873
|
+
userVerification: "discouraged",
|
|
874
|
+
});
|
|
875
|
+
console.log("Authentication assertion received from client:", assertionResponse);
|
|
876
|
+
// 3. Send the assertion back to the server for verification
|
|
877
|
+
console.log("Sending assertion to server for verification...");
|
|
878
|
+
await axiosInstance.post(AuthChallengeVerifyEndpoint, assertionResponse);
|
|
879
|
+
return true;
|
|
880
|
+
}
|
|
881
|
+
catch (error) {
|
|
882
|
+
console.error("Authentication failed:", error);
|
|
883
|
+
// toast.error("❌ Could not sign in.");
|
|
884
|
+
return false;
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
async HandleRegister(RegisterNewChallengeEndpoint, RegisterVerify, register, data) {
|
|
888
|
+
try {
|
|
889
|
+
// 1. Fetch challenge from your server
|
|
890
|
+
console.log("Requesting registration challenge from server...");
|
|
891
|
+
const { data: options } = await axiosInstance.post(RegisterNewChallengeEndpoint, { ...data });
|
|
892
|
+
console.log("Received challenge:", options);
|
|
893
|
+
// 2. Call the SDK to trigger the browser's passkey creation UI
|
|
894
|
+
console.log("Calling SDK register function...");
|
|
895
|
+
const attestationResponse = await register(options);
|
|
896
|
+
console.log("Passkey created on client:", attestationResponse);
|
|
897
|
+
// 3. Send the response back to the server for verification
|
|
898
|
+
console.log("Sending attestation to server for verification...");
|
|
899
|
+
await axiosInstance.post(RegisterVerify + `?username=${data.username}`, attestationResponse);
|
|
900
|
+
// toast.success("✅ Registration successful! Passkey created.");
|
|
901
|
+
return true;
|
|
902
|
+
}
|
|
903
|
+
catch (error) {
|
|
904
|
+
console.error("Registration failed:", error);
|
|
905
|
+
// toast.error("❌ Could not create passkey.");
|
|
906
|
+
return false;
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
GetRemainingAttempts() {
|
|
910
|
+
return Math.max(0, this.maxAttempts - this.attemptCount);
|
|
911
|
+
}
|
|
912
|
+
ResetUserAttempts() {
|
|
913
|
+
this.attemptCount = 0;
|
|
310
914
|
}
|
|
311
915
|
}
|
|
312
916
|
|
|
917
|
+
exports.APIHeaders = APIHeaders;
|
|
918
|
+
exports.AuthFailureMessageSchema = AuthFailureMessageSchema;
|
|
313
919
|
exports.CAMSError = CAMSError;
|
|
314
|
-
exports.
|
|
920
|
+
exports.CAMSMFAAuthenticator = CAMSMFAAuthenticator;
|
|
921
|
+
exports.CAMSSessionManager = CAMSSessionManager;
|
|
315
922
|
exports.ErrorMessageSchema = ErrorMessageSchema;
|
|
923
|
+
exports.Logger = Logger;
|
|
316
924
|
exports.ProfileSchema = ProfileSchema;
|
|
317
|
-
exports.TokenManager = TokenManager;
|
|
318
|
-
exports.TokenMessageSchema = TokenMessageSchema;
|
|
319
|
-
exports.TokenSchema = TokenSchema;
|
|
320
925
|
exports.URLSchema = URLSchema;
|
|
926
|
+
exports.axiosInstance = axiosInstance;
|
|
927
|
+
exports.generateSecureWindowName = generateSecureWindowName;
|
|
928
|
+
exports.isPopupWindow = isPopupWindow;
|
|
321
929
|
exports.openCAMSPopUpLogin = openCAMSPopUpLogin;
|
|
322
930
|
exports.validateConfig = validateConfig;
|
|
323
931
|
|