@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.cjs.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var zod = require('zod');
|
|
4
|
+
var axios = require('axios');
|
|
5
|
+
var https = require('https');
|
|
4
6
|
|
|
5
7
|
exports.CAMSErrorType = void 0;
|
|
6
8
|
(function (CAMSErrorType) {
|
|
@@ -10,228 +12,539 @@ exports.CAMSErrorType = void 0;
|
|
|
10
12
|
CAMSErrorType["USER_CANCELLED"] = "USER_CANCELLED";
|
|
11
13
|
CAMSErrorType["INVALID_URL"] = "INVALID_URL";
|
|
12
14
|
CAMSErrorType["MAX_RETRIES_EXCEEDED"] = "MAX_RETRIES_EXCEEDED";
|
|
15
|
+
CAMSErrorType["API_VALIDATION_ERROR"] = "VALIDATION_ERROR";
|
|
16
|
+
CAMSErrorType["NETWORK_ERROR"] = "NETWORK_ERROR";
|
|
13
17
|
})(exports.CAMSErrorType || (exports.CAMSErrorType = {}));
|
|
14
18
|
class CAMSError extends Error {
|
|
19
|
+
type;
|
|
15
20
|
constructor(type, message) {
|
|
16
21
|
super(message);
|
|
17
22
|
this.type = type;
|
|
18
|
-
this.name =
|
|
23
|
+
this.name = this.constructor.name;
|
|
19
24
|
}
|
|
20
25
|
}
|
|
21
26
|
|
|
22
|
-
// Validate the returned token -
|
|
23
|
-
const
|
|
24
|
-
|
|
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
|
+
}),
|
|
25
43
|
});
|
|
26
44
|
const ErrorMessageSchema = zod.z.object({
|
|
27
|
-
error: zod.z.string(),
|
|
28
|
-
});
|
|
29
|
-
const TokenSchema = zod.z.object({
|
|
30
|
-
access_token: zod.z.string(),
|
|
31
|
-
refresh_token: zod.z.string().optional(),
|
|
32
|
-
expires_in: zod.z.number(), // in seconds
|
|
33
|
-
token_type: zod.z.string().default("Bearer"),
|
|
34
|
-
id_token: zod.z.string().optional(),
|
|
45
|
+
error: zod.z.string().min(1, "Error message cannot be empty"),
|
|
35
46
|
});
|
|
36
|
-
const
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
family_name: zod.z.string().optional(),
|
|
42
|
-
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()),
|
|
43
52
|
});
|
|
44
|
-
|
|
45
|
-
|
|
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
|
+
}
|
|
46
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
|
+
*/
|
|
47
221
|
function validateConfig(config) {
|
|
48
|
-
// Validate URL format
|
|
49
222
|
const urlValidation = URLSchema.safeParse(config.camsUrl);
|
|
50
223
|
if (!urlValidation.success) {
|
|
51
|
-
throw new CAMSError(exports.CAMSErrorType.INVALID_URL,
|
|
224
|
+
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Invalid CAMS URL format");
|
|
52
225
|
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');
|
|
56
|
-
}
|
|
57
|
-
const url = new URL(config.camsUrl); // URLSchema already validated this
|
|
58
|
-
const isAllowed = config.allowedDomains.some(domain => url.hostname === domain || url.hostname.endsWith('.' + domain));
|
|
59
|
-
if (!isAllowed) {
|
|
60
|
-
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");
|
|
61
228
|
}
|
|
229
|
+
return new URL(config.camsUrl);
|
|
62
230
|
}
|
|
231
|
+
/**
|
|
232
|
+
* Open CAMS authentication popup and handle the authentication flow
|
|
233
|
+
*/
|
|
63
234
|
function openCAMSPopUpLogin(config) {
|
|
64
235
|
return new Promise((resolve, reject) => {
|
|
65
|
-
|
|
66
|
-
|
|
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;
|
|
67
240
|
}
|
|
68
|
-
|
|
69
|
-
|
|
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"));
|
|
70
244
|
return;
|
|
71
245
|
}
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
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;
|
|
76
252
|
try {
|
|
77
|
-
|
|
253
|
+
validatedUrl = validateConfig(config);
|
|
254
|
+
Logger.debug("Configuration validation passed");
|
|
78
255
|
}
|
|
79
256
|
catch (error) {
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
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);
|
|
85
261
|
return;
|
|
86
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
|
+
*/
|
|
87
275
|
const cleanup = () => {
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
276
|
+
if (removeMessageListener) {
|
|
277
|
+
removeMessageListener();
|
|
278
|
+
removeMessageListener = null;
|
|
279
|
+
}
|
|
280
|
+
if (idleTimeoutId)
|
|
281
|
+
NativeFunctions.clearTimeout(idleTimeoutId);
|
|
282
|
+
if (authTimeoutId)
|
|
283
|
+
NativeFunctions.clearTimeout(authTimeoutId);
|
|
91
284
|
if (checkClosedInterval)
|
|
92
|
-
|
|
285
|
+
NativeFunctions.clearTimeout(checkClosedInterval);
|
|
286
|
+
idleTimeoutId = null;
|
|
287
|
+
authTimeoutId = null;
|
|
288
|
+
checkClosedInterval = null;
|
|
93
289
|
};
|
|
290
|
+
/**
|
|
291
|
+
* Clean up and close the popup window, then reject with error
|
|
292
|
+
*/
|
|
94
293
|
const cleanupAndClose = (error) => {
|
|
95
294
|
cleanup();
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
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;
|
|
99
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;
|
|
100
363
|
}
|
|
101
|
-
|
|
102
|
-
|
|
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;
|
|
103
373
|
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
const sanitizedOrigin = event.origin.replace(/[\r\n]/g, '');
|
|
111
|
-
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();
|
|
112
380
|
return;
|
|
113
381
|
}
|
|
114
|
-
//
|
|
115
|
-
|
|
116
|
-
|
|
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");
|
|
117
393
|
cleanupAndClose();
|
|
118
|
-
resolve(
|
|
394
|
+
resolve(profileValidation.data);
|
|
119
395
|
return;
|
|
120
396
|
}
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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})` : ''}`));
|
|
124
407
|
return;
|
|
125
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
|
+
});
|
|
126
426
|
cleanupAndClose(new CAMSError(exports.CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
|
|
127
427
|
};
|
|
128
|
-
//
|
|
129
|
-
timeoutId = setTimeout(() => {
|
|
130
|
-
cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));
|
|
131
|
-
}, timeout);
|
|
132
|
-
checkClosedInterval = setInterval(() => {
|
|
133
|
-
if (authWindow && authWindow.closed) {
|
|
134
|
-
cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
|
|
135
|
-
}
|
|
136
|
-
}, 2000); // Reduced polling frequency
|
|
428
|
+
// Main authentication flow execution
|
|
137
429
|
try {
|
|
138
|
-
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
|
+
}
|
|
139
471
|
}
|
|
140
472
|
catch (error) {
|
|
473
|
+
Logger.error("Failed to initialize authentication popup", {
|
|
474
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
475
|
+
});
|
|
141
476
|
cleanup();
|
|
142
|
-
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to
|
|
143
|
-
|
|
477
|
+
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to initialize authentication: " +
|
|
478
|
+
(error instanceof Error ? error.message : "Unknown error")));
|
|
144
479
|
}
|
|
145
480
|
});
|
|
146
481
|
}
|
|
147
482
|
|
|
148
|
-
class
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
this.
|
|
157
|
-
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;
|
|
158
493
|
}
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
return this.token;
|
|
162
|
-
const raw = this.storage.getItem(this.storageKey);
|
|
163
|
-
if (!raw)
|
|
164
|
-
return null;
|
|
165
|
-
try {
|
|
166
|
-
const parsed = JSON.parse(raw);
|
|
167
|
-
try {
|
|
168
|
-
this.token = TokenSchema.parse(parsed);
|
|
169
|
-
return this.token;
|
|
170
|
-
}
|
|
171
|
-
catch (validationError) {
|
|
172
|
-
console.warn('Token validation failed:', validationError instanceof Error ? validationError.message : 'Unknown error');
|
|
173
|
-
this.storage.removeItem(this.storageKey);
|
|
174
|
-
return null;
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
catch (parseError) {
|
|
178
|
-
console.warn('Failed to parse stored token JSON:', parseError instanceof Error ? parseError.message : 'Unknown error');
|
|
179
|
-
this.storage.removeItem(this.storageKey);
|
|
180
|
-
return null;
|
|
181
|
-
}
|
|
494
|
+
setItem(key, value) {
|
|
495
|
+
this.storage.setItem(`${this.keyPrefix}:${key}`, value);
|
|
182
496
|
}
|
|
183
|
-
|
|
184
|
-
this.
|
|
185
|
-
this.storage.removeItem(this.storageKey);
|
|
497
|
+
getItem(key) {
|
|
498
|
+
return this.storage.getItem(`${this.keyPrefix}:${key}`);
|
|
186
499
|
}
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
return token ? token.access_token : null;
|
|
500
|
+
removeItem(key) {
|
|
501
|
+
this.storage.removeItem(`${this.keyPrefix}:${key}`);
|
|
190
502
|
}
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
if (token.id_token) {
|
|
197
|
-
try {
|
|
198
|
-
const parts = token.id_token.split(".");
|
|
199
|
-
if (parts.length < 3)
|
|
200
|
-
return true; // Invalid JWT format
|
|
201
|
-
const payload = JSON.parse(atob(parts[1]));
|
|
202
|
-
if (typeof payload.exp !== 'number')
|
|
203
|
-
return true;
|
|
204
|
-
const exp = payload.exp * 1000;
|
|
205
|
-
return Date.now() > exp;
|
|
206
|
-
}
|
|
207
|
-
catch (error) {
|
|
208
|
-
console.warn('Failed to parse JWT token:', error instanceof Error ? error.message : 'Unknown error');
|
|
209
|
-
return true;
|
|
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);
|
|
210
508
|
}
|
|
211
|
-
}
|
|
212
|
-
// Fallback: return true for safety when expiration cannot be determined
|
|
213
|
-
return true;
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
class CAMSSession {
|
|
218
|
-
constructor(storage = sessionStorage, storageKey, events = {}) {
|
|
219
|
-
this.tokenManager = new TokenManager(storage, storageKey);
|
|
220
|
-
this.events = events;
|
|
509
|
+
});
|
|
221
510
|
}
|
|
222
511
|
async login(config) {
|
|
223
512
|
try {
|
|
224
|
-
|
|
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();
|
|
225
521
|
let attempts = 0;
|
|
226
522
|
const maxAttempts = (config.retryAttempts ?? 0) + 1;
|
|
523
|
+
Logger.debug("Login retry configuration", { maxAttempts });
|
|
227
524
|
while (attempts < maxAttempts) {
|
|
228
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
|
+
}
|
|
229
534
|
const response = await openCAMSPopUpLogin(config);
|
|
230
|
-
|
|
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);
|
|
231
541
|
return response;
|
|
232
542
|
}
|
|
233
543
|
catch (error) {
|
|
234
|
-
|
|
544
|
+
Logger.warn("Login attempt failed", {
|
|
545
|
+
attempt: attempts,
|
|
546
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
547
|
+
});
|
|
235
548
|
if (attempts >= maxAttempts || !(error instanceof CAMSError)) {
|
|
236
549
|
throw error;
|
|
237
550
|
}
|
|
@@ -239,80 +552,405 @@ class CAMSSession {
|
|
|
239
552
|
if (![exports.CAMSErrorType.TIMEOUT, exports.CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {
|
|
240
553
|
throw error;
|
|
241
554
|
}
|
|
555
|
+
Logger.info("Retrying login", { nextAttempt: attempts + 1 });
|
|
242
556
|
}
|
|
243
557
|
}
|
|
244
|
-
throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED,
|
|
558
|
+
throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED, "Max retry attempts exceeded");
|
|
245
559
|
}
|
|
246
560
|
catch (error) {
|
|
247
|
-
const
|
|
248
|
-
|
|
249
|
-
|
|
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);
|
|
250
571
|
throw camsError;
|
|
251
572
|
}
|
|
252
573
|
}
|
|
253
574
|
async logout() {
|
|
254
|
-
|
|
575
|
+
Logger.info("Session logout");
|
|
576
|
+
this.clearToken();
|
|
255
577
|
}
|
|
256
|
-
|
|
257
|
-
|
|
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();
|
|
258
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");
|
|
259
656
|
return false;
|
|
260
|
-
|
|
261
|
-
|
|
657
|
+
}
|
|
658
|
+
if (this.checkTokenExpiration()) {
|
|
262
659
|
return false;
|
|
263
660
|
}
|
|
661
|
+
Logger.debug("Token is valid");
|
|
264
662
|
return true;
|
|
265
663
|
}
|
|
266
|
-
|
|
267
|
-
const
|
|
268
|
-
if (!
|
|
664
|
+
async getProfile() {
|
|
665
|
+
const storedToken = this.getAccessToken();
|
|
666
|
+
if (!storedToken)
|
|
269
667
|
return null;
|
|
270
|
-
|
|
271
|
-
|
|
668
|
+
// Check token expiration before processing
|
|
669
|
+
if (this.checkTokenExpiration()) {
|
|
272
670
|
return null;
|
|
273
671
|
}
|
|
274
|
-
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
|
+
}
|
|
275
697
|
}
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
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;
|
|
282
705
|
}
|
|
283
|
-
|
|
706
|
+
Logger.warn("Reporting authentication error from popup");
|
|
284
707
|
}
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
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) {
|
|
289
801
|
try {
|
|
290
|
-
const
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
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");
|
|
299
837
|
}
|
|
300
838
|
}
|
|
301
839
|
catch (error) {
|
|
302
|
-
|
|
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"}`);
|
|
303
851
|
}
|
|
304
|
-
|
|
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;
|
|
305
939
|
}
|
|
306
940
|
}
|
|
307
941
|
|
|
942
|
+
exports.APIHeaders = APIHeaders;
|
|
943
|
+
exports.AuthFailureMessageSchema = AuthFailureMessageSchema;
|
|
308
944
|
exports.CAMSError = CAMSError;
|
|
309
|
-
exports.
|
|
945
|
+
exports.CAMSMFAAuthenticator = CAMSMFAAuthenticator;
|
|
946
|
+
exports.CAMSSessionManager = CAMSSessionManager;
|
|
310
947
|
exports.ErrorMessageSchema = ErrorMessageSchema;
|
|
948
|
+
exports.Logger = Logger;
|
|
311
949
|
exports.ProfileSchema = ProfileSchema;
|
|
312
|
-
exports.TokenManager = TokenManager;
|
|
313
|
-
exports.TokenMessageSchema = TokenMessageSchema;
|
|
314
|
-
exports.TokenSchema = TokenSchema;
|
|
315
950
|
exports.URLSchema = URLSchema;
|
|
951
|
+
exports.axiosInstance = axiosInstance;
|
|
952
|
+
exports.generateSecureWindowName = generateSecureWindowName;
|
|
953
|
+
exports.isPopupWindow = isPopupWindow;
|
|
316
954
|
exports.openCAMSPopUpLogin = openCAMSPopUpLogin;
|
|
317
955
|
exports.validateConfig = validateConfig;
|
|
318
956
|
//# sourceMappingURL=index.cjs.js.map
|