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