@nibssplc/cams-sdk 0.0.1-beta.2 → 0.0.1-beta.21
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 +107 -18
- package/dist/auth.d.ts +1 -1
- package/dist/index.cjs.js +418 -159
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.esm.js +416 -158
- package/dist/index.esm.js.map +1 -1
- package/dist/index.umd.js +418 -159
- package/dist/index.umd.js.map +1 -1
- package/dist/logger.d.ts +20 -0
- package/dist/sessionManager.d.ts +37 -0
- package/dist/types.d.ts +6 -4
- package/dist/validators.d.ts +13 -2
- package/package.json +13 -4
- package/dist/session.d.ts +0 -19
- package/dist/tokenManager.d.ts +0 -12
package/dist/index.umd.js
CHANGED
|
@@ -12,21 +12,33 @@
|
|
|
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"] = "API_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 -
|
|
26
|
+
// Validate the returned token - non-empty string
|
|
25
27
|
const TokenMessageSchema = zod.z.object({
|
|
26
|
-
|
|
28
|
+
type: zod.z.literal("AUTH_SUCCESS"),
|
|
29
|
+
accessToken: zod.z.string().min(1, "Access token cannot be empty"),
|
|
30
|
+
user: zod.z.object({
|
|
31
|
+
name: zod.z.string(),
|
|
32
|
+
image: zod.z.string().nullable(),
|
|
33
|
+
}).optional(),
|
|
27
34
|
});
|
|
28
35
|
const ErrorMessageSchema = zod.z.object({
|
|
29
|
-
error: zod.z.string(),
|
|
36
|
+
error: zod.z.string().min(1, "Error message cannot be empty"),
|
|
37
|
+
});
|
|
38
|
+
const AuthFailureMessageSchema = zod.z.object({
|
|
39
|
+
type: zod.z.literal("AUTH_FAILURE"),
|
|
40
|
+
error: zod.z.string().min(1, "Error message cannot be empty"),
|
|
41
|
+
errorCode: zod.z.string().optional(),
|
|
30
42
|
});
|
|
31
43
|
const TokenSchema = zod.z.object({
|
|
32
44
|
access_token: zod.z.string(),
|
|
@@ -43,198 +55,340 @@
|
|
|
43
55
|
family_name: zod.z.string().optional(),
|
|
44
56
|
roles: zod.z.array(zod.z.string()).optional(),
|
|
45
57
|
});
|
|
46
|
-
|
|
47
|
-
const URLSchema = zod.z.string().url().refine((url) => url.startsWith('https://'), { message: "Only HTTPS URLs are allowed" });
|
|
58
|
+
const URLSchema = zod.z.url();
|
|
48
59
|
|
|
60
|
+
exports.LogLevel = void 0;
|
|
61
|
+
(function (LogLevel) {
|
|
62
|
+
LogLevel[LogLevel["ERROR"] = 0] = "ERROR";
|
|
63
|
+
LogLevel[LogLevel["WARN"] = 1] = "WARN";
|
|
64
|
+
LogLevel[LogLevel["INFO"] = 2] = "INFO";
|
|
65
|
+
LogLevel[LogLevel["DEBUG"] = 3] = "DEBUG";
|
|
66
|
+
})(exports.LogLevel || (exports.LogLevel = {}));
|
|
67
|
+
class Logger {
|
|
68
|
+
static level = exports.LogLevel.WARN;
|
|
69
|
+
static prefix = '[CAMS-SDK]';
|
|
70
|
+
static isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';
|
|
71
|
+
static setLevel(level) {
|
|
72
|
+
Logger.level = level;
|
|
73
|
+
}
|
|
74
|
+
static sanitizeForLog(input) {
|
|
75
|
+
if (typeof input === 'string') {
|
|
76
|
+
// Remove newlines and control characters to prevent log injection
|
|
77
|
+
return input.replace(/[\r\n\t]/g, ' ').replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '');
|
|
78
|
+
}
|
|
79
|
+
if (typeof input === 'object' && input !== null) {
|
|
80
|
+
const sanitized = {};
|
|
81
|
+
for (const [key, value] of Object.entries(input)) {
|
|
82
|
+
sanitized[Logger.sanitizeForLog(key)] = Logger.sanitizeForLog(value);
|
|
83
|
+
}
|
|
84
|
+
return sanitized;
|
|
85
|
+
}
|
|
86
|
+
return input;
|
|
87
|
+
}
|
|
88
|
+
static error(message, context) {
|
|
89
|
+
if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.ERROR) {
|
|
90
|
+
console.error(`${Logger.prefix} ERROR:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
static warn(message, context) {
|
|
94
|
+
if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.WARN) {
|
|
95
|
+
console.warn(`${Logger.prefix} WARN:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
static info(message, context) {
|
|
99
|
+
if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.INFO) {
|
|
100
|
+
console.info(`${Logger.prefix} INFO:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
static debug(message, context) {
|
|
104
|
+
if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.DEBUG) {
|
|
105
|
+
console.debug(`${Logger.prefix} DEBUG:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Capture original functions to prevent tampering
|
|
111
|
+
const originalWindowOpen = window.open;
|
|
112
|
+
const originalAddEventListener = window.addEventListener;
|
|
113
|
+
const originalRemoveEventListener = window.removeEventListener;
|
|
114
|
+
const originalSetTimeout = window.setTimeout;
|
|
115
|
+
const originalClearTimeout = window.clearTimeout;
|
|
116
|
+
// Generate random window name to prevent targeting
|
|
117
|
+
const generateSecureWindowName = () => `cams_auth_${Math.random().toString(36).substr(2, 9)}_${Date.now()}`;
|
|
49
118
|
function validateConfig(config) {
|
|
50
|
-
|
|
51
|
-
// Validate URL format
|
|
119
|
+
// Validate URL format and parse once
|
|
52
120
|
const urlValidation = URLSchema.safeParse(config.camsUrl);
|
|
53
121
|
if (!urlValidation.success) {
|
|
54
|
-
throw new CAMSError(exports.CAMSErrorType.INVALID_URL,
|
|
122
|
+
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Invalid CAMS URL format");
|
|
55
123
|
}
|
|
56
124
|
// 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');
|
|
125
|
+
if (!config.messageOrigin) {
|
|
126
|
+
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Message Origin must be specified for security");
|
|
64
127
|
}
|
|
128
|
+
const url = new URL(config.camsUrl);
|
|
129
|
+
return url;
|
|
65
130
|
}
|
|
66
131
|
function openCAMSPopUpLogin(config) {
|
|
67
132
|
return new Promise((resolve, reject) => {
|
|
133
|
+
if (config.debug)
|
|
134
|
+
Logger.setLevel(exports.LogLevel.DEBUG);
|
|
135
|
+
Logger.info("Starting CAMS authentication", { url: config.camsUrl });
|
|
136
|
+
let validatedUrl;
|
|
68
137
|
try {
|
|
69
|
-
validateConfig(config);
|
|
138
|
+
validatedUrl = validateConfig(config);
|
|
139
|
+
Logger.debug("Config validation passed");
|
|
70
140
|
}
|
|
71
141
|
catch (error) {
|
|
142
|
+
Logger.error("Config validation failed", {
|
|
143
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
144
|
+
});
|
|
72
145
|
reject(error);
|
|
73
146
|
return;
|
|
74
147
|
}
|
|
75
|
-
const {
|
|
148
|
+
const { messageOrigin, windowHeight, windowWidth, authTimeout = 300000, // 5 minutes as a final failsafe
|
|
149
|
+
idleTimeout = 120000, // 2 minutes of inactivity
|
|
150
|
+
} = config;
|
|
76
151
|
let authWindow;
|
|
77
|
-
let
|
|
152
|
+
let authTimeoutId = null;
|
|
153
|
+
let idleTimeoutId = null;
|
|
78
154
|
let checkClosedInterval = null;
|
|
79
155
|
try {
|
|
80
|
-
|
|
156
|
+
Logger.debug("Opening popup window", {
|
|
157
|
+
width: windowWidth,
|
|
158
|
+
height: windowHeight,
|
|
159
|
+
});
|
|
160
|
+
// Center the popup window
|
|
161
|
+
const left = (window.screen.width - windowWidth) / 2;
|
|
162
|
+
const top = (window.screen.height - windowHeight) / 2;
|
|
163
|
+
const secureWindowName = generateSecureWindowName();
|
|
164
|
+
authWindow = originalWindowOpen.call(window, validatedUrl.toString(), secureWindowName, `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes,noopener=yes,noreferrer=yes`);
|
|
81
165
|
}
|
|
82
166
|
catch (error) {
|
|
83
|
-
|
|
167
|
+
Logger.error("Failed to open popup window", {
|
|
168
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
169
|
+
});
|
|
170
|
+
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window: " +
|
|
171
|
+
(error instanceof Error ? error.message : "Unknown error")));
|
|
84
172
|
return;
|
|
85
173
|
}
|
|
86
174
|
if (!authWindow) {
|
|
175
|
+
Logger.error("Popup window blocked");
|
|
87
176
|
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window. Please allow popups."));
|
|
88
177
|
return;
|
|
89
178
|
}
|
|
179
|
+
Logger.debug("Popup window opened successfully");
|
|
90
180
|
const cleanup = () => {
|
|
91
|
-
|
|
92
|
-
if (
|
|
93
|
-
|
|
181
|
+
originalRemoveEventListener.call(window, "message", listener);
|
|
182
|
+
if (idleTimeoutId)
|
|
183
|
+
originalClearTimeout(idleTimeoutId);
|
|
184
|
+
if (authTimeoutId)
|
|
185
|
+
originalClearTimeout(authTimeoutId);
|
|
94
186
|
if (checkClosedInterval)
|
|
95
|
-
|
|
187
|
+
originalClearTimeout(checkClosedInterval);
|
|
188
|
+
idleTimeoutId = null;
|
|
189
|
+
authTimeoutId = null;
|
|
190
|
+
checkClosedInterval = null;
|
|
96
191
|
};
|
|
97
|
-
const
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
192
|
+
const listener = (event) => {
|
|
193
|
+
const messageEvent = event;
|
|
194
|
+
Logger.debug("Received message", {
|
|
195
|
+
origin: messageEvent.origin,
|
|
196
|
+
expectedOrigin: messageOrigin,
|
|
197
|
+
data: messageEvent.data,
|
|
198
|
+
});
|
|
199
|
+
const originUrl = new URL(messageEvent.origin);
|
|
200
|
+
const expectedHostname = messageOrigin.startsWith('http')
|
|
201
|
+
? new URL(messageOrigin).hostname
|
|
202
|
+
: messageOrigin;
|
|
203
|
+
// Allow Microsoft redirect domains for Azure AD authentication
|
|
204
|
+
const isMicrosoftDomain = originUrl.hostname.endsWith('.microsoft.com') ||
|
|
205
|
+
originUrl.hostname.endsWith('.microsoftonline.com') ||
|
|
206
|
+
originUrl.hostname.endsWith('.live.com');
|
|
207
|
+
const isAllowedOrigin = originUrl.hostname === expectedHostname ||
|
|
208
|
+
originUrl.hostname.endsWith("." + expectedHostname) ||
|
|
209
|
+
isMicrosoftDomain;
|
|
210
|
+
if (!isAllowedOrigin) {
|
|
211
|
+
Logger.warn("Blocked message from unauthorized origin", {
|
|
212
|
+
origin: messageEvent.origin,
|
|
213
|
+
expected: messageOrigin,
|
|
214
|
+
data: messageEvent.data,
|
|
215
|
+
});
|
|
216
|
+
return;
|
|
103
217
|
}
|
|
104
|
-
|
|
105
|
-
|
|
218
|
+
// Validate event source
|
|
219
|
+
if (messageEvent.source !== authWindow) {
|
|
220
|
+
Logger.warn("Message from unexpected source", { source: messageEvent.source });
|
|
221
|
+
return;
|
|
106
222
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
if (event.origin !== allowedOrigin) {
|
|
112
|
-
// Sanitize origin for logging to prevent log injection
|
|
113
|
-
const sanitizedOrigin = event.origin.replace(/[\r\n]/g, '');
|
|
114
|
-
console.warn("Blocked message from origin:", sanitizedOrigin);
|
|
223
|
+
// Ignore heartbeat messages
|
|
224
|
+
if (messageEvent.data?.type === 'heartbeat') {
|
|
225
|
+
Logger.debug("Received heartbeat message");
|
|
226
|
+
resetIdleTimeout();
|
|
115
227
|
return;
|
|
116
228
|
}
|
|
117
229
|
// ✅ Validate payload
|
|
118
|
-
const tokenMsg = TokenMessageSchema.safeParse(
|
|
230
|
+
const tokenMsg = TokenMessageSchema.safeParse(messageEvent.data);
|
|
119
231
|
if (tokenMsg.success) {
|
|
232
|
+
Logger.info("Authentication successful");
|
|
120
233
|
cleanupAndClose();
|
|
121
|
-
resolve({ token: tokenMsg.data.
|
|
234
|
+
resolve({ token: tokenMsg.data.accessToken });
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
const authFailureMsg = AuthFailureMessageSchema.safeParse(messageEvent.data);
|
|
238
|
+
if (authFailureMsg.success) {
|
|
239
|
+
Logger.warn("Authentication failure received", {
|
|
240
|
+
error: authFailureMsg.data.error,
|
|
241
|
+
errorCode: authFailureMsg.data.errorCode,
|
|
242
|
+
});
|
|
243
|
+
cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication failed: " + authFailureMsg.data.error));
|
|
122
244
|
return;
|
|
123
245
|
}
|
|
124
|
-
const errorMsg = ErrorMessageSchema.safeParse(
|
|
246
|
+
const errorMsg = ErrorMessageSchema.safeParse(messageEvent.data);
|
|
125
247
|
if (errorMsg.success) {
|
|
248
|
+
Logger.warn("Authentication error received", {
|
|
249
|
+
error: errorMsg.data.error,
|
|
250
|
+
});
|
|
126
251
|
cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication failed: " + errorMsg.data.error));
|
|
127
252
|
return;
|
|
128
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
|
+
});
|
|
129
264
|
cleanupAndClose(new CAMSError(exports.CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
|
|
130
265
|
};
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
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");
|
|
137
301
|
cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
|
|
302
|
+
return;
|
|
138
303
|
}
|
|
139
|
-
|
|
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);
|
|
140
309
|
try {
|
|
141
|
-
|
|
310
|
+
originalAddEventListener.call(window, "message", listener);
|
|
311
|
+
Logger.debug("Message listener attached");
|
|
142
312
|
}
|
|
143
313
|
catch (error) {
|
|
314
|
+
Logger.error("Failed to attach message listener", {
|
|
315
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
316
|
+
});
|
|
144
317
|
cleanup();
|
|
145
|
-
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")));
|
|
146
320
|
return;
|
|
147
321
|
}
|
|
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;
|
|
322
|
+
// Add focus to the popup for better UX
|
|
168
323
|
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;
|
|
324
|
+
if (authWindow) {
|
|
325
|
+
authWindow.focus();
|
|
178
326
|
}
|
|
179
327
|
}
|
|
180
|
-
catch
|
|
181
|
-
|
|
182
|
-
this.storage.removeItem(this.storageKey);
|
|
183
|
-
return null;
|
|
328
|
+
catch {
|
|
329
|
+
// Ignore focus errors (cross-origin restrictions)
|
|
184
330
|
}
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
class CAMSSessionManager {
|
|
335
|
+
storage;
|
|
336
|
+
keyPrefix;
|
|
337
|
+
events;
|
|
338
|
+
token = null;
|
|
339
|
+
constructor(storage = null, keyPrefix, events = {}) {
|
|
340
|
+
this.storage = storage || getDefaultStorage();
|
|
341
|
+
this.keyPrefix = keyPrefix ?? "CAMS-SDK";
|
|
342
|
+
this.events = events;
|
|
185
343
|
}
|
|
186
|
-
|
|
187
|
-
this.
|
|
188
|
-
this.storage.removeItem(this.storageKey);
|
|
344
|
+
setItem(key, value) {
|
|
345
|
+
this.storage.setItem(`${this.keyPrefix}:${key}`, value);
|
|
189
346
|
}
|
|
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;
|
|
347
|
+
getItem(key) {
|
|
348
|
+
return this.storage.getItem(`${this.keyPrefix}:${key}`);
|
|
194
349
|
}
|
|
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;
|
|
350
|
+
removeItem(key) {
|
|
351
|
+
this.storage.removeItem(`${this.keyPrefix}:${key}`);
|
|
216
352
|
}
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
353
|
+
clear() {
|
|
354
|
+
// clear only CAMS-prefixed items
|
|
355
|
+
Object.keys(this.storage).forEach((k) => {
|
|
356
|
+
if (k.startsWith(this.keyPrefix)) {
|
|
357
|
+
this.storage.removeItem(k);
|
|
358
|
+
}
|
|
359
|
+
});
|
|
223
360
|
}
|
|
224
361
|
async login(config) {
|
|
225
|
-
var _a, _b, _c, _d, _e, _f, _g;
|
|
226
362
|
try {
|
|
227
|
-
(
|
|
363
|
+
Logger.info("Session login started");
|
|
364
|
+
if (this.events.onAuthStart)
|
|
365
|
+
this.events.onAuthStart();
|
|
228
366
|
let attempts = 0;
|
|
229
|
-
const maxAttempts = (
|
|
367
|
+
const maxAttempts = (config.retryAttempts ?? 0) + 1;
|
|
368
|
+
Logger.debug("Login retry configuration", { maxAttempts });
|
|
230
369
|
while (attempts < maxAttempts) {
|
|
231
370
|
try {
|
|
371
|
+
attempts++;
|
|
372
|
+
Logger.debug("Login attempt", { attempt: attempts, maxAttempts });
|
|
373
|
+
// Add exponential backoff delay for retries
|
|
374
|
+
if (attempts > 1) {
|
|
375
|
+
const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay
|
|
376
|
+
Logger.debug("Retry delay", { delay });
|
|
377
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
378
|
+
}
|
|
232
379
|
const response = await openCAMSPopUpLogin(config);
|
|
233
|
-
(
|
|
380
|
+
Logger.debug("Login Response", response);
|
|
381
|
+
this.setToken(response.token);
|
|
382
|
+
Logger.info("Session login successful");
|
|
383
|
+
if (this.events.onAuthSuccess)
|
|
384
|
+
this.events.onAuthSuccess(response);
|
|
234
385
|
return response;
|
|
235
386
|
}
|
|
236
387
|
catch (error) {
|
|
237
|
-
|
|
388
|
+
Logger.warn("Login attempt failed", {
|
|
389
|
+
attempt: attempts,
|
|
390
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
391
|
+
});
|
|
238
392
|
if (attempts >= maxAttempts || !(error instanceof CAMSError)) {
|
|
239
393
|
throw error;
|
|
240
394
|
}
|
|
@@ -242,79 +396,184 @@
|
|
|
242
396
|
if (![exports.CAMSErrorType.TIMEOUT, exports.CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {
|
|
243
397
|
throw error;
|
|
244
398
|
}
|
|
399
|
+
Logger.info("Retrying login", { nextAttempt: attempts + 1 });
|
|
245
400
|
}
|
|
246
401
|
}
|
|
247
|
-
throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED,
|
|
402
|
+
throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED, "Max retry attempts exceeded");
|
|
248
403
|
}
|
|
249
404
|
catch (error) {
|
|
250
|
-
const
|
|
251
|
-
|
|
252
|
-
|
|
405
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
406
|
+
const camsError = error instanceof CAMSError
|
|
407
|
+
? error
|
|
408
|
+
: new CAMSError(exports.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);
|
|
253
415
|
throw camsError;
|
|
254
416
|
}
|
|
255
417
|
}
|
|
256
418
|
async logout() {
|
|
257
|
-
|
|
419
|
+
Logger.info("Session logout");
|
|
420
|
+
this.clearToken();
|
|
258
421
|
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
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();
|
|
262
445
|
if (!token)
|
|
263
|
-
return
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
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;
|
|
267
462
|
}
|
|
268
|
-
return true;
|
|
269
463
|
}
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
const token = this.tokenManager.loadToken();
|
|
464
|
+
isPaddedExpired() {
|
|
465
|
+
const token = this.getAccessToken();
|
|
273
466
|
if (!token)
|
|
274
|
-
return
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
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;
|
|
278
479
|
}
|
|
279
|
-
|
|
480
|
+
catch (error) {
|
|
481
|
+
Logger.warn("Failed to parse JWT token", {
|
|
482
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
483
|
+
});
|
|
484
|
+
return true;
|
|
485
|
+
}
|
|
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;
|
|
280
507
|
}
|
|
281
508
|
decodeBase64Url(str) {
|
|
282
|
-
//
|
|
283
|
-
|
|
509
|
+
// Work with a copy to avoid mutating input
|
|
510
|
+
let result = str.replace(/-/g, "+").replace(/_/g, "/");
|
|
284
511
|
// Add padding if needed
|
|
285
|
-
while (
|
|
286
|
-
|
|
512
|
+
while (result.length % 4) {
|
|
513
|
+
result += "=";
|
|
287
514
|
}
|
|
288
|
-
return atob(
|
|
515
|
+
return atob(result);
|
|
289
516
|
}
|
|
290
517
|
async getProfile() {
|
|
291
|
-
const storedToken = this.
|
|
292
|
-
if (!
|
|
518
|
+
const storedToken = this.getAccessToken();
|
|
519
|
+
if (!storedToken)
|
|
293
520
|
return null;
|
|
521
|
+
// Check token expiration before processing
|
|
522
|
+
if (this.checkTokenExpiration()) {
|
|
523
|
+
return null;
|
|
524
|
+
}
|
|
294
525
|
try {
|
|
295
|
-
const parts = storedToken.
|
|
296
|
-
if (parts.length >= 3) {
|
|
526
|
+
const parts = storedToken.split(".");
|
|
527
|
+
if (parts.length >= 3) {
|
|
528
|
+
// JWT has header.payload.signature format
|
|
297
529
|
try {
|
|
298
530
|
const payload = JSON.parse(this.decodeBase64Url(parts[1]));
|
|
299
531
|
return ProfileSchema.parse(payload);
|
|
300
532
|
}
|
|
301
533
|
catch (decodeError) {
|
|
302
|
-
|
|
534
|
+
Logger.warn("Failed to decode JWT payload", {
|
|
535
|
+
error: decodeError instanceof Error
|
|
536
|
+
? decodeError.message
|
|
537
|
+
: "Unknown error",
|
|
538
|
+
});
|
|
303
539
|
}
|
|
304
540
|
}
|
|
305
541
|
}
|
|
306
542
|
catch (error) {
|
|
307
|
-
|
|
543
|
+
Logger.warn("Failed to extract profile from token", {
|
|
544
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
545
|
+
});
|
|
308
546
|
}
|
|
309
547
|
return null;
|
|
310
548
|
}
|
|
311
549
|
}
|
|
550
|
+
// 🔹 Safe fallback for Node/SSR
|
|
551
|
+
function getDefaultStorage() {
|
|
552
|
+
if (typeof window !== "undefined" && window.localStorage) {
|
|
553
|
+
return window.localStorage;
|
|
554
|
+
}
|
|
555
|
+
const memoryStore = {};
|
|
556
|
+
return {
|
|
557
|
+
getItem: (key) => (key in memoryStore ? memoryStore[key] : null),
|
|
558
|
+
setItem: (key, value) => {
|
|
559
|
+
memoryStore[key] = value;
|
|
560
|
+
},
|
|
561
|
+
removeItem: (key) => {
|
|
562
|
+
delete memoryStore[key];
|
|
563
|
+
},
|
|
564
|
+
key: (i) => Object.keys(memoryStore)[i] ?? null,
|
|
565
|
+
get length() {
|
|
566
|
+
return Object.keys(memoryStore).length;
|
|
567
|
+
},
|
|
568
|
+
};
|
|
569
|
+
}
|
|
312
570
|
|
|
571
|
+
exports.AuthFailureMessageSchema = AuthFailureMessageSchema;
|
|
313
572
|
exports.CAMSError = CAMSError;
|
|
314
|
-
exports.
|
|
573
|
+
exports.CAMSSessionManager = CAMSSessionManager;
|
|
315
574
|
exports.ErrorMessageSchema = ErrorMessageSchema;
|
|
575
|
+
exports.Logger = Logger;
|
|
316
576
|
exports.ProfileSchema = ProfileSchema;
|
|
317
|
-
exports.TokenManager = TokenManager;
|
|
318
577
|
exports.TokenMessageSchema = TokenMessageSchema;
|
|
319
578
|
exports.TokenSchema = TokenSchema;
|
|
320
579
|
exports.URLSchema = URLSchema;
|