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