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