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