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