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