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