@nibssplc/cams-sdk 0.0.1-beta.3 → 0.0.1-beta.31
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 +384 -36
- package/dist/auth.d.ts +5 -3
- package/dist/index.cjs.js +430 -187
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +2 -3
- package/dist/index.esm.js +427 -184
- package/dist/index.esm.js.map +1 -1
- package/dist/index.umd.js +430 -187
- package/dist/index.umd.js.map +1 -1
- package/dist/logger.d.ts +19 -0
- package/dist/sessionManager.d.ts +39 -0
- package/dist/types.d.ts +6 -10
- package/dist/validators.d.ts +27 -20
- package/package.json +22 -5
- package/dist/session.d.ts +0 -19
- package/dist/tokenManager.d.ts +0 -12
package/dist/index.umd.js
CHANGED
|
@@ -12,229 +12,387 @@
|
|
|
12
12
|
CAMSErrorType["USER_CANCELLED"] = "USER_CANCELLED";
|
|
13
13
|
CAMSErrorType["INVALID_URL"] = "INVALID_URL";
|
|
14
14
|
CAMSErrorType["MAX_RETRIES_EXCEEDED"] = "MAX_RETRIES_EXCEEDED";
|
|
15
|
+
CAMSErrorType["API_VALIDATION_ERROR"] = "VALIDATION_ERROR";
|
|
15
16
|
})(exports.CAMSErrorType || (exports.CAMSErrorType = {}));
|
|
16
17
|
class CAMSError extends Error {
|
|
18
|
+
type;
|
|
17
19
|
constructor(type, message) {
|
|
18
20
|
super(message);
|
|
19
21
|
this.type = type;
|
|
20
|
-
this.name =
|
|
22
|
+
this.name = this.constructor.name;
|
|
21
23
|
}
|
|
22
24
|
}
|
|
23
25
|
|
|
24
|
-
// Validate the returned token -
|
|
25
|
-
const
|
|
26
|
-
|
|
26
|
+
// Validate the returned token - non-empty string
|
|
27
|
+
const ProfileSchema = zod.z.object({
|
|
28
|
+
type: zod.z.literal("AUTH_SUCCESS"),
|
|
29
|
+
userProfile: zod.z
|
|
30
|
+
.object({
|
|
31
|
+
name: zod.z.string(),
|
|
32
|
+
email: zod.z.email(),
|
|
33
|
+
mfaIsEnabled: zod.z.boolean(),
|
|
34
|
+
message: zod.z.string(),
|
|
35
|
+
isAuthenticated: zod.z.boolean(),
|
|
36
|
+
userType: zod.z.enum(["SUPER_ADMIN", "ADMIN", "USER"]),
|
|
37
|
+
redirectURL: zod.z.url().optional(),
|
|
38
|
+
tokens: zod.z.object({
|
|
39
|
+
Nonce: zod.z.string(),
|
|
40
|
+
Bearer: zod.z.string(),
|
|
41
|
+
}),
|
|
42
|
+
}),
|
|
27
43
|
});
|
|
28
44
|
const ErrorMessageSchema = zod.z.object({
|
|
29
|
-
error: zod.z.string(),
|
|
30
|
-
});
|
|
31
|
-
const TokenSchema = zod.z.object({
|
|
32
|
-
access_token: zod.z.string(),
|
|
33
|
-
refresh_token: zod.z.string().optional(),
|
|
34
|
-
expires_in: zod.z.number(), // in seconds
|
|
35
|
-
token_type: zod.z.string().default("Bearer"),
|
|
36
|
-
id_token: zod.z.string().optional(),
|
|
45
|
+
error: zod.z.string().min(1, "Error message cannot be empty"),
|
|
37
46
|
});
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
family_name: zod.z.string().optional(),
|
|
44
|
-
roles: zod.z.array(zod.z.string()).optional(),
|
|
47
|
+
const AuthFailureMessageSchema = zod.z.object({
|
|
48
|
+
type: zod.z.literal("AUTH_FAILURE"),
|
|
49
|
+
error: zod.z.string().min(1, "Error message cannot be empty"),
|
|
50
|
+
errorCode: zod.z.string(),
|
|
51
|
+
errorDetails: zod.z.object().or(zod.z.any()),
|
|
45
52
|
});
|
|
46
|
-
|
|
47
|
-
|
|
53
|
+
const URLSchema = zod.z.url();
|
|
54
|
+
|
|
55
|
+
exports.LogLevel = void 0;
|
|
56
|
+
(function (LogLevel) {
|
|
57
|
+
LogLevel[LogLevel["ERROR"] = 0] = "ERROR";
|
|
58
|
+
LogLevel[LogLevel["WARN"] = 1] = "WARN";
|
|
59
|
+
LogLevel[LogLevel["INFO"] = 2] = "INFO";
|
|
60
|
+
LogLevel[LogLevel["DEBUG"] = 3] = "DEBUG";
|
|
61
|
+
})(exports.LogLevel || (exports.LogLevel = {}));
|
|
62
|
+
class Logger {
|
|
63
|
+
static level = exports.LogLevel.WARN;
|
|
64
|
+
static prefix = '[CAMS-SDK]';
|
|
65
|
+
static isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';
|
|
66
|
+
static setLevel(level) {
|
|
67
|
+
Logger.level = level;
|
|
68
|
+
}
|
|
69
|
+
static error(message, context) {
|
|
70
|
+
if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.ERROR) {
|
|
71
|
+
console.error(`${Logger.prefix} ERROR:`, message, context || '');
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
static warn(message, context) {
|
|
75
|
+
if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.WARN) {
|
|
76
|
+
console.warn(`${Logger.prefix} WARN:`, message, context || '');
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
static info(message, context) {
|
|
80
|
+
if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.INFO) {
|
|
81
|
+
console.info(`${Logger.prefix} INFO:`, message, context || '');
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
static debug(message, context) {
|
|
85
|
+
if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.DEBUG) {
|
|
86
|
+
console.debug(`${Logger.prefix} DEBUG:`, message, context || '');
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
48
90
|
|
|
91
|
+
// Capture original functions to prevent tampering
|
|
92
|
+
const originalWindowOpen = window.open;
|
|
93
|
+
const originalAddEventListener = window.addEventListener;
|
|
94
|
+
const originalRemoveEventListener = window.removeEventListener;
|
|
95
|
+
const originalSetTimeout = window.setTimeout;
|
|
96
|
+
const originalClearTimeout = window.clearTimeout;
|
|
97
|
+
// Generate random window name to prevent targeting
|
|
98
|
+
const generateSecureWindowName = () => `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;
|
|
49
99
|
function validateConfig(config) {
|
|
50
|
-
|
|
51
|
-
// Validate URL format
|
|
100
|
+
// Validate URL format and parse once
|
|
52
101
|
const urlValidation = URLSchema.safeParse(config.camsUrl);
|
|
53
102
|
if (!urlValidation.success) {
|
|
54
|
-
throw new CAMSError(exports.CAMSErrorType.INVALID_URL,
|
|
103
|
+
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Invalid CAMS URL format");
|
|
55
104
|
}
|
|
56
105
|
// Domain validation is mandatory for security
|
|
57
|
-
if (!
|
|
58
|
-
throw new CAMSError(exports.CAMSErrorType.INVALID_URL,
|
|
59
|
-
}
|
|
60
|
-
const url = new URL(config.camsUrl); // URLSchema already validated this
|
|
61
|
-
const isAllowed = config.allowedDomains.some(domain => url.hostname === domain || url.hostname.endsWith('.' + domain));
|
|
62
|
-
if (!isAllowed) {
|
|
63
|
-
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'URL not in allowed domains list');
|
|
106
|
+
if (!config.messageOrigin) {
|
|
107
|
+
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Message Origin must be specified for security");
|
|
64
108
|
}
|
|
109
|
+
const url = new URL(config.camsUrl);
|
|
110
|
+
return url;
|
|
65
111
|
}
|
|
66
112
|
function openCAMSPopUpLogin(config) {
|
|
67
113
|
return new Promise((resolve, reject) => {
|
|
114
|
+
if (config.debug)
|
|
115
|
+
Logger.setLevel(exports.LogLevel.DEBUG);
|
|
116
|
+
Logger.info("Starting CAMS authentication", { url: config.camsUrl });
|
|
117
|
+
let validatedUrl;
|
|
68
118
|
try {
|
|
69
|
-
validateConfig(config);
|
|
119
|
+
validatedUrl = validateConfig(config);
|
|
120
|
+
Logger.debug("Config validation passed");
|
|
70
121
|
}
|
|
71
122
|
catch (error) {
|
|
123
|
+
Logger.error("Config validation failed", {
|
|
124
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
125
|
+
});
|
|
72
126
|
reject(error);
|
|
73
127
|
return;
|
|
74
128
|
}
|
|
75
|
-
const {
|
|
129
|
+
const { messageOrigin, windowHeight, windowWidth, authTimeout = 300000, // 5 minutes as a final failsafe
|
|
130
|
+
idleTimeout = 120000, // 2 minutes of inactivity
|
|
131
|
+
} = config;
|
|
76
132
|
let authWindow;
|
|
77
|
-
let
|
|
133
|
+
let authTimeoutId = null;
|
|
134
|
+
let idleTimeoutId = null;
|
|
78
135
|
let checkClosedInterval = null;
|
|
79
136
|
try {
|
|
80
|
-
|
|
137
|
+
Logger.debug("Opening popup window", {
|
|
138
|
+
width: windowWidth,
|
|
139
|
+
height: windowHeight,
|
|
140
|
+
});
|
|
141
|
+
// Center the popup window
|
|
142
|
+
const left = (window.screen.width - windowWidth) / 2;
|
|
143
|
+
const top = (window.screen.height - windowHeight) / 2;
|
|
144
|
+
const secureWindowName = generateSecureWindowName();
|
|
145
|
+
authWindow = originalWindowOpen.call(window, validatedUrl.toString(), secureWindowName, `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes`);
|
|
81
146
|
}
|
|
82
147
|
catch (error) {
|
|
83
|
-
|
|
148
|
+
Logger.error("Failed to open popup window", {
|
|
149
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
150
|
+
});
|
|
151
|
+
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
|
|
84
152
|
return;
|
|
85
153
|
}
|
|
86
154
|
if (!authWindow) {
|
|
87
|
-
|
|
155
|
+
Logger.error("Popup window blocked");
|
|
156
|
+
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
// Only check for immediate closure (true popup blocking)
|
|
160
|
+
if (authWindow.closed) {
|
|
161
|
+
Logger.error("Popup immediately closed by blocker");
|
|
162
|
+
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
|
|
88
163
|
return;
|
|
89
164
|
}
|
|
165
|
+
Logger.debug("Popup window opened successfully");
|
|
90
166
|
const cleanup = () => {
|
|
91
|
-
|
|
92
|
-
if (
|
|
93
|
-
|
|
167
|
+
originalRemoveEventListener.call(window, "message", listener);
|
|
168
|
+
if (idleTimeoutId)
|
|
169
|
+
originalClearTimeout(idleTimeoutId);
|
|
170
|
+
if (authTimeoutId)
|
|
171
|
+
originalClearTimeout(authTimeoutId);
|
|
94
172
|
if (checkClosedInterval)
|
|
95
|
-
|
|
173
|
+
originalClearTimeout(checkClosedInterval);
|
|
174
|
+
idleTimeoutId = null;
|
|
175
|
+
authTimeoutId = null;
|
|
176
|
+
checkClosedInterval = null;
|
|
96
177
|
};
|
|
97
|
-
const
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
178
|
+
const listener = (event) => {
|
|
179
|
+
const messageEvent = event;
|
|
180
|
+
Logger.debug("Received message", {
|
|
181
|
+
origin: messageEvent.origin,
|
|
182
|
+
expectedOrigin: messageOrigin,
|
|
183
|
+
data: messageEvent.data,
|
|
184
|
+
});
|
|
185
|
+
const originUrl = new URL(messageEvent.origin);
|
|
186
|
+
const expectedHostname = messageOrigin.startsWith("http")
|
|
187
|
+
? new URL(messageOrigin).hostname
|
|
188
|
+
: messageOrigin;
|
|
189
|
+
// Allow Microsoft redirect domains for Azure AD authentication
|
|
190
|
+
const isMicrosoftDomain = originUrl.hostname.endsWith(".microsoft.com") ||
|
|
191
|
+
originUrl.hostname.endsWith(".microsoftonline.com") ||
|
|
192
|
+
originUrl.hostname.endsWith(".live.com");
|
|
193
|
+
const isAllowedOrigin = originUrl.hostname === expectedHostname ||
|
|
194
|
+
originUrl.hostname.endsWith("." + expectedHostname) ||
|
|
195
|
+
isMicrosoftDomain;
|
|
196
|
+
if (!isAllowedOrigin) {
|
|
197
|
+
Logger.warn("Blocked message from unauthorized origin", {
|
|
198
|
+
origin: messageEvent.origin,
|
|
199
|
+
expected: messageOrigin,
|
|
200
|
+
data: messageEvent.data,
|
|
201
|
+
});
|
|
202
|
+
return;
|
|
103
203
|
}
|
|
104
|
-
|
|
105
|
-
|
|
204
|
+
// Validate event source
|
|
205
|
+
if (messageEvent.source !== authWindow) {
|
|
206
|
+
Logger.warn("Message from unexpected source", {
|
|
207
|
+
source: messageEvent.source,
|
|
208
|
+
origin: messageEvent.origin,
|
|
209
|
+
expected: messageOrigin,
|
|
210
|
+
data: messageEvent.data,
|
|
211
|
+
});
|
|
212
|
+
return;
|
|
106
213
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
214
|
+
// Validate event source
|
|
215
|
+
if (messageEvent.source !== authWindow) {
|
|
216
|
+
Logger.warn("Message from unexpected source", {
|
|
217
|
+
source: messageEvent.source,
|
|
218
|
+
origin: messageEvent.origin,
|
|
219
|
+
expected: messageOrigin,
|
|
220
|
+
data: messageEvent.data,
|
|
221
|
+
});
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
// Ignore heartbeat messages
|
|
225
|
+
if (messageEvent.data?.type === "heartbeat") {
|
|
226
|
+
Logger.debug("Received heartbeat message");
|
|
227
|
+
resetIdleTimeout();
|
|
115
228
|
return;
|
|
116
229
|
}
|
|
117
230
|
// ✅ Validate payload
|
|
118
|
-
const tokenMsg =
|
|
231
|
+
const tokenMsg = ProfileSchema.safeParse(messageEvent.data);
|
|
119
232
|
if (tokenMsg.success) {
|
|
233
|
+
Logger.info("Authentication successful");
|
|
120
234
|
cleanupAndClose();
|
|
121
|
-
resolve(
|
|
235
|
+
resolve(tokenMsg.data);
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
const authFailureMsg = AuthFailureMessageSchema.safeParse(messageEvent.data);
|
|
239
|
+
if (authFailureMsg.success) {
|
|
240
|
+
Logger.warn("Authentication failure received", {
|
|
241
|
+
errorDetails: authFailureMsg.data.errorDetails,
|
|
242
|
+
error: authFailureMsg.data.error,
|
|
243
|
+
errorCode: authFailureMsg.data.errorCode,
|
|
244
|
+
});
|
|
245
|
+
cleanupAndClose(new CAMSError(exports.CAMSErrorType.API_VALIDATION_ERROR, "Authentication failed: " + authFailureMsg.data.error));
|
|
122
246
|
return;
|
|
123
247
|
}
|
|
124
|
-
const errorMsg = ErrorMessageSchema.safeParse(
|
|
248
|
+
const errorMsg = ErrorMessageSchema.safeParse(messageEvent.data);
|
|
125
249
|
if (errorMsg.success) {
|
|
250
|
+
Logger.warn("Authentication error received", {
|
|
251
|
+
error: errorMsg.data.error,
|
|
252
|
+
});
|
|
126
253
|
cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication failed: " + errorMsg.data.error));
|
|
127
254
|
return;
|
|
128
255
|
}
|
|
256
|
+
Logger.error("Invalid message format received", {
|
|
257
|
+
messageData: messageEvent.data,
|
|
258
|
+
dataType: typeof messageEvent.data,
|
|
259
|
+
tokenValidationError: tokenMsg.error
|
|
260
|
+
? tokenMsg.error.issues
|
|
261
|
+
: undefined,
|
|
262
|
+
errorValidationError: errorMsg.error
|
|
263
|
+
? errorMsg.error.issues
|
|
264
|
+
: undefined,
|
|
265
|
+
});
|
|
129
266
|
cleanupAndClose(new CAMSError(exports.CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
|
|
130
267
|
};
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
268
|
+
const cleanupAndClose = (error) => {
|
|
269
|
+
cleanup();
|
|
270
|
+
try {
|
|
271
|
+
if (authWindow && !authWindow.closed) {
|
|
272
|
+
authWindow.close();
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
catch {
|
|
276
|
+
// Ignore close errors
|
|
277
|
+
}
|
|
278
|
+
if (error)
|
|
279
|
+
reject(error);
|
|
280
|
+
};
|
|
281
|
+
const resetIdleTimeout = () => {
|
|
282
|
+
// Timeout handler
|
|
283
|
+
if (idleTimeoutId)
|
|
284
|
+
originalClearTimeout(idleTimeoutId);
|
|
285
|
+
Logger.debug("Resetting idle timeout", { idleTimeout });
|
|
286
|
+
idleTimeoutId = originalSetTimeout(() => {
|
|
287
|
+
Logger.warn("Authentication idle timeout reached", { idleTimeout });
|
|
288
|
+
cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timed out due to inactivity after ${idleTimeout}ms`));
|
|
289
|
+
}, idleTimeout);
|
|
290
|
+
};
|
|
291
|
+
Logger.debug("Setting auth timeout", { authTimeout });
|
|
292
|
+
authTimeoutId = originalSetTimeout(() => {
|
|
293
|
+
Logger.warn("Authentication auth timeout reached", { authTimeout });
|
|
294
|
+
cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication process exceeded auth time limit of ${authTimeout}ms`));
|
|
295
|
+
}, authTimeout);
|
|
296
|
+
resetIdleTimeout();
|
|
297
|
+
// Use exponential backoff for popup closure checking
|
|
298
|
+
let pollInterval = 1000; // Start with 1 second
|
|
299
|
+
const maxPollInterval = 5000; // Max 5 seconds
|
|
300
|
+
const checkClosed = () => {
|
|
301
|
+
if (authWindow?.closed) {
|
|
302
|
+
Logger.info("Authentication window closed by user");
|
|
137
303
|
cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
|
|
304
|
+
return;
|
|
138
305
|
}
|
|
139
|
-
|
|
306
|
+
// Exponential backoff: increase interval up to max
|
|
307
|
+
pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);
|
|
308
|
+
checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);
|
|
309
|
+
};
|
|
310
|
+
checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);
|
|
140
311
|
try {
|
|
141
|
-
|
|
312
|
+
originalAddEventListener.call(window, "message", listener);
|
|
313
|
+
Logger.debug("Message listener attached");
|
|
142
314
|
}
|
|
143
315
|
catch (error) {
|
|
316
|
+
Logger.error("Failed to attach message listener", {
|
|
317
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
318
|
+
});
|
|
144
319
|
cleanup();
|
|
145
|
-
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " +
|
|
320
|
+
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " +
|
|
321
|
+
(error instanceof Error ? error.message : "Unknown error")));
|
|
146
322
|
return;
|
|
147
323
|
}
|
|
148
|
-
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
class TokenManager {
|
|
152
|
-
constructor(storage = sessionStorage, storageKey = "cams_token") {
|
|
153
|
-
this.storage = storage;
|
|
154
|
-
this.token = null;
|
|
155
|
-
this.storageKey = storageKey;
|
|
156
|
-
}
|
|
157
|
-
setToken(token) {
|
|
158
|
-
const parsed = TokenSchema.parse(token);
|
|
159
|
-
this.token = parsed;
|
|
160
|
-
this.storage.setItem(this.storageKey, JSON.stringify(parsed));
|
|
161
|
-
}
|
|
162
|
-
loadToken() {
|
|
163
|
-
if (this.token)
|
|
164
|
-
return this.token;
|
|
165
|
-
const raw = this.storage.getItem(this.storageKey);
|
|
166
|
-
if (!raw)
|
|
167
|
-
return null;
|
|
324
|
+
// Add focus to the popup for better UX
|
|
168
325
|
try {
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
this.token = TokenSchema.parse(parsed);
|
|
172
|
-
return this.token;
|
|
173
|
-
}
|
|
174
|
-
catch (validationError) {
|
|
175
|
-
console.warn('Token validation failed:', validationError instanceof Error ? validationError.message : 'Unknown error');
|
|
176
|
-
this.storage.removeItem(this.storageKey);
|
|
177
|
-
return null;
|
|
326
|
+
if (authWindow && !authWindow.closed) {
|
|
327
|
+
authWindow.focus();
|
|
178
328
|
}
|
|
179
329
|
}
|
|
180
|
-
catch
|
|
181
|
-
|
|
182
|
-
this.storage.removeItem(this.storageKey);
|
|
183
|
-
return null;
|
|
330
|
+
catch {
|
|
331
|
+
// Ignore focus errors (cross-origin restrictions)
|
|
184
332
|
}
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
class CAMSSessionManager {
|
|
337
|
+
storage;
|
|
338
|
+
keyPrefix;
|
|
339
|
+
events;
|
|
340
|
+
token = null;
|
|
341
|
+
profile = null;
|
|
342
|
+
constructor(storage = null, keyPrefix, events = {}) {
|
|
343
|
+
this.storage = storage || getDefaultStorage();
|
|
344
|
+
this.keyPrefix = keyPrefix ?? "CAMS-SDK";
|
|
345
|
+
this.events = events;
|
|
185
346
|
}
|
|
186
|
-
|
|
187
|
-
this.
|
|
188
|
-
this.storage.removeItem(this.storageKey);
|
|
347
|
+
setItem(key, value) {
|
|
348
|
+
this.storage.setItem(`${this.keyPrefix}:${key}`, value);
|
|
189
349
|
}
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
const token = this.loadToken();
|
|
193
|
-
return (_a = token === null || token === void 0 ? void 0 : token.access_token) !== null && _a !== void 0 ? _a : null;
|
|
350
|
+
getItem(key) {
|
|
351
|
+
return this.storage.getItem(`${this.keyPrefix}:${key}`);
|
|
194
352
|
}
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
if (!token)
|
|
198
|
-
return true;
|
|
199
|
-
// JWT expiration check if available
|
|
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
|
-
const exp = payload.exp * 1000;
|
|
207
|
-
return Date.now() > exp;
|
|
208
|
-
}
|
|
209
|
-
catch (error) {
|
|
210
|
-
console.warn('Failed to parse JWT token:', error instanceof Error ? error.message : 'Unknown error');
|
|
211
|
-
return true;
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
// Fallback: return true for safety when expiration cannot be determined
|
|
215
|
-
return true;
|
|
353
|
+
removeItem(key) {
|
|
354
|
+
this.storage.removeItem(`${this.keyPrefix}:${key}`);
|
|
216
355
|
}
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
356
|
+
clear() {
|
|
357
|
+
// clear only CAMS-prefixed items
|
|
358
|
+
Object.keys(this.storage).forEach((k) => {
|
|
359
|
+
if (k.startsWith(this.keyPrefix)) {
|
|
360
|
+
this.storage.removeItem(k);
|
|
361
|
+
}
|
|
362
|
+
});
|
|
223
363
|
}
|
|
224
364
|
async login(config) {
|
|
225
|
-
var _a, _b, _c, _d, _e, _f, _g;
|
|
226
365
|
try {
|
|
227
|
-
(
|
|
366
|
+
Logger.info("Session login started");
|
|
367
|
+
if (this.events.onAuthStart)
|
|
368
|
+
this.events.onAuthStart();
|
|
228
369
|
let attempts = 0;
|
|
229
|
-
const maxAttempts = (
|
|
370
|
+
const maxAttempts = (config.retryAttempts ?? 0) + 1;
|
|
371
|
+
Logger.debug("Login retry configuration", { maxAttempts });
|
|
230
372
|
while (attempts < maxAttempts) {
|
|
231
373
|
try {
|
|
374
|
+
attempts++;
|
|
375
|
+
Logger.debug("Login attempt", { attempt: attempts, maxAttempts });
|
|
376
|
+
// Add exponential backoff delay for retries
|
|
377
|
+
if (attempts > 1) {
|
|
378
|
+
const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay
|
|
379
|
+
Logger.debug("Retry delay", { delay });
|
|
380
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
381
|
+
}
|
|
232
382
|
const response = await openCAMSPopUpLogin(config);
|
|
233
|
-
(
|
|
383
|
+
Logger.debug("Login Response", response);
|
|
384
|
+
this.profile = response;
|
|
385
|
+
this.setToken(response.userProfile.tokens.Bearer);
|
|
386
|
+
Logger.info("Session login successful");
|
|
387
|
+
if (this.events.onAuthSuccess)
|
|
388
|
+
this.events.onAuthSuccess(response);
|
|
234
389
|
return response;
|
|
235
390
|
}
|
|
236
391
|
catch (error) {
|
|
237
|
-
|
|
392
|
+
Logger.warn("Login attempt failed", {
|
|
393
|
+
attempt: attempts,
|
|
394
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
395
|
+
});
|
|
238
396
|
if (attempts >= maxAttempts || !(error instanceof CAMSError)) {
|
|
239
397
|
throw error;
|
|
240
398
|
}
|
|
@@ -242,82 +400,167 @@
|
|
|
242
400
|
if (![exports.CAMSErrorType.TIMEOUT, exports.CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {
|
|
243
401
|
throw error;
|
|
244
402
|
}
|
|
403
|
+
Logger.info("Retrying login", { nextAttempt: attempts + 1 });
|
|
245
404
|
}
|
|
246
405
|
}
|
|
247
|
-
throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED,
|
|
406
|
+
throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED, "Max retry attempts exceeded");
|
|
248
407
|
}
|
|
249
408
|
catch (error) {
|
|
250
|
-
const
|
|
251
|
-
|
|
252
|
-
|
|
409
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
410
|
+
const camsError = error instanceof CAMSError
|
|
411
|
+
? error
|
|
412
|
+
: new CAMSError(exports.CAMSErrorType.USER_CANCELLED, errorMessage);
|
|
413
|
+
Logger.error("Session login failed", {
|
|
414
|
+
error: camsError.message,
|
|
415
|
+
type: camsError.type,
|
|
416
|
+
});
|
|
417
|
+
if (this.events.onAuthError)
|
|
418
|
+
this.events.onAuthError(camsError);
|
|
253
419
|
throw camsError;
|
|
254
420
|
}
|
|
255
421
|
}
|
|
256
422
|
async logout() {
|
|
257
|
-
|
|
423
|
+
Logger.info("Session logout");
|
|
424
|
+
this.clearToken();
|
|
258
425
|
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
426
|
+
setToken(token) {
|
|
427
|
+
this.token = token;
|
|
428
|
+
this.storage.setItem(this.keyPrefix, token);
|
|
429
|
+
Logger.debug("Token stored", { storageKey: this.keyPrefix });
|
|
430
|
+
}
|
|
431
|
+
getAccessToken() {
|
|
432
|
+
// Return cached token if available, avoiding redundant storage access
|
|
433
|
+
if (this.token)
|
|
434
|
+
return this.token;
|
|
435
|
+
const raw = this.storage.getItem(this.keyPrefix);
|
|
436
|
+
if (!raw)
|
|
437
|
+
return null;
|
|
438
|
+
this.token = raw;
|
|
439
|
+
Logger.debug("Token loaded from storage");
|
|
440
|
+
return this.token;
|
|
441
|
+
}
|
|
442
|
+
clearToken() {
|
|
443
|
+
this.token = null;
|
|
444
|
+
this.storage.removeItem(this.keyPrefix);
|
|
445
|
+
Logger.debug("Token cleared");
|
|
446
|
+
}
|
|
447
|
+
isExpired() {
|
|
448
|
+
const token = this.getAccessToken();
|
|
262
449
|
if (!token)
|
|
263
|
-
return
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
450
|
+
return true;
|
|
451
|
+
try {
|
|
452
|
+
const parts = token.split(".");
|
|
453
|
+
if (parts.length < 3)
|
|
454
|
+
return true; // Invalid JWT format
|
|
455
|
+
const payload = JSON.parse(atob(parts[1]));
|
|
456
|
+
if (typeof payload.exp !== "number")
|
|
457
|
+
return true;
|
|
458
|
+
const exp = payload.exp * 1000;
|
|
459
|
+
return Date.now() > exp;
|
|
460
|
+
}
|
|
461
|
+
catch (error) {
|
|
462
|
+
Logger.warn("Failed to parse JWT token", {
|
|
463
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
464
|
+
});
|
|
465
|
+
return true;
|
|
267
466
|
}
|
|
268
|
-
return true;
|
|
269
467
|
}
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
const token = this.tokenManager.loadToken();
|
|
468
|
+
isPaddedExpired() {
|
|
469
|
+
const token = this.getAccessToken();
|
|
273
470
|
if (!token)
|
|
274
|
-
return
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
471
|
+
return true;
|
|
472
|
+
try {
|
|
473
|
+
const parts = token.split(".");
|
|
474
|
+
if (parts.length < 3)
|
|
475
|
+
return true; // Invalid JWT format
|
|
476
|
+
const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
477
|
+
const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=");
|
|
478
|
+
const payload = JSON.parse(atob(padded));
|
|
479
|
+
if (typeof payload.exp !== "number")
|
|
480
|
+
return true;
|
|
481
|
+
const exp = payload.exp * 1000;
|
|
482
|
+
return Date.now() > exp;
|
|
483
|
+
}
|
|
484
|
+
catch (error) {
|
|
485
|
+
Logger.warn("Failed to parse JWT token", {
|
|
486
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
487
|
+
});
|
|
488
|
+
return true;
|
|
278
489
|
}
|
|
279
|
-
|
|
490
|
+
}
|
|
491
|
+
checkTokenExpiration() {
|
|
492
|
+
if (this.isExpired()) {
|
|
493
|
+
Logger.info("Token expired");
|
|
494
|
+
if (this.events.onTokenExpired)
|
|
495
|
+
this.events.onTokenExpired();
|
|
496
|
+
return true;
|
|
497
|
+
}
|
|
498
|
+
return false;
|
|
499
|
+
}
|
|
500
|
+
isAuthenticated() {
|
|
501
|
+
const token = this.getAccessToken();
|
|
502
|
+
if (!token) {
|
|
503
|
+
Logger.debug("No token found");
|
|
504
|
+
return false;
|
|
505
|
+
}
|
|
506
|
+
if (this.checkTokenExpiration()) {
|
|
507
|
+
return false;
|
|
508
|
+
}
|
|
509
|
+
Logger.debug("Token is valid");
|
|
510
|
+
return true;
|
|
280
511
|
}
|
|
281
512
|
decodeBase64Url(str) {
|
|
282
|
-
//
|
|
283
|
-
|
|
513
|
+
// Work with a copy to avoid mutating input
|
|
514
|
+
let result = str.replace(/-/g, "+").replace(/_/g, "/");
|
|
284
515
|
// Add padding if needed
|
|
285
|
-
while (
|
|
286
|
-
|
|
516
|
+
while (result.length % 4) {
|
|
517
|
+
result += "=";
|
|
287
518
|
}
|
|
288
|
-
return atob(
|
|
519
|
+
return atob(result);
|
|
289
520
|
}
|
|
290
521
|
async getProfile() {
|
|
291
|
-
const storedToken = this.
|
|
292
|
-
if (!
|
|
522
|
+
const storedToken = this.getAccessToken();
|
|
523
|
+
if (!storedToken)
|
|
524
|
+
return null;
|
|
525
|
+
// Check token expiration before processing
|
|
526
|
+
if (this.checkTokenExpiration()) {
|
|
293
527
|
return null;
|
|
294
|
-
try {
|
|
295
|
-
const parts = storedToken.id_token.split('.');
|
|
296
|
-
if (parts.length >= 3) { // JWT has header.payload.signature format
|
|
297
|
-
try {
|
|
298
|
-
const payload = JSON.parse(this.decodeBase64Url(parts[1]));
|
|
299
|
-
return ProfileSchema.parse(payload);
|
|
300
|
-
}
|
|
301
|
-
catch (decodeError) {
|
|
302
|
-
console.warn('Failed to decode JWT payload:', decodeError instanceof Error ? decodeError.message : 'Unknown error');
|
|
303
|
-
}
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
catch (error) {
|
|
307
|
-
console.warn('Failed to extract profile from token:', error instanceof Error ? error.message : 'Unknown error');
|
|
308
528
|
}
|
|
529
|
+
return this.profile;
|
|
530
|
+
}
|
|
531
|
+
getSessionError() {
|
|
309
532
|
return null;
|
|
310
533
|
}
|
|
311
534
|
}
|
|
535
|
+
// 🔹 Safe fallback for Node/SSR
|
|
536
|
+
function getDefaultStorage() {
|
|
537
|
+
if (typeof window !== "undefined" && window.localStorage) {
|
|
538
|
+
return window.localStorage;
|
|
539
|
+
}
|
|
540
|
+
const memoryStore = {};
|
|
541
|
+
return {
|
|
542
|
+
getItem: (key) => (key in memoryStore ? memoryStore[key] : null),
|
|
543
|
+
setItem: (key, value) => {
|
|
544
|
+
memoryStore[key] = value;
|
|
545
|
+
},
|
|
546
|
+
removeItem: (key) => {
|
|
547
|
+
delete memoryStore[key];
|
|
548
|
+
},
|
|
549
|
+
key: (i) => Object.keys(memoryStore)[i] ?? null,
|
|
550
|
+
get length() {
|
|
551
|
+
return Object.keys(memoryStore).length;
|
|
552
|
+
},
|
|
553
|
+
};
|
|
554
|
+
}
|
|
312
555
|
|
|
556
|
+
exports.AuthFailureMessageSchema = AuthFailureMessageSchema;
|
|
313
557
|
exports.CAMSError = CAMSError;
|
|
314
|
-
exports.
|
|
558
|
+
exports.CAMSSessionManager = CAMSSessionManager;
|
|
315
559
|
exports.ErrorMessageSchema = ErrorMessageSchema;
|
|
560
|
+
exports.Logger = Logger;
|
|
316
561
|
exports.ProfileSchema = ProfileSchema;
|
|
317
|
-
exports.TokenManager = TokenManager;
|
|
318
|
-
exports.TokenMessageSchema = TokenMessageSchema;
|
|
319
|
-
exports.TokenSchema = TokenSchema;
|
|
320
562
|
exports.URLSchema = URLSchema;
|
|
563
|
+
exports.generateSecureWindowName = generateSecureWindowName;
|
|
321
564
|
exports.openCAMSPopUpLogin = openCAMSPopUpLogin;
|
|
322
565
|
exports.validateConfig = validateConfig;
|
|
323
566
|
|