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