@nibssplc/cams-sdk 0.0.1-beta.9 → 0.0.1-beta.93
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 +111 -87
- package/dist/MFAAuth.d.ts +54 -0
- package/dist/__tests__/validators.authState.test.d.ts +1 -0
- package/dist/auth.d.ts +18 -3
- package/dist/index.cjs.js +1079 -197
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +7 -2
- package/dist/index.esm.js +1066 -194
- package/dist/index.esm.js.map +1 -1
- package/dist/index.umd.js +1081 -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/lib/WebAuthnUtils.d.ts +27 -0
- package/dist/logger.d.ts +19 -0
- package/dist/sessionManager.d.ts +47 -0
- package/dist/tracing.d.ts +6 -0
- package/dist/types.d.ts +81 -8
- package/dist/validators.d.ts +39 -19
- package/package.json +24 -5
- package/dist/session.d.ts +0 -19
- package/dist/tokenManager.d.ts +0 -12
package/dist/index.esm.js
CHANGED
|
@@ -1,241 +1,587 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
+
import { trace, propagation, context, SpanStatusCode, SpanKind } from '@opentelemetry/api';
|
|
3
|
+
import axios, { AxiosError } from 'axios';
|
|
2
4
|
|
|
3
5
|
var CAMSErrorType;
|
|
4
6
|
(function (CAMSErrorType) {
|
|
5
7
|
CAMSErrorType["POPUP_BLOCKED"] = "POPUP_BLOCKED";
|
|
6
8
|
CAMSErrorType["TIMEOUT"] = "TIMEOUT";
|
|
7
9
|
CAMSErrorType["INVALID_ORIGIN"] = "INVALID_ORIGIN";
|
|
10
|
+
CAMSErrorType["API_UNAUTHORIZED_ERROR"] = "UNAUTHORIZED_USER";
|
|
8
11
|
CAMSErrorType["USER_CANCELLED"] = "USER_CANCELLED";
|
|
9
12
|
CAMSErrorType["INVALID_URL"] = "INVALID_URL";
|
|
10
13
|
CAMSErrorType["MAX_RETRIES_EXCEEDED"] = "MAX_RETRIES_EXCEEDED";
|
|
14
|
+
CAMSErrorType["API_VALIDATION_ERROR"] = "VALIDATION_ERROR";
|
|
15
|
+
CAMSErrorType["NETWORK_ERROR"] = "NETWORK_ERROR";
|
|
11
16
|
})(CAMSErrorType || (CAMSErrorType = {}));
|
|
12
17
|
class CAMSError extends Error {
|
|
18
|
+
type;
|
|
13
19
|
constructor(type, message) {
|
|
14
20
|
super(message);
|
|
15
21
|
this.type = type;
|
|
16
|
-
this.name =
|
|
22
|
+
this.name = this.constructor.name;
|
|
17
23
|
}
|
|
18
24
|
}
|
|
19
25
|
|
|
20
|
-
// Validate the returned token -
|
|
21
|
-
const
|
|
22
|
-
|
|
26
|
+
// Validate the returned token - non-empty string
|
|
27
|
+
const ProfileSchema = z.object({
|
|
28
|
+
state: z.literal("AUTH_SUCCESS").or(z.literal("AUTH_FAILURE")),
|
|
29
|
+
role: z.enum(["SUPER_ADMIN", "ADMIN", "USER"]),
|
|
30
|
+
message: z.string(),
|
|
31
|
+
profile: z.object({
|
|
32
|
+
priviledges: z.array(z.string()).optional(),
|
|
33
|
+
userInfo: z.object({
|
|
34
|
+
id: z.number(),
|
|
35
|
+
name: z.string(),
|
|
36
|
+
email: z.email(),
|
|
37
|
+
isMFAEnabled: z.boolean(),
|
|
38
|
+
}),
|
|
39
|
+
tokens: z.object({
|
|
40
|
+
Nonce: z.string(),
|
|
41
|
+
Bearer: z.string(),
|
|
42
|
+
}),
|
|
43
|
+
}),
|
|
44
|
+
authType: z.enum(["MSAL", "AD_CREDENTIALS"]).optional(),
|
|
23
45
|
});
|
|
24
46
|
const ErrorMessageSchema = z.object({
|
|
25
|
-
error: z.string(),
|
|
47
|
+
error: z.string().min(1, "Error message cannot be empty"),
|
|
26
48
|
});
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
id_token: z.string().optional(),
|
|
49
|
+
const AuthFailureMessageSchema = z.object({
|
|
50
|
+
type: z.literal("AUTH_FAILURE"),
|
|
51
|
+
error: z.string().min(1, "Error message cannot be empty"),
|
|
52
|
+
errorCode: z.string(),
|
|
53
|
+
errorDetails: z.object().or(z.any()),
|
|
33
54
|
});
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
55
|
+
const URLSchema = z.url();
|
|
56
|
+
|
|
57
|
+
var LogLevel;
|
|
58
|
+
(function (LogLevel) {
|
|
59
|
+
LogLevel[LogLevel["ERROR"] = 0] = "ERROR";
|
|
60
|
+
LogLevel[LogLevel["WARN"] = 1] = "WARN";
|
|
61
|
+
LogLevel[LogLevel["INFO"] = 2] = "INFO";
|
|
62
|
+
LogLevel[LogLevel["DEBUG"] = 3] = "DEBUG";
|
|
63
|
+
})(LogLevel || (LogLevel = {}));
|
|
64
|
+
class Logger {
|
|
65
|
+
static level = LogLevel.DEBUG;
|
|
66
|
+
static prefix = '[CAMS-SDK]';
|
|
67
|
+
static isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';
|
|
68
|
+
static setLevel(level) {
|
|
69
|
+
Logger.level = level;
|
|
70
|
+
}
|
|
71
|
+
static error(message, context) {
|
|
72
|
+
if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {
|
|
73
|
+
console.error(`${Logger.prefix} ERROR:`, message, context || '');
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
static warn(message, context) {
|
|
77
|
+
if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {
|
|
78
|
+
console.warn(`${Logger.prefix} WARN:`, message, context || '');
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
static info(message, context) {
|
|
82
|
+
if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {
|
|
83
|
+
console.info(`${Logger.prefix} INFO:`, message, context || '');
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
static debug(message, context) {
|
|
87
|
+
if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {
|
|
88
|
+
console.debug(`${Logger.prefix} DEBUG:`, message, context || '');
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const CAMS_SERVICE_NAME = "NIBSS-CENTRAL-AUTH-SDK";
|
|
94
|
+
const tracer = trace.getTracer(CAMS_SERVICE_NAME);
|
|
95
|
+
const getSpanAttributes = (attributes = {}) => ({
|
|
96
|
+
"service.name": CAMS_SERVICE_NAME,
|
|
97
|
+
...attributes,
|
|
41
98
|
});
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
/^http:\/\/localhost(:\d+)?$/i.test(url) || // localhost
|
|
46
|
-
internalIpRegex.test(url), // internal LAN IPs
|
|
47
|
-
{
|
|
48
|
-
message: "Only HTTPS, http://localhost, or internal IPs (192.168.x.x, 10.x.x.x, 172.16–31.x.x) are allowed",
|
|
99
|
+
const startCAMSSpan = (name, attributes = {}, kind) => tracer.startSpan(name, {
|
|
100
|
+
attributes: getSpanAttributes(attributes),
|
|
101
|
+
kind,
|
|
49
102
|
});
|
|
103
|
+
async function withCAMSSpan(name, operation) {
|
|
104
|
+
return tracer.startActiveSpan(name, { attributes: getSpanAttributes() }, async (span) => {
|
|
105
|
+
try {
|
|
106
|
+
const result = await operation();
|
|
107
|
+
span.setStatus({ code: SpanStatusCode.OK });
|
|
108
|
+
return result;
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
finally {
|
|
115
|
+
span.end();
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
const injectCAMSContext = (span, carrier) => {
|
|
120
|
+
propagation.inject(trace.setSpan(context.active(), span), carrier, {
|
|
121
|
+
set: (headers, key, value) => headers.set(key, value),
|
|
122
|
+
});
|
|
123
|
+
};
|
|
50
124
|
|
|
125
|
+
// Constants
|
|
126
|
+
const DEFAULT_AUTH_TIMEOUT = 300000; // 5 minutes
|
|
127
|
+
const DEFAULT_IDLE_TIMEOUT = 120000; // 2 minutes
|
|
128
|
+
const INITIAL_POLL_INTERVAL = 1000;
|
|
129
|
+
const WINDOW_FEATURES = "scrollbars=yes,resizable=yes";
|
|
130
|
+
// Default allowed Microsoft domains for Azure AD redirects
|
|
131
|
+
const DEFAULT_MICROSOFT_DOMAINS = [
|
|
132
|
+
".microsoft.com",
|
|
133
|
+
".microsoftonline.com",
|
|
134
|
+
".live.com",
|
|
135
|
+
"login.microsoftonline.com"
|
|
136
|
+
];
|
|
137
|
+
// Secure reference to native functions with proper binding
|
|
138
|
+
const NativeFunctions = {
|
|
139
|
+
addEventListener: typeof window !== "undefined" ? window.addEventListener.bind(window) : null,
|
|
140
|
+
removeEventListener: typeof window !== "undefined" ? window.removeEventListener.bind(window) : null,
|
|
141
|
+
setTimeout: typeof window !== "undefined" && window.setTimeout ? window.setTimeout.bind(window) : setTimeout,
|
|
142
|
+
clearTimeout: typeof window !== "undefined" && window.clearTimeout ? window.clearTimeout.bind(window) : clearTimeout,
|
|
143
|
+
};
|
|
144
|
+
/**
|
|
145
|
+
* Generate a secure random window name to prevent targeting
|
|
146
|
+
*/
|
|
147
|
+
const generateSecureWindowName = () => `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;
|
|
148
|
+
/**
|
|
149
|
+
* Detect if current window is a popup to prevent recursive popups
|
|
150
|
+
*/
|
|
151
|
+
const isPopupWindow = () => {
|
|
152
|
+
if (typeof window === "undefined")
|
|
153
|
+
return false;
|
|
154
|
+
// Skip popup detection in test environments
|
|
155
|
+
if (typeof process !== "undefined" && process.env && process.env.NODE_ENV === "test") {
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
try {
|
|
159
|
+
return window.opener !== null && window.opener !== window;
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
/**
|
|
166
|
+
* Safely close a window with error handling for cross-origin restrictions
|
|
167
|
+
*/
|
|
168
|
+
const safeWindowClose = (window) => {
|
|
169
|
+
if (!window)
|
|
170
|
+
return;
|
|
171
|
+
try {
|
|
172
|
+
if (!window.closed) {
|
|
173
|
+
window.close();
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
Logger.debug("Error closing window (cross-origin restriction)", {
|
|
178
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
/**
|
|
183
|
+
* Center popup window on screen
|
|
184
|
+
*/
|
|
185
|
+
const getPopupPosition = (width, height) => {
|
|
186
|
+
if (typeof window === "undefined")
|
|
187
|
+
return { left: 0, top: 0 };
|
|
188
|
+
const left = Math.max(0, (window.screen.width - width) / 2);
|
|
189
|
+
const top = Math.max(0, (window.screen.height - height) / 2);
|
|
190
|
+
return { left, top };
|
|
191
|
+
};
|
|
192
|
+
/**
|
|
193
|
+
* Validate origin against expected domain with support for subdomains and Microsoft redirects
|
|
194
|
+
*/
|
|
195
|
+
const isValidOrigin = (eventOrigin, expectedOrigin, microsoftDomains = DEFAULT_MICROSOFT_DOMAINS) => {
|
|
196
|
+
try {
|
|
197
|
+
const originUrl = new URL(eventOrigin);
|
|
198
|
+
const expectedHostname = expectedOrigin.startsWith("http")
|
|
199
|
+
? new URL(expectedOrigin).hostname
|
|
200
|
+
: expectedOrigin;
|
|
201
|
+
// Check Microsoft domains for Azure AD redirects
|
|
202
|
+
const isMicrosoftDomain = microsoftDomains.some(domain => originUrl.hostname === domain || originUrl.hostname.endsWith(domain));
|
|
203
|
+
// Allow exact match, subdomains, or Microsoft domains
|
|
204
|
+
return (originUrl.hostname === expectedHostname ||
|
|
205
|
+
originUrl.hostname.endsWith("." + expectedHostname) ||
|
|
206
|
+
isMicrosoftDomain);
|
|
207
|
+
}
|
|
208
|
+
catch {
|
|
209
|
+
return false;
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
/**
|
|
213
|
+
* Safely check if window is closed with cross-origin handling
|
|
214
|
+
*/
|
|
215
|
+
const isWindowClosed = (window) => {
|
|
216
|
+
if (!window)
|
|
217
|
+
return true;
|
|
218
|
+
try {
|
|
219
|
+
return window.closed;
|
|
220
|
+
}
|
|
221
|
+
catch (error) {
|
|
222
|
+
// Cross-origin error means we can't access the property
|
|
223
|
+
// This typically happens when redirected to external auth providers
|
|
224
|
+
Logger.debug("Cannot access window.closed due to cross-origin restrictions - assuming window is still open", error);
|
|
225
|
+
return false;
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
/**
|
|
229
|
+
* Safely add message event listener with error handling
|
|
230
|
+
*/
|
|
231
|
+
const addMessageListener = (listener) => {
|
|
232
|
+
if (!NativeFunctions.addEventListener) {
|
|
233
|
+
throw new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Message listener not available in current environment");
|
|
234
|
+
}
|
|
235
|
+
const wrappedListener = (event) => {
|
|
236
|
+
try {
|
|
237
|
+
listener(event);
|
|
238
|
+
}
|
|
239
|
+
catch (error) {
|
|
240
|
+
Logger.error("Error in message listener", {
|
|
241
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
NativeFunctions.addEventListener("message", wrappedListener);
|
|
246
|
+
return () => {
|
|
247
|
+
if (NativeFunctions.removeEventListener) {
|
|
248
|
+
NativeFunctions.removeEventListener("message", wrappedListener);
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
};
|
|
252
|
+
/**
|
|
253
|
+
* Validate configuration and return parsed URL
|
|
254
|
+
*/
|
|
51
255
|
function validateConfig(config) {
|
|
52
|
-
// Validate URL format
|
|
53
256
|
const urlValidation = URLSchema.safeParse(config.camsUrl);
|
|
54
257
|
if (!urlValidation.success) {
|
|
55
|
-
throw new CAMSError(CAMSErrorType.INVALID_URL,
|
|
56
|
-
}
|
|
57
|
-
// Domain validation is mandatory for security
|
|
58
|
-
if (!config.allowedDomains?.length) {
|
|
59
|
-
throw new CAMSError(CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');
|
|
258
|
+
throw new CAMSError(CAMSErrorType.INVALID_URL, "Invalid CAMS URL format");
|
|
60
259
|
}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
if (!isAllowed) {
|
|
64
|
-
throw new CAMSError(CAMSErrorType.INVALID_URL, 'URL not in allowed domains list');
|
|
260
|
+
if (!config.messageOrigin) {
|
|
261
|
+
throw new CAMSError(CAMSErrorType.INVALID_URL, "Message Origin must be specified for security");
|
|
65
262
|
}
|
|
263
|
+
return new URL(config.camsUrl);
|
|
66
264
|
}
|
|
265
|
+
/**
|
|
266
|
+
* Open CAMS authentication popup and handle the authentication flow
|
|
267
|
+
*/
|
|
67
268
|
function openCAMSPopUpLogin(config) {
|
|
269
|
+
return withCAMSSpan("CAMS.Auth.Popup", () => openCAMSPopUpLoginInternal(config));
|
|
270
|
+
}
|
|
271
|
+
function openCAMSPopUpLoginInternal(config) {
|
|
68
272
|
return new Promise((resolve, reject) => {
|
|
69
|
-
|
|
70
|
-
|
|
273
|
+
// Environment validation
|
|
274
|
+
if (typeof window === "undefined") {
|
|
275
|
+
reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Cannot open popup in server-side environment"));
|
|
276
|
+
return;
|
|
71
277
|
}
|
|
72
|
-
|
|
73
|
-
|
|
278
|
+
if (isPopupWindow()) {
|
|
279
|
+
Logger.warn("Attempted to open popup from within popup window");
|
|
280
|
+
reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Cannot open authentication popup from within popup window"));
|
|
74
281
|
return;
|
|
75
282
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
283
|
+
// Initialize logging
|
|
284
|
+
if (config.debug)
|
|
285
|
+
Logger.setLevel(LogLevel.DEBUG);
|
|
286
|
+
Logger.info("Starting CAMS authentication", { url: config.camsUrl });
|
|
287
|
+
// Validate configuration
|
|
288
|
+
let validatedUrl;
|
|
80
289
|
try {
|
|
81
|
-
|
|
290
|
+
validatedUrl = validateConfig(config);
|
|
291
|
+
Logger.debug("Configuration validation passed");
|
|
82
292
|
}
|
|
83
293
|
catch (error) {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window. Please allow popups."));
|
|
294
|
+
Logger.error("Configuration validation failed", {
|
|
295
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
296
|
+
});
|
|
297
|
+
reject(error);
|
|
89
298
|
return;
|
|
90
299
|
}
|
|
300
|
+
// Extract configuration with defaults
|
|
301
|
+
const { messageOrigin, windowHeight = 600, windowWidth = 500, authTimeout = DEFAULT_AUTH_TIMEOUT, idleTimeout = DEFAULT_IDLE_TIMEOUT, allowedRedirectDomains = [...DEFAULT_MICROSOFT_DOMAINS, messageOrigin], } = config;
|
|
302
|
+
// State management
|
|
303
|
+
let authWindow = null;
|
|
304
|
+
let authTimeoutId = null;
|
|
305
|
+
let idleTimeoutId = null;
|
|
306
|
+
let checkClosedInterval = null;
|
|
307
|
+
let removeMessageListener = null;
|
|
308
|
+
let hasReceivedValidMessage = false;
|
|
309
|
+
/**
|
|
310
|
+
* Clean up all resources and timeouts
|
|
311
|
+
*/
|
|
91
312
|
const cleanup = () => {
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
313
|
+
if (removeMessageListener) {
|
|
314
|
+
removeMessageListener();
|
|
315
|
+
removeMessageListener = null;
|
|
316
|
+
}
|
|
317
|
+
if (idleTimeoutId)
|
|
318
|
+
NativeFunctions.clearTimeout(idleTimeoutId);
|
|
319
|
+
if (authTimeoutId)
|
|
320
|
+
NativeFunctions.clearTimeout(authTimeoutId);
|
|
95
321
|
if (checkClosedInterval)
|
|
96
|
-
|
|
322
|
+
NativeFunctions.clearTimeout(checkClosedInterval);
|
|
323
|
+
idleTimeoutId = null;
|
|
324
|
+
authTimeoutId = null;
|
|
325
|
+
checkClosedInterval = null;
|
|
97
326
|
};
|
|
327
|
+
/**
|
|
328
|
+
* Clean up and close the popup window, then reject with error
|
|
329
|
+
*/
|
|
98
330
|
const cleanupAndClose = (error) => {
|
|
99
331
|
cleanup();
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
332
|
+
safeWindowClose(authWindow);
|
|
333
|
+
if (error) {
|
|
334
|
+
reject(error);
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
/**
|
|
338
|
+
* Reset idle timeout on user activity
|
|
339
|
+
*/
|
|
340
|
+
const resetIdleTimeout = () => {
|
|
341
|
+
if (idleTimeoutId)
|
|
342
|
+
NativeFunctions.clearTimeout(idleTimeoutId);
|
|
343
|
+
Logger.debug("Resetting idle timeout", { idleTimeout });
|
|
344
|
+
idleTimeoutId = NativeFunctions.setTimeout(() => {
|
|
345
|
+
Logger.warn("Authentication idle timeout reached", { idleTimeout });
|
|
346
|
+
cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication timed out due to inactivity after ${idleTimeout}ms`));
|
|
347
|
+
}, idleTimeout);
|
|
348
|
+
};
|
|
349
|
+
/**
|
|
350
|
+
* Set up popup window closure detection with cross-origin handling
|
|
351
|
+
*/
|
|
352
|
+
const setupClosureDetection = () => {
|
|
353
|
+
let pollInterval = INITIAL_POLL_INTERVAL;
|
|
354
|
+
const checkClosed = () => {
|
|
355
|
+
// Skip closure detection when on Microsoft domains
|
|
356
|
+
if (authWindow) {
|
|
357
|
+
try {
|
|
358
|
+
const currentUrl = authWindow.location.href;
|
|
359
|
+
const isMicrosoftDomain = allowedRedirectDomains.some(domain => currentUrl.includes(domain));
|
|
360
|
+
if (isMicrosoftDomain) {
|
|
361
|
+
Logger.debug("Skipping closure check - on Microsoft domain");
|
|
362
|
+
checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
catch (error) {
|
|
367
|
+
// Cross-origin error - assume we're on Microsoft domain and skip check
|
|
368
|
+
Logger.debug("Cross-origin error - skipping closure check");
|
|
369
|
+
checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
103
372
|
}
|
|
373
|
+
const isClosed = isWindowClosed(authWindow);
|
|
374
|
+
if (isClosed && !hasReceivedValidMessage) {
|
|
375
|
+
Logger.info("Authentication window closed by user");
|
|
376
|
+
cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);
|
|
380
|
+
};
|
|
381
|
+
checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);
|
|
382
|
+
};
|
|
383
|
+
/**
|
|
384
|
+
* Handle incoming message events from the popup
|
|
385
|
+
*/
|
|
386
|
+
const handleMessage = (event) => {
|
|
387
|
+
Logger.debug("Received message", {
|
|
388
|
+
origin: event.origin,
|
|
389
|
+
expectedOrigin: messageOrigin,
|
|
390
|
+
data: event.data,
|
|
391
|
+
});
|
|
392
|
+
// Security: Validate origin
|
|
393
|
+
if (!isValidOrigin(event.origin, messageOrigin, allowedRedirectDomains)) {
|
|
394
|
+
Logger.warn("Blocked message from unauthorized origin", {
|
|
395
|
+
origin: event.origin,
|
|
396
|
+
expected: messageOrigin,
|
|
397
|
+
data: event.data,
|
|
398
|
+
});
|
|
399
|
+
return;
|
|
104
400
|
}
|
|
105
|
-
|
|
106
|
-
|
|
401
|
+
// Security: Validate message source
|
|
402
|
+
if (event.source !== authWindow) {
|
|
403
|
+
Logger.warn("Message from unexpected source", {
|
|
404
|
+
source: event.source,
|
|
405
|
+
origin: event.origin,
|
|
406
|
+
expected: messageOrigin,
|
|
407
|
+
data: event.data,
|
|
408
|
+
});
|
|
409
|
+
return;
|
|
107
410
|
}
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
const sanitizedOrigin = event.origin.replace(/[\r\n]/g, '');
|
|
115
|
-
console.warn("Blocked message from origin:", sanitizedOrigin);
|
|
411
|
+
// Mark that we've received a valid message (prevents false closure detection)
|
|
412
|
+
hasReceivedValidMessage = true;
|
|
413
|
+
// Handle heartbeat messages (reset idle timeout)
|
|
414
|
+
if (event.data?.type === "heartbeat") {
|
|
415
|
+
Logger.debug("Received heartbeat message");
|
|
416
|
+
resetIdleTimeout();
|
|
116
417
|
return;
|
|
117
418
|
}
|
|
118
|
-
//
|
|
119
|
-
|
|
120
|
-
|
|
419
|
+
// Process authentication messages
|
|
420
|
+
processAuthenticationMessage(event.data);
|
|
421
|
+
};
|
|
422
|
+
/**
|
|
423
|
+
* Process and validate authentication message payloads
|
|
424
|
+
*/
|
|
425
|
+
const processAuthenticationMessage = (data) => {
|
|
426
|
+
// Success case: Valid profile received
|
|
427
|
+
const profileValidation = ProfileSchema.safeParse(data);
|
|
428
|
+
if (profileValidation.success) {
|
|
429
|
+
Logger.info("Authentication successful");
|
|
121
430
|
cleanupAndClose();
|
|
122
|
-
resolve(
|
|
431
|
+
resolve(profileValidation.data);
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
// Authentication failure case
|
|
435
|
+
const authFailureValidation = AuthFailureMessageSchema.safeParse(data);
|
|
436
|
+
if (authFailureValidation.success) {
|
|
437
|
+
const { error, errorCode, errorDetails } = authFailureValidation.data;
|
|
438
|
+
Logger.warn("Authentication failure received", {
|
|
439
|
+
error,
|
|
440
|
+
errorCode,
|
|
441
|
+
errorDetails,
|
|
442
|
+
});
|
|
443
|
+
cleanupAndClose(new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, `Authentication failed: ${error}${errorCode ? ` (${errorCode})` : ''}`));
|
|
123
444
|
return;
|
|
124
445
|
}
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
446
|
+
// Generic error case
|
|
447
|
+
const errorValidation = ErrorMessageSchema.safeParse(data);
|
|
448
|
+
if (errorValidation.success) {
|
|
449
|
+
Logger.warn("Authentication error received", {
|
|
450
|
+
error: errorValidation.data.error,
|
|
451
|
+
});
|
|
452
|
+
cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, `Authentication failed: ${errorValidation.data.error}`));
|
|
128
453
|
return;
|
|
129
454
|
}
|
|
455
|
+
// Invalid message format
|
|
456
|
+
Logger.error("Invalid message format received", {
|
|
457
|
+
messageData: data,
|
|
458
|
+
dataType: typeof data,
|
|
459
|
+
profileValidationError: profileValidation.error?.issues,
|
|
460
|
+
authFailureValidationError: authFailureValidation.error?.issues,
|
|
461
|
+
errorValidationError: errorValidation.error?.issues,
|
|
462
|
+
});
|
|
130
463
|
cleanupAndClose(new CAMSError(CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
|
|
131
464
|
};
|
|
132
|
-
//
|
|
133
|
-
timeoutId = setTimeout(() => {
|
|
134
|
-
cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));
|
|
135
|
-
}, timeout);
|
|
136
|
-
checkClosedInterval = setInterval(() => {
|
|
137
|
-
if (authWindow && authWindow.closed) {
|
|
138
|
-
cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
|
|
139
|
-
}
|
|
140
|
-
}, 2000); // Reduced polling frequency
|
|
465
|
+
// Main authentication flow execution
|
|
141
466
|
try {
|
|
142
|
-
window
|
|
467
|
+
// Open popup window
|
|
468
|
+
const { left, top } = getPopupPosition(windowWidth, windowHeight);
|
|
469
|
+
const secureWindowName = generateSecureWindowName();
|
|
470
|
+
Logger.debug("Opening popup window", {
|
|
471
|
+
width: windowWidth,
|
|
472
|
+
height: windowHeight,
|
|
473
|
+
left,
|
|
474
|
+
top,
|
|
475
|
+
});
|
|
476
|
+
authWindow = window.open(validatedUrl.toString(), secureWindowName, `width=${windowWidth},height=${windowHeight},left=${left},top=${top},${WINDOW_FEATURES}`);
|
|
477
|
+
// Check for popup blocking
|
|
478
|
+
if (!authWindow) {
|
|
479
|
+
Logger.error("Popup window blocked or failed to open");
|
|
480
|
+
reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
// Check for immediate closure (aggressive popup blockers)
|
|
484
|
+
if (isWindowClosed(authWindow)) {
|
|
485
|
+
Logger.error("Popup immediately closed by blocker");
|
|
486
|
+
reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
Logger.debug("Popup window opened successfully");
|
|
490
|
+
// Set up message listener
|
|
491
|
+
removeMessageListener = addMessageListener(handleMessage);
|
|
492
|
+
Logger.debug("Message listener attached");
|
|
493
|
+
// Set up timeouts
|
|
494
|
+
Logger.debug("Setting authentication timeout", { authTimeout });
|
|
495
|
+
authTimeoutId = NativeFunctions.setTimeout(() => {
|
|
496
|
+
Logger.warn("Authentication timeout reached", { authTimeout });
|
|
497
|
+
cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication process exceeded time limit of ${authTimeout}ms`));
|
|
498
|
+
}, authTimeout);
|
|
499
|
+
resetIdleTimeout();
|
|
500
|
+
setupClosureDetection();
|
|
501
|
+
// Focus popup for better UX
|
|
502
|
+
try {
|
|
503
|
+
authWindow.focus();
|
|
504
|
+
}
|
|
505
|
+
catch (error) {
|
|
506
|
+
Logger.debug("Could not focus popup window (cross-origin restriction)");
|
|
507
|
+
}
|
|
143
508
|
}
|
|
144
509
|
catch (error) {
|
|
510
|
+
Logger.error("Failed to initialize authentication popup", {
|
|
511
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
512
|
+
});
|
|
145
513
|
cleanup();
|
|
146
|
-
reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Failed to
|
|
147
|
-
|
|
514
|
+
reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Failed to initialize authentication: " +
|
|
515
|
+
(error instanceof Error ? error.message : "Unknown error")));
|
|
148
516
|
}
|
|
149
517
|
});
|
|
150
518
|
}
|
|
151
519
|
|
|
152
|
-
class
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
this.
|
|
161
|
-
this.
|
|
520
|
+
class CAMSSessionManager {
|
|
521
|
+
storage;
|
|
522
|
+
keyPrefix;
|
|
523
|
+
events;
|
|
524
|
+
token = null;
|
|
525
|
+
profile = null;
|
|
526
|
+
constructor(storage = null, keyPrefix, events = {}) {
|
|
527
|
+
this.storage = storage || getDefaultStorage();
|
|
528
|
+
this.keyPrefix = keyPrefix ?? "CAMS-SDK";
|
|
529
|
+
this.events = events;
|
|
162
530
|
}
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
return this.token;
|
|
166
|
-
const raw = this.storage.getItem(this.storageKey);
|
|
167
|
-
if (!raw)
|
|
168
|
-
return null;
|
|
169
|
-
try {
|
|
170
|
-
const parsed = JSON.parse(raw);
|
|
171
|
-
try {
|
|
172
|
-
this.token = TokenSchema.parse(parsed);
|
|
173
|
-
return this.token;
|
|
174
|
-
}
|
|
175
|
-
catch (validationError) {
|
|
176
|
-
console.warn('Token validation failed:', validationError instanceof Error ? validationError.message : 'Unknown error');
|
|
177
|
-
this.storage.removeItem(this.storageKey);
|
|
178
|
-
return null;
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
catch (parseError) {
|
|
182
|
-
console.warn('Failed to parse stored token JSON:', parseError instanceof Error ? parseError.message : 'Unknown error');
|
|
183
|
-
this.storage.removeItem(this.storageKey);
|
|
184
|
-
return null;
|
|
185
|
-
}
|
|
531
|
+
setItem(key, value) {
|
|
532
|
+
this.storage.setItem(`${this.keyPrefix}:${key}`, value);
|
|
186
533
|
}
|
|
187
|
-
|
|
188
|
-
this.
|
|
189
|
-
this.storage.removeItem(this.storageKey);
|
|
534
|
+
getItem(key) {
|
|
535
|
+
return this.storage.getItem(`${this.keyPrefix}:${key}`);
|
|
190
536
|
}
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
return token ? token.access_token : null;
|
|
537
|
+
removeItem(key) {
|
|
538
|
+
this.storage.removeItem(`${this.keyPrefix}:${key}`);
|
|
194
539
|
}
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
if (token.id_token) {
|
|
201
|
-
try {
|
|
202
|
-
const parts = token.id_token.split(".");
|
|
203
|
-
if (parts.length < 3)
|
|
204
|
-
return true; // Invalid JWT format
|
|
205
|
-
const payload = JSON.parse(atob(parts[1]));
|
|
206
|
-
if (typeof payload.exp !== 'number')
|
|
207
|
-
return true;
|
|
208
|
-
const exp = payload.exp * 1000;
|
|
209
|
-
return Date.now() > exp;
|
|
540
|
+
clear() {
|
|
541
|
+
// clear only CAMS-prefixed items
|
|
542
|
+
Object.keys(this.storage).forEach((k) => {
|
|
543
|
+
if (k.startsWith(this.keyPrefix)) {
|
|
544
|
+
this.storage.removeItem(k);
|
|
210
545
|
}
|
|
211
|
-
|
|
212
|
-
console.warn('Failed to parse JWT token:', error instanceof Error ? error.message : 'Unknown error');
|
|
213
|
-
return true;
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
// Fallback: return true for safety when expiration cannot be determined
|
|
217
|
-
return true;
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
class CAMSSession {
|
|
222
|
-
constructor(storage = sessionStorage, storageKey, events = {}) {
|
|
223
|
-
this.tokenManager = new TokenManager(storage, storageKey);
|
|
224
|
-
this.events = events;
|
|
546
|
+
});
|
|
225
547
|
}
|
|
226
548
|
async login(config) {
|
|
227
549
|
try {
|
|
228
|
-
|
|
550
|
+
Logger.info("Session login started");
|
|
551
|
+
// If we're in a popup, don't attempt to open another popup
|
|
552
|
+
if (isPopupWindow()) {
|
|
553
|
+
Logger.warn("Cannot initiate login from popup window");
|
|
554
|
+
throw new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Cannot initiate authentication from within popup window");
|
|
555
|
+
}
|
|
556
|
+
if (this.events.onAuthStart)
|
|
557
|
+
this.events.onAuthStart();
|
|
229
558
|
let attempts = 0;
|
|
230
559
|
const maxAttempts = (config.retryAttempts ?? 0) + 1;
|
|
560
|
+
Logger.debug("Login retry configuration", { maxAttempts });
|
|
231
561
|
while (attempts < maxAttempts) {
|
|
232
562
|
try {
|
|
563
|
+
attempts++;
|
|
564
|
+
Logger.debug("Login attempt", { attempt: attempts, maxAttempts });
|
|
565
|
+
// Add exponential backoff delay for retries
|
|
566
|
+
if (attempts > 1) {
|
|
567
|
+
const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay
|
|
568
|
+
Logger.debug("Retry delay", { delay });
|
|
569
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
570
|
+
}
|
|
233
571
|
const response = await openCAMSPopUpLogin(config);
|
|
234
|
-
|
|
572
|
+
Logger.debug("Login Response", response);
|
|
573
|
+
this.profile = response;
|
|
574
|
+
this.setToken(response.profile.tokens.Bearer);
|
|
575
|
+
Logger.info("Session login successful");
|
|
576
|
+
if (this.events.onAuthSuccess)
|
|
577
|
+
this.events.onAuthSuccess(response);
|
|
235
578
|
return response;
|
|
236
579
|
}
|
|
237
580
|
catch (error) {
|
|
238
|
-
|
|
581
|
+
Logger.warn("Login attempt failed", {
|
|
582
|
+
attempt: attempts,
|
|
583
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
584
|
+
});
|
|
239
585
|
if (attempts >= maxAttempts || !(error instanceof CAMSError)) {
|
|
240
586
|
throw error;
|
|
241
587
|
}
|
|
@@ -243,71 +589,597 @@ class CAMSSession {
|
|
|
243
589
|
if (![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {
|
|
244
590
|
throw error;
|
|
245
591
|
}
|
|
592
|
+
Logger.info("Retrying login", { nextAttempt: attempts + 1 });
|
|
246
593
|
}
|
|
247
594
|
}
|
|
248
|
-
throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED,
|
|
595
|
+
throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, "Max retry attempts exceeded");
|
|
249
596
|
}
|
|
250
597
|
catch (error) {
|
|
251
|
-
const
|
|
252
|
-
|
|
253
|
-
|
|
598
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
599
|
+
const camsError = error instanceof CAMSError
|
|
600
|
+
? error
|
|
601
|
+
: new CAMSError(CAMSErrorType.USER_CANCELLED, errorMessage);
|
|
602
|
+
Logger.error("Session login failed", {
|
|
603
|
+
error: camsError.message,
|
|
604
|
+
type: camsError.type,
|
|
605
|
+
});
|
|
606
|
+
if (this.events.onAuthError)
|
|
607
|
+
this.events.onAuthError(camsError);
|
|
254
608
|
throw camsError;
|
|
255
609
|
}
|
|
256
610
|
}
|
|
257
611
|
async logout() {
|
|
258
|
-
|
|
612
|
+
Logger.info("Session logout");
|
|
613
|
+
this.clearToken();
|
|
259
614
|
}
|
|
260
|
-
|
|
261
|
-
|
|
615
|
+
setToken(token) {
|
|
616
|
+
this.token = token;
|
|
617
|
+
this.storage.setItem(this.keyPrefix, token);
|
|
618
|
+
Logger.debug("Token stored", { storageKey: this.keyPrefix });
|
|
619
|
+
}
|
|
620
|
+
getAccessToken() {
|
|
621
|
+
// Return cached token if available, avoiding redundant storage access
|
|
622
|
+
if (this.token)
|
|
623
|
+
return this.token;
|
|
624
|
+
const raw = this.storage.getItem(this.keyPrefix);
|
|
625
|
+
if (!raw)
|
|
626
|
+
return null;
|
|
627
|
+
this.token = raw;
|
|
628
|
+
Logger.debug("Token loaded from storage");
|
|
629
|
+
return this.token;
|
|
630
|
+
}
|
|
631
|
+
clearToken() {
|
|
632
|
+
this.token = null;
|
|
633
|
+
this.storage.removeItem(this.keyPrefix);
|
|
634
|
+
Logger.debug("Token cleared");
|
|
635
|
+
}
|
|
636
|
+
isExpired() {
|
|
637
|
+
const token = this.getAccessToken();
|
|
638
|
+
if (!token)
|
|
639
|
+
return true;
|
|
640
|
+
try {
|
|
641
|
+
const parts = token.split(".");
|
|
642
|
+
if (parts.length < 3)
|
|
643
|
+
return true; // Invalid JWT format
|
|
644
|
+
const payload = JSON.parse(atob(parts[1]));
|
|
645
|
+
if (typeof payload.exp !== "number")
|
|
646
|
+
return true;
|
|
647
|
+
const exp = payload.exp * 1000;
|
|
648
|
+
return Date.now() > exp;
|
|
649
|
+
}
|
|
650
|
+
catch (error) {
|
|
651
|
+
Logger.warn("Failed to parse JWT token", {
|
|
652
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
653
|
+
});
|
|
654
|
+
return true;
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
isPaddedExpired() {
|
|
658
|
+
const token = this.getAccessToken();
|
|
262
659
|
if (!token)
|
|
660
|
+
return true;
|
|
661
|
+
try {
|
|
662
|
+
const parts = token.split(".");
|
|
663
|
+
if (parts.length < 3)
|
|
664
|
+
return true; // Invalid JWT format
|
|
665
|
+
const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
666
|
+
const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=");
|
|
667
|
+
const payload = JSON.parse(atob(padded));
|
|
668
|
+
if (typeof payload.exp !== "number")
|
|
669
|
+
return true;
|
|
670
|
+
const exp = payload.exp * 1000;
|
|
671
|
+
return Date.now() > exp;
|
|
672
|
+
}
|
|
673
|
+
catch (error) {
|
|
674
|
+
Logger.warn("Failed to parse JWT token", {
|
|
675
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
676
|
+
});
|
|
677
|
+
return true;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
checkTokenExpiration() {
|
|
681
|
+
if (this.isExpired()) {
|
|
682
|
+
Logger.info("Token expired");
|
|
683
|
+
if (this.events.onTokenExpired)
|
|
684
|
+
this.events.onTokenExpired();
|
|
685
|
+
return true;
|
|
686
|
+
}
|
|
687
|
+
return false;
|
|
688
|
+
}
|
|
689
|
+
isAuthenticated() {
|
|
690
|
+
const token = this.getAccessToken();
|
|
691
|
+
if (!token) {
|
|
692
|
+
Logger.debug("No Token Found");
|
|
263
693
|
return false;
|
|
264
|
-
|
|
265
|
-
|
|
694
|
+
}
|
|
695
|
+
if (this.checkTokenExpiration()) {
|
|
266
696
|
return false;
|
|
267
697
|
}
|
|
698
|
+
Logger.debug("Token is valid");
|
|
268
699
|
return true;
|
|
269
700
|
}
|
|
270
|
-
|
|
271
|
-
const
|
|
272
|
-
if (!
|
|
701
|
+
async getProfile() {
|
|
702
|
+
const storedToken = this.getAccessToken();
|
|
703
|
+
if (!storedToken)
|
|
273
704
|
return null;
|
|
274
|
-
|
|
275
|
-
|
|
705
|
+
// Check token expiration before processing
|
|
706
|
+
if (this.checkTokenExpiration()) {
|
|
276
707
|
return null;
|
|
277
708
|
}
|
|
278
|
-
return
|
|
709
|
+
return this.profile;
|
|
710
|
+
}
|
|
711
|
+
getSessionError() {
|
|
712
|
+
return null;
|
|
279
713
|
}
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
714
|
+
/**
|
|
715
|
+
* Complete authentication in popup window
|
|
716
|
+
* This should be called by popup apps when authentication is successful
|
|
717
|
+
*/
|
|
718
|
+
completePopupAuth(user, targetOrigin) {
|
|
719
|
+
if (!isPopupWindow()) {
|
|
720
|
+
Logger.warn("completePopupAuth called outside of popup window");
|
|
721
|
+
return;
|
|
722
|
+
}
|
|
723
|
+
try {
|
|
724
|
+
// Store the authentication data locally in the popup
|
|
725
|
+
this.profile = user;
|
|
726
|
+
this.setToken(user.profile.tokens.Bearer);
|
|
727
|
+
Logger.info("Authentication completed in popup, forwarding to parent");
|
|
728
|
+
}
|
|
729
|
+
catch (error) {
|
|
730
|
+
Logger.error("Failed to complete popup authentication", {
|
|
731
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
732
|
+
});
|
|
286
733
|
}
|
|
287
|
-
return atob(str);
|
|
288
734
|
}
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
735
|
+
/**
|
|
736
|
+
* Report authentication error in popup window
|
|
737
|
+
*/
|
|
738
|
+
errorPopupAuth(error, targetOrigin) {
|
|
739
|
+
if (!isPopupWindow()) {
|
|
740
|
+
Logger.warn("errorPopupAuth called outside of popup window");
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
743
|
+
Logger.warn("Reporting authentication error from popup");
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
// 🔹 Safe fallback for Node/SSR
|
|
747
|
+
function getDefaultStorage() {
|
|
748
|
+
if (typeof window !== "undefined" && window.localStorage) {
|
|
749
|
+
return window.localStorage;
|
|
750
|
+
}
|
|
751
|
+
const memoryStore = {};
|
|
752
|
+
return {
|
|
753
|
+
getItem: (key) => (key in memoryStore ? memoryStore[key] : null),
|
|
754
|
+
setItem: (key, value) => {
|
|
755
|
+
memoryStore[key] = value;
|
|
756
|
+
},
|
|
757
|
+
removeItem: (key) => {
|
|
758
|
+
delete memoryStore[key];
|
|
759
|
+
},
|
|
760
|
+
key: (i) => Object.keys(memoryStore)[i] ?? null,
|
|
761
|
+
get length() {
|
|
762
|
+
return Object.keys(memoryStore).length;
|
|
763
|
+
},
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
// Function to parse userAgent and generate a device ID
|
|
768
|
+
const GenerateDeviceId = () => {
|
|
769
|
+
if (typeof window === "undefined" || !window.navigator) {
|
|
770
|
+
return "unknown-device";
|
|
771
|
+
}
|
|
772
|
+
const userAgent = window.navigator.userAgent;
|
|
773
|
+
let deviceId = "";
|
|
774
|
+
// Parse browser, version, OS, and device type
|
|
775
|
+
const browserMatch = Array.from(userAgent.matchAll(/(Chrome|Firefox|Safari|Edge|Opera)\/([\d.]+)/gi));
|
|
776
|
+
const osMatch = Array.from(userAgent.matchAll(/\(([^)]+)\)/g));
|
|
777
|
+
const isMobile = /Mobile|Android|iPhone|iPad/i.test(userAgent);
|
|
778
|
+
// Browser info
|
|
779
|
+
if (browserMatch.length > 0) {
|
|
780
|
+
const [, browserName, browserVersion] = browserMatch[0];
|
|
781
|
+
const majorVersion = browserVersion.split(".")[0];
|
|
782
|
+
deviceId += `${browserName}-${majorVersion}`;
|
|
783
|
+
}
|
|
784
|
+
else {
|
|
785
|
+
deviceId += "UnknownBrowser";
|
|
786
|
+
}
|
|
787
|
+
// OS info
|
|
788
|
+
if (osMatch.length > 0) {
|
|
789
|
+
const osInfo = osMatch[0][1]
|
|
790
|
+
.split(";")[0]
|
|
791
|
+
.trim()
|
|
792
|
+
.replace(/[\s/()]/g, "_");
|
|
793
|
+
deviceId += `_${osInfo}`;
|
|
794
|
+
}
|
|
795
|
+
else {
|
|
796
|
+
deviceId += "_UnknownOS";
|
|
797
|
+
}
|
|
798
|
+
// Device type
|
|
799
|
+
deviceId += isMobile ? "_Mobile" : "_Desktop";
|
|
800
|
+
// Add a simple hash of userAgent for uniqueness
|
|
801
|
+
const hash = btoa(userAgent).slice(0, 8);
|
|
802
|
+
deviceId += `_${hash}`;
|
|
803
|
+
return deviceId.replace(/[^a-zA-Z0-9-_]/g, "_") ?? "unknown-device";
|
|
804
|
+
};
|
|
805
|
+
const APIHeaders = {
|
|
806
|
+
"X-DEVICE-ID": GenerateDeviceId(),
|
|
807
|
+
"X-API-VERSION": "1.0",
|
|
808
|
+
};
|
|
809
|
+
|
|
810
|
+
const requestSpans = new WeakMap();
|
|
811
|
+
const finishRequestSpan = (config, statusCode, failed = false) => {
|
|
812
|
+
if (!config)
|
|
813
|
+
return;
|
|
814
|
+
const span = requestSpans.get(config);
|
|
815
|
+
if (!span)
|
|
816
|
+
return;
|
|
817
|
+
requestSpans.delete(config);
|
|
818
|
+
if (statusCode !== undefined) {
|
|
819
|
+
span.setAttribute("http.response.status_code", statusCode);
|
|
820
|
+
}
|
|
821
|
+
if (failed) {
|
|
822
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
823
|
+
}
|
|
824
|
+
else {
|
|
825
|
+
span.setStatus({ code: SpanStatusCode.OK });
|
|
826
|
+
}
|
|
827
|
+
span.end();
|
|
828
|
+
};
|
|
829
|
+
// Creates an Axios instance for browser environments.
|
|
830
|
+
const axiosInstance = axios.create({
|
|
831
|
+
// httpsAgent: new https.Agent({ rejectUnauthorized: false }),
|
|
832
|
+
headers: {
|
|
833
|
+
"Content-Type": "application/json",
|
|
834
|
+
...APIHeaders,
|
|
835
|
+
},
|
|
836
|
+
});
|
|
837
|
+
// Intercepts outgoing requests to add authorization token, version header, and timeout settings.
|
|
838
|
+
axiosInstance.interceptors.request.use((config) => {
|
|
839
|
+
const requestConfig = {
|
|
840
|
+
...config,
|
|
841
|
+
timeout: 605000,
|
|
842
|
+
timeoutErrorMessage: "Operation Timed Out",
|
|
843
|
+
};
|
|
844
|
+
const span = startCAMSSpan("CAMS.HTTP.Client", { "http.request.method": config.method?.toUpperCase() ?? "HTTP" }, SpanKind.CLIENT);
|
|
845
|
+
requestSpans.set(requestConfig, span);
|
|
846
|
+
injectCAMSContext(span, requestConfig.headers);
|
|
847
|
+
return requestConfig;
|
|
848
|
+
}, (axiosError) => {
|
|
849
|
+
// Handles request errors.
|
|
850
|
+
return {
|
|
851
|
+
status: axiosError.response?.status,
|
|
852
|
+
message: axiosError.message,
|
|
853
|
+
data: axiosError.response?.data,
|
|
854
|
+
};
|
|
855
|
+
});
|
|
856
|
+
axiosInstance.interceptors.response.use((response) => {
|
|
857
|
+
finishRequestSpan(response.config, response.status);
|
|
858
|
+
return response;
|
|
859
|
+
}, (error) => {
|
|
860
|
+
if (axios.isAxiosError(error)) {
|
|
861
|
+
finishRequestSpan(error.config, error.response?.status, true);
|
|
862
|
+
}
|
|
863
|
+
return Promise.reject(error);
|
|
864
|
+
});
|
|
865
|
+
|
|
866
|
+
function bufferToBase64url(buf) {
|
|
867
|
+
return btoa(String.fromCharCode(...new Uint8Array(buf)))
|
|
868
|
+
.replace(/\+/g, "-")
|
|
869
|
+
.replace(/\//g, "_")
|
|
870
|
+
.replace(/=/g, "");
|
|
871
|
+
}
|
|
872
|
+
function base64urlToBuffer(b64url) {
|
|
873
|
+
const b64 = b64url.replace(/-/g, "+").replace(/_/g, "/");
|
|
874
|
+
const bin = atob(b64);
|
|
875
|
+
return Uint8Array.from(bin, (c) => c.charCodeAt(0)).buffer;
|
|
876
|
+
}
|
|
877
|
+
function prepareRegistrationOptions(options) {
|
|
878
|
+
return {
|
|
879
|
+
...options,
|
|
880
|
+
challenge: base64urlToBuffer(options.challenge),
|
|
881
|
+
user: {
|
|
882
|
+
...options.user,
|
|
883
|
+
id: base64urlToBuffer(options.user.id),
|
|
884
|
+
},
|
|
885
|
+
excludeCredentials: (options.excludeCredentials ?? []).map((c) => ({
|
|
886
|
+
...c,
|
|
887
|
+
id: base64urlToBuffer(c.id),
|
|
888
|
+
})),
|
|
889
|
+
};
|
|
890
|
+
}
|
|
891
|
+
function prepareAssertionOptions(options) {
|
|
892
|
+
return {
|
|
893
|
+
...options,
|
|
894
|
+
challenge: base64urlToBuffer(options.challenge),
|
|
895
|
+
allowCredentials: (options.allowCredentials ?? []).map((c) => ({
|
|
896
|
+
...c,
|
|
897
|
+
id: base64urlToBuffer(c.id),
|
|
898
|
+
})),
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
function serializeAttestation(cred) {
|
|
902
|
+
const response = cred.response;
|
|
903
|
+
return {
|
|
904
|
+
id: cred.id,
|
|
905
|
+
rawId: bufferToBase64url(cred.rawId),
|
|
906
|
+
type: cred.type,
|
|
907
|
+
response: {
|
|
908
|
+
attestationObject: bufferToBase64url(response.attestationObject),
|
|
909
|
+
clientDataJSON: bufferToBase64url(response.clientDataJSON),
|
|
910
|
+
transports: response.getTransports?.() ?? [],
|
|
911
|
+
},
|
|
912
|
+
clientExtensionResults: cred.getClientExtensionResults(),
|
|
913
|
+
};
|
|
914
|
+
}
|
|
915
|
+
function serializeAssertion(cred) {
|
|
916
|
+
const response = cred.response;
|
|
917
|
+
return {
|
|
918
|
+
id: cred.id,
|
|
919
|
+
rawId: bufferToBase64url(cred.rawId),
|
|
920
|
+
type: cred.type,
|
|
921
|
+
response: {
|
|
922
|
+
authenticatorData: bufferToBase64url(response.authenticatorData),
|
|
923
|
+
clientDataJSON: bufferToBase64url(response.clientDataJSON),
|
|
924
|
+
signature: bufferToBase64url(response.signature),
|
|
925
|
+
userHandle: response.userHandle
|
|
926
|
+
? bufferToBase64url(response.userHandle)
|
|
927
|
+
: null,
|
|
928
|
+
},
|
|
929
|
+
clientExtensionResults: cred.getClientExtensionResults(),
|
|
930
|
+
};
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
class CAMSMFAAuthenticator {
|
|
934
|
+
attemptCount = 0;
|
|
935
|
+
maxAttempts = 3;
|
|
936
|
+
async GetUserMFAConfig(config) {
|
|
293
937
|
try {
|
|
294
|
-
const
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
938
|
+
const response = await axiosInstance.post(config.APIAuthEndpoint, {
|
|
939
|
+
Provider: config.provider,
|
|
940
|
+
accessToken: config.accessToken,
|
|
941
|
+
idToken: config.idToken,
|
|
942
|
+
});
|
|
943
|
+
Logger.debug("GetUserMFAConfig Response", response);
|
|
944
|
+
return response.data;
|
|
945
|
+
}
|
|
946
|
+
catch (error) {
|
|
947
|
+
Logger.error("GetUserMFAConfig Failed", error);
|
|
948
|
+
if (error.code === "ERR_NETWORK" ||
|
|
949
|
+
error.code === "ECONNREFUSED" ||
|
|
950
|
+
error.code === "ERR_CONNECTION_REFUSED") {
|
|
951
|
+
throw new CAMSError(CAMSErrorType.NETWORK_ERROR, "Cannot Connect to CAS MFA server.");
|
|
952
|
+
}
|
|
953
|
+
if (error instanceof AxiosError && error.response?.status === 401) {
|
|
954
|
+
throw new CAMSError(CAMSErrorType.API_UNAUTHORIZED_ERROR, error.response?.data?.message ?? "Unauthorized: User Validation Failed");
|
|
955
|
+
}
|
|
956
|
+
throw new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, `Failed to Retrieve MFA Configuration: ${error.message || "Unknown error"}`);
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
async VerifyMFAOTP(ValidateRequest, MFAEndpoint) {
|
|
960
|
+
if (this.attemptCount >= this.maxAttempts) {
|
|
961
|
+
throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, "Maximum MFA attempts exceeded");
|
|
962
|
+
}
|
|
963
|
+
this.attemptCount++;
|
|
964
|
+
try {
|
|
965
|
+
Logger.debug("Verifying User MFA Code", { attempt: this.attemptCount });
|
|
966
|
+
const response = await axiosInstance.post(MFAEndpoint, ValidateRequest);
|
|
967
|
+
const data = response.data;
|
|
968
|
+
console.log("API MFA Response >>>", data);
|
|
969
|
+
if (data.isValid) {
|
|
970
|
+
Logger.info("API >>> MFA Verification Successful");
|
|
971
|
+
this.ResetUserAttempts();
|
|
972
|
+
return data;
|
|
973
|
+
}
|
|
974
|
+
else {
|
|
975
|
+
throw new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, data.message || "User MFA Verification Failed");
|
|
303
976
|
}
|
|
304
977
|
}
|
|
305
978
|
catch (error) {
|
|
306
|
-
|
|
979
|
+
Logger.error("MFA Verification Failed", {
|
|
980
|
+
error: error.response,
|
|
981
|
+
attempt: this.attemptCount,
|
|
982
|
+
});
|
|
983
|
+
if (error.code === "ERR_NETWORK" ||
|
|
984
|
+
error.code === "ECONNREFUSED" ||
|
|
985
|
+
error.code === "ERR_CONNECTION_REFUSED") {
|
|
986
|
+
throw new CAMSError(CAMSErrorType.NETWORK_ERROR, "Cannot Connect to CAS MFA Server.");
|
|
987
|
+
}
|
|
988
|
+
if (error instanceof AxiosError && error.response?.status === 401) {
|
|
989
|
+
Logger.error("MFA Verification Failed - Unauthorized", {
|
|
990
|
+
error: error.response?.data,
|
|
991
|
+
status: error.response?.status,
|
|
992
|
+
attempt: this.attemptCount,
|
|
993
|
+
});
|
|
994
|
+
throw new CAMSError(CAMSErrorType.API_UNAUTHORIZED_ERROR, // or your equivalent unauthorized error type
|
|
995
|
+
`MFA Verification Failed: ${error.response?.data?.message ?? "Unauthorized"}`);
|
|
996
|
+
}
|
|
997
|
+
throw new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, `MFA Verification Failed: ${error instanceof AxiosError
|
|
998
|
+
? error?.response?.data.message
|
|
999
|
+
: "Unknown Error"}`);
|
|
307
1000
|
}
|
|
308
|
-
return null;
|
|
309
1001
|
}
|
|
1002
|
+
async LoginADCredentials(credentials, CredentialsAuthEndpoint) {
|
|
1003
|
+
try {
|
|
1004
|
+
const response = await axiosInstance.post(CredentialsAuthEndpoint, credentials);
|
|
1005
|
+
credentials.password = ""; // Clear password after use
|
|
1006
|
+
if (!response?.data) {
|
|
1007
|
+
throw new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, "No response data received from Server");
|
|
1008
|
+
}
|
|
1009
|
+
Logger.debug("LoginADCredentials Response", response);
|
|
1010
|
+
return response.data;
|
|
1011
|
+
}
|
|
1012
|
+
catch (error) {
|
|
1013
|
+
credentials.password = ""; // Clear password even on error
|
|
1014
|
+
Logger.error("AD Credentials Login Failed", error);
|
|
1015
|
+
if (error instanceof CAMSError) {
|
|
1016
|
+
throw error;
|
|
1017
|
+
}
|
|
1018
|
+
if (error.code === "ERR_NETWORK" ||
|
|
1019
|
+
error.code === "ECONNREFUSED" ||
|
|
1020
|
+
error.code === "ERR_CONNECTION_REFUSED") {
|
|
1021
|
+
throw new CAMSError(CAMSErrorType.NETWORK_ERROR, "Cannot Connect to CAS MFA server.");
|
|
1022
|
+
}
|
|
1023
|
+
throw new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, error?.response?.data.message || "Unknown Error");
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
async HandleFIDOLogin(RetrieveAuthChallengeEndpoint, AuthChallengeVerifyEndpoint, email) {
|
|
1027
|
+
try {
|
|
1028
|
+
Logger.debug("Requesting authentication challenge from server...");
|
|
1029
|
+
const response = await axiosInstance.post(RetrieveAuthChallengeEndpoint, { email });
|
|
1030
|
+
if (!response?.data) {
|
|
1031
|
+
throw new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, "No Challenge data received from server");
|
|
1032
|
+
}
|
|
1033
|
+
Logger.debug("Received auth challenge", response.data);
|
|
1034
|
+
const options = prepareAssertionOptions(response.data);
|
|
1035
|
+
const credential = await navigator.credentials.get({ publicKey: options });
|
|
1036
|
+
if (!credential) {
|
|
1037
|
+
throw new CAMSError(CAMSErrorType.USER_CANCELLED, "No credential returned by authenticator");
|
|
1038
|
+
}
|
|
1039
|
+
Logger.debug("Assertion received, verifying with server...");
|
|
1040
|
+
await axiosInstance.post(`${AuthChallengeVerifyEndpoint}?username=${encodeURIComponent(email)}`, serializeAssertion(credential));
|
|
1041
|
+
return true;
|
|
1042
|
+
}
|
|
1043
|
+
catch (error) {
|
|
1044
|
+
Logger.error("FIDO2 Authentication failed", error);
|
|
1045
|
+
if (error instanceof CAMSError)
|
|
1046
|
+
throw error;
|
|
1047
|
+
if (error.code === "ERR_NETWORK" ||
|
|
1048
|
+
error.code === "ECONNREFUSED" ||
|
|
1049
|
+
error.code === "ERR_CONNECTION_REFUSED") {
|
|
1050
|
+
throw new CAMSError(CAMSErrorType.NETWORK_ERROR, "Cannot Connect to CAS MFA Server.");
|
|
1051
|
+
}
|
|
1052
|
+
return false;
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
async HandleRegister(RegisterNewChallengeEndpoint, RegisterVerifyEndpoint, data) {
|
|
1056
|
+
try {
|
|
1057
|
+
Logger.debug("Requesting registration challenge from server...");
|
|
1058
|
+
const response = await axiosInstance.post(RegisterNewChallengeEndpoint, data);
|
|
1059
|
+
if (!response?.data) {
|
|
1060
|
+
throw new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, "No challenge data received from server");
|
|
1061
|
+
}
|
|
1062
|
+
Logger.debug("Received registration challenge", response.data);
|
|
1063
|
+
const options = prepareRegistrationOptions(response.data);
|
|
1064
|
+
const credential = await navigator.credentials.create({ publicKey: options });
|
|
1065
|
+
if (!credential) {
|
|
1066
|
+
throw new CAMSError(CAMSErrorType.USER_CANCELLED, "No credential returned by authenticator");
|
|
1067
|
+
}
|
|
1068
|
+
Logger.debug("Attestation received, verifying with server...");
|
|
1069
|
+
await axiosInstance.post(`${RegisterVerifyEndpoint}?username=${encodeURIComponent(data.email)}`, serializeAttestation(credential));
|
|
1070
|
+
return true;
|
|
1071
|
+
}
|
|
1072
|
+
catch (error) {
|
|
1073
|
+
Logger.error("FIDO2 Registration failed", error);
|
|
1074
|
+
if (error instanceof CAMSError)
|
|
1075
|
+
throw error;
|
|
1076
|
+
if (error.code === "ERR_NETWORK" ||
|
|
1077
|
+
error.code === "ECONNREFUSED" ||
|
|
1078
|
+
error.code === "ERR_CONNECTION_REFUSED") {
|
|
1079
|
+
throw new CAMSError(CAMSErrorType.NETWORK_ERROR, "Cannot Connect to CAS MFA Server.");
|
|
1080
|
+
}
|
|
1081
|
+
return false;
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
/**
|
|
1085
|
+
* Opens a popup to the central auth domain to perform the passkey sign-in
|
|
1086
|
+
* ceremony there, then verifies the resulting assertion with the server.
|
|
1087
|
+
* Use this when the client page's origin does not match the RP ID.
|
|
1088
|
+
*/
|
|
1089
|
+
async HandleFIDOLoginViaPopup(passkeyPopupUrl, AuthChallengeVerifyEndpoint, email, options = {}) {
|
|
1090
|
+
const { windowWidth = 500, windowHeight = 600, timeout = 300000 } = options;
|
|
1091
|
+
const popupOrigin = new URL(passkeyPopupUrl).origin;
|
|
1092
|
+
const url = new URL(passkeyPopupUrl);
|
|
1093
|
+
url.searchParams.set("email", email);
|
|
1094
|
+
url.searchParams.set("action", "authenticate");
|
|
1095
|
+
url.searchParams.set("verifyEndpoint", AuthChallengeVerifyEndpoint);
|
|
1096
|
+
const assertion = await openPasskeyPopup(url.toString(), popupOrigin, windowWidth, windowHeight, timeout);
|
|
1097
|
+
Logger.debug("Popup returned assertion, verifying with server...");
|
|
1098
|
+
await axiosInstance.post(`${AuthChallengeVerifyEndpoint}?username=${encodeURIComponent(email)}`, assertion);
|
|
1099
|
+
return true;
|
|
1100
|
+
}
|
|
1101
|
+
/**
|
|
1102
|
+
* Opens a popup to the central auth domain to perform the passkey registration
|
|
1103
|
+
* ceremony there, then verifies the resulting attestation with the server.
|
|
1104
|
+
* Use this when the client page's origin does not match the RP ID.
|
|
1105
|
+
*/
|
|
1106
|
+
async HandleRegisterViaPopup(passkeyPopupUrl, RegisterVerifyEndpoint, data, options = {}) {
|
|
1107
|
+
const { windowWidth = 500, windowHeight = 600, timeout = 300000 } = options;
|
|
1108
|
+
const popupOrigin = new URL(passkeyPopupUrl).origin;
|
|
1109
|
+
const url = new URL(passkeyPopupUrl);
|
|
1110
|
+
url.searchParams.set("email", data.email);
|
|
1111
|
+
url.searchParams.set("displayName", data.displayName);
|
|
1112
|
+
url.searchParams.set("action", "register");
|
|
1113
|
+
url.searchParams.set("verifyEndpoint", RegisterVerifyEndpoint);
|
|
1114
|
+
const attestation = await openPasskeyPopup(url.toString(), popupOrigin, windowWidth, windowHeight, timeout);
|
|
1115
|
+
Logger.debug("Popup returned attestation, verifying with server...");
|
|
1116
|
+
await axiosInstance.post(`${RegisterVerifyEndpoint}?username=${encodeURIComponent(data.email)}`, attestation);
|
|
1117
|
+
return true;
|
|
1118
|
+
}
|
|
1119
|
+
GetRemainingAttempts() {
|
|
1120
|
+
return Math.max(0, this.maxAttempts - this.attemptCount);
|
|
1121
|
+
}
|
|
1122
|
+
ResetUserAttempts() {
|
|
1123
|
+
this.attemptCount = 0;
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
/**
|
|
1127
|
+
* Opens a popup window to the central auth domain, waits for it to post back
|
|
1128
|
+
* a `{ type: 'CAMS_PASSKEY_RESULT', payload }` message, and resolves with the
|
|
1129
|
+
* payload. Rejects on timeout, user cancellation, or an error payload.
|
|
1130
|
+
*/
|
|
1131
|
+
function openPasskeyPopup(url, expectedOrigin, windowWidth, windowHeight, timeout) {
|
|
1132
|
+
return new Promise((resolve, reject) => {
|
|
1133
|
+
const left = Math.max(0, (window.screen.width - windowWidth) / 2);
|
|
1134
|
+
const top = Math.max(0, (window.screen.height - windowHeight) / 2);
|
|
1135
|
+
const popup = window.open(url, `cams_passkey_${Date.now()}`, `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes`);
|
|
1136
|
+
if (!popup) {
|
|
1137
|
+
reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Passkey popup was blocked by the browser."));
|
|
1138
|
+
return;
|
|
1139
|
+
}
|
|
1140
|
+
let settled = false;
|
|
1141
|
+
const settle = (fn) => {
|
|
1142
|
+
if (settled)
|
|
1143
|
+
return;
|
|
1144
|
+
settled = true;
|
|
1145
|
+
clearTimeout(timeoutId);
|
|
1146
|
+
clearInterval(closedPollId);
|
|
1147
|
+
window.removeEventListener("message", onMessage);
|
|
1148
|
+
try {
|
|
1149
|
+
popup.close();
|
|
1150
|
+
}
|
|
1151
|
+
catch { /* cross-origin */ }
|
|
1152
|
+
fn();
|
|
1153
|
+
};
|
|
1154
|
+
const onMessage = (event) => {
|
|
1155
|
+
if (event.origin !== expectedOrigin)
|
|
1156
|
+
return;
|
|
1157
|
+
if (event.source !== popup)
|
|
1158
|
+
return;
|
|
1159
|
+
if (!event.data || event.data.type !== "CAMS_PASSKEY_RESULT")
|
|
1160
|
+
return;
|
|
1161
|
+
const { success, payload, error } = event.data;
|
|
1162
|
+
if (success && payload) {
|
|
1163
|
+
settle(() => resolve(payload));
|
|
1164
|
+
}
|
|
1165
|
+
else {
|
|
1166
|
+
settle(() => reject(new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, error ?? "Passkey ceremony failed.")));
|
|
1167
|
+
}
|
|
1168
|
+
};
|
|
1169
|
+
window.addEventListener("message", onMessage);
|
|
1170
|
+
const timeoutId = setTimeout(() => {
|
|
1171
|
+
settle(() => reject(new CAMSError(CAMSErrorType.TIMEOUT, "Passkey popup timed out.")));
|
|
1172
|
+
}, timeout);
|
|
1173
|
+
const closedPollId = setInterval(() => {
|
|
1174
|
+
try {
|
|
1175
|
+
if (popup.closed) {
|
|
1176
|
+
settle(() => reject(new CAMSError(CAMSErrorType.USER_CANCELLED, "Passkey popup was closed.")));
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
catch { /* cross-origin — ignore */ }
|
|
1180
|
+
}, 1000);
|
|
1181
|
+
});
|
|
310
1182
|
}
|
|
311
1183
|
|
|
312
|
-
export { CAMSError, CAMSErrorType,
|
|
1184
|
+
export { APIHeaders, AuthFailureMessageSchema, CAMSError, CAMSErrorType, CAMSMFAAuthenticator, CAMSSessionManager, ErrorMessageSchema, LogLevel, Logger, ProfileSchema, URLSchema, axiosInstance, base64urlToBuffer, bufferToBase64url, generateSecureWindowName, isPopupWindow, openCAMSPopUpLogin, prepareAssertionOptions, prepareRegistrationOptions, serializeAssertion, serializeAttestation, validateConfig };
|
|
313
1185
|
//# sourceMappingURL=index.esm.js.map
|