@nibssplc/cams-sdk 0.0.1-beta.2 → 0.0.1-beta.20
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 +413 -159
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.esm.js +411 -158
- package/dist/index.esm.js.map +1 -1
- package/dist/index.umd.js +413 -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,335 @@ 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
|
+
const isAllowedOrigin = originUrl.hostname === expectedHostname ||
|
|
202
|
+
originUrl.hostname.endsWith("." + expectedHostname);
|
|
203
|
+
if (!isAllowedOrigin) {
|
|
204
|
+
Logger.warn("Blocked message from unauthorized origin", {
|
|
205
|
+
origin: messageEvent.origin,
|
|
206
|
+
expected: messageOrigin,
|
|
207
|
+
data: messageEvent.data,
|
|
208
|
+
});
|
|
209
|
+
return;
|
|
101
210
|
}
|
|
102
|
-
|
|
103
|
-
|
|
211
|
+
// Validate event source
|
|
212
|
+
if (messageEvent.source !== authWindow) {
|
|
213
|
+
Logger.warn("Message from unexpected source", { source: messageEvent.source });
|
|
214
|
+
return;
|
|
104
215
|
}
|
|
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);
|
|
216
|
+
// Ignore heartbeat messages
|
|
217
|
+
if (messageEvent.data?.type === 'heartbeat') {
|
|
218
|
+
Logger.debug("Received heartbeat message");
|
|
219
|
+
resetIdleTimeout();
|
|
113
220
|
return;
|
|
114
221
|
}
|
|
115
222
|
// ✅ Validate payload
|
|
116
|
-
const tokenMsg = TokenMessageSchema.safeParse(
|
|
223
|
+
const tokenMsg = TokenMessageSchema.safeParse(messageEvent.data);
|
|
117
224
|
if (tokenMsg.success) {
|
|
225
|
+
Logger.info("Authentication successful");
|
|
118
226
|
cleanupAndClose();
|
|
119
|
-
resolve({ token: tokenMsg.data.
|
|
227
|
+
resolve({ token: tokenMsg.data.accessToken });
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
const authFailureMsg = AuthFailureMessageSchema.safeParse(messageEvent.data);
|
|
231
|
+
if (authFailureMsg.success) {
|
|
232
|
+
Logger.warn("Authentication failure received", {
|
|
233
|
+
error: authFailureMsg.data.error,
|
|
234
|
+
errorCode: authFailureMsg.data.errorCode,
|
|
235
|
+
});
|
|
236
|
+
cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication failed: " + authFailureMsg.data.error));
|
|
120
237
|
return;
|
|
121
238
|
}
|
|
122
|
-
const errorMsg = ErrorMessageSchema.safeParse(
|
|
239
|
+
const errorMsg = ErrorMessageSchema.safeParse(messageEvent.data);
|
|
123
240
|
if (errorMsg.success) {
|
|
241
|
+
Logger.warn("Authentication error received", {
|
|
242
|
+
error: errorMsg.data.error,
|
|
243
|
+
});
|
|
124
244
|
cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication failed: " + errorMsg.data.error));
|
|
125
245
|
return;
|
|
126
246
|
}
|
|
247
|
+
Logger.error("Invalid message format received", {
|
|
248
|
+
messageData: messageEvent.data,
|
|
249
|
+
dataType: typeof messageEvent.data,
|
|
250
|
+
tokenValidationError: tokenMsg.error
|
|
251
|
+
? tokenMsg.error.issues
|
|
252
|
+
: undefined,
|
|
253
|
+
errorValidationError: errorMsg.error
|
|
254
|
+
? errorMsg.error.issues
|
|
255
|
+
: undefined,
|
|
256
|
+
});
|
|
127
257
|
cleanupAndClose(new CAMSError(exports.CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
|
|
128
258
|
};
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
259
|
+
const cleanupAndClose = (error) => {
|
|
260
|
+
cleanup();
|
|
261
|
+
try {
|
|
262
|
+
if (authWindow && !authWindow.closed) {
|
|
263
|
+
authWindow.close();
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
// Ignore close errors
|
|
268
|
+
}
|
|
269
|
+
if (error)
|
|
270
|
+
reject(error);
|
|
271
|
+
};
|
|
272
|
+
const resetIdleTimeout = () => {
|
|
273
|
+
// Timeout handler
|
|
274
|
+
if (idleTimeoutId)
|
|
275
|
+
originalClearTimeout(idleTimeoutId);
|
|
276
|
+
Logger.debug("Resetting idle timeout", { idleTimeout });
|
|
277
|
+
idleTimeoutId = originalSetTimeout(() => {
|
|
278
|
+
Logger.warn("Authentication idle timeout reached", { idleTimeout });
|
|
279
|
+
cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timed out due to inactivity after ${idleTimeout}ms`));
|
|
280
|
+
}, idleTimeout);
|
|
281
|
+
};
|
|
282
|
+
Logger.debug("Setting auth timeout", { authTimeout });
|
|
283
|
+
authTimeoutId = originalSetTimeout(() => {
|
|
284
|
+
Logger.warn("Authentication auth timeout reached", { authTimeout });
|
|
285
|
+
cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication process exceeded auth time limit of ${authTimeout}ms`));
|
|
286
|
+
}, authTimeout);
|
|
287
|
+
resetIdleTimeout();
|
|
288
|
+
// Use exponential backoff for popup closure checking
|
|
289
|
+
let pollInterval = 1000; // Start with 1 second
|
|
290
|
+
const maxPollInterval = 5000; // Max 5 seconds
|
|
291
|
+
const checkClosed = () => {
|
|
292
|
+
if (authWindow?.closed) {
|
|
293
|
+
Logger.info("Authentication window closed by user");
|
|
135
294
|
cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
|
|
295
|
+
return;
|
|
136
296
|
}
|
|
137
|
-
|
|
297
|
+
// Exponential backoff: increase interval up to max
|
|
298
|
+
pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);
|
|
299
|
+
checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);
|
|
300
|
+
};
|
|
301
|
+
checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);
|
|
138
302
|
try {
|
|
139
|
-
|
|
303
|
+
originalAddEventListener.call(window, "message", listener);
|
|
304
|
+
Logger.debug("Message listener attached");
|
|
140
305
|
}
|
|
141
306
|
catch (error) {
|
|
307
|
+
Logger.error("Failed to attach message listener", {
|
|
308
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
309
|
+
});
|
|
142
310
|
cleanup();
|
|
143
|
-
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " +
|
|
311
|
+
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " +
|
|
312
|
+
(error instanceof Error ? error.message : "Unknown error")));
|
|
144
313
|
return;
|
|
145
314
|
}
|
|
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;
|
|
315
|
+
// Add focus to the popup for better UX
|
|
166
316
|
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;
|
|
317
|
+
if (authWindow) {
|
|
318
|
+
authWindow.focus();
|
|
176
319
|
}
|
|
177
320
|
}
|
|
178
|
-
catch
|
|
179
|
-
|
|
180
|
-
this.storage.removeItem(this.storageKey);
|
|
181
|
-
return null;
|
|
321
|
+
catch {
|
|
322
|
+
// Ignore focus errors (cross-origin restrictions)
|
|
182
323
|
}
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
class CAMSSessionManager {
|
|
328
|
+
storage;
|
|
329
|
+
keyPrefix;
|
|
330
|
+
events;
|
|
331
|
+
token = null;
|
|
332
|
+
constructor(storage = null, keyPrefix, events = {}) {
|
|
333
|
+
this.storage = storage || getDefaultStorage();
|
|
334
|
+
this.keyPrefix = keyPrefix ?? "CAMS-SDK";
|
|
335
|
+
this.events = events;
|
|
183
336
|
}
|
|
184
|
-
|
|
185
|
-
this.
|
|
186
|
-
this.storage.removeItem(this.storageKey);
|
|
337
|
+
setItem(key, value) {
|
|
338
|
+
this.storage.setItem(`${this.keyPrefix}:${key}`, value);
|
|
187
339
|
}
|
|
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;
|
|
340
|
+
getItem(key) {
|
|
341
|
+
return this.storage.getItem(`${this.keyPrefix}:${key}`);
|
|
192
342
|
}
|
|
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;
|
|
343
|
+
removeItem(key) {
|
|
344
|
+
this.storage.removeItem(`${this.keyPrefix}:${key}`);
|
|
214
345
|
}
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
346
|
+
clear() {
|
|
347
|
+
// clear only CAMS-prefixed items
|
|
348
|
+
Object.keys(this.storage).forEach((k) => {
|
|
349
|
+
if (k.startsWith(this.keyPrefix)) {
|
|
350
|
+
this.storage.removeItem(k);
|
|
351
|
+
}
|
|
352
|
+
});
|
|
221
353
|
}
|
|
222
354
|
async login(config) {
|
|
223
|
-
var _a, _b, _c, _d, _e, _f, _g;
|
|
224
355
|
try {
|
|
225
|
-
(
|
|
356
|
+
Logger.info("Session login started");
|
|
357
|
+
if (this.events.onAuthStart)
|
|
358
|
+
this.events.onAuthStart();
|
|
226
359
|
let attempts = 0;
|
|
227
|
-
const maxAttempts = (
|
|
360
|
+
const maxAttempts = (config.retryAttempts ?? 0) + 1;
|
|
361
|
+
Logger.debug("Login retry configuration", { maxAttempts });
|
|
228
362
|
while (attempts < maxAttempts) {
|
|
229
363
|
try {
|
|
364
|
+
attempts++;
|
|
365
|
+
Logger.debug("Login attempt", { attempt: attempts, maxAttempts });
|
|
366
|
+
// Add exponential backoff delay for retries
|
|
367
|
+
if (attempts > 1) {
|
|
368
|
+
const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay
|
|
369
|
+
Logger.debug("Retry delay", { delay });
|
|
370
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
371
|
+
}
|
|
230
372
|
const response = await openCAMSPopUpLogin(config);
|
|
231
|
-
(
|
|
373
|
+
Logger.debug("Login Response", response);
|
|
374
|
+
this.setToken(response.token);
|
|
375
|
+
Logger.info("Session login successful");
|
|
376
|
+
if (this.events.onAuthSuccess)
|
|
377
|
+
this.events.onAuthSuccess(response);
|
|
232
378
|
return response;
|
|
233
379
|
}
|
|
234
380
|
catch (error) {
|
|
235
|
-
|
|
381
|
+
Logger.warn("Login attempt failed", {
|
|
382
|
+
attempt: attempts,
|
|
383
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
384
|
+
});
|
|
236
385
|
if (attempts >= maxAttempts || !(error instanceof CAMSError)) {
|
|
237
386
|
throw error;
|
|
238
387
|
}
|
|
@@ -240,79 +389,184 @@ class CAMSSession {
|
|
|
240
389
|
if (![exports.CAMSErrorType.TIMEOUT, exports.CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {
|
|
241
390
|
throw error;
|
|
242
391
|
}
|
|
392
|
+
Logger.info("Retrying login", { nextAttempt: attempts + 1 });
|
|
243
393
|
}
|
|
244
394
|
}
|
|
245
|
-
throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED,
|
|
395
|
+
throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED, "Max retry attempts exceeded");
|
|
246
396
|
}
|
|
247
397
|
catch (error) {
|
|
248
|
-
const
|
|
249
|
-
|
|
250
|
-
|
|
398
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
399
|
+
const camsError = error instanceof CAMSError
|
|
400
|
+
? error
|
|
401
|
+
: new CAMSError(exports.CAMSErrorType.USER_CANCELLED, errorMessage);
|
|
402
|
+
Logger.error("Session login failed", {
|
|
403
|
+
error: camsError.message,
|
|
404
|
+
type: camsError.type,
|
|
405
|
+
});
|
|
406
|
+
if (this.events.onAuthError)
|
|
407
|
+
this.events.onAuthError(camsError);
|
|
251
408
|
throw camsError;
|
|
252
409
|
}
|
|
253
410
|
}
|
|
254
411
|
async logout() {
|
|
255
|
-
|
|
412
|
+
Logger.info("Session logout");
|
|
413
|
+
this.clearToken();
|
|
256
414
|
}
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
415
|
+
setToken(token) {
|
|
416
|
+
this.token = token;
|
|
417
|
+
this.storage.setItem(this.keyPrefix, token);
|
|
418
|
+
Logger.debug("Token stored", { storageKey: this.keyPrefix });
|
|
419
|
+
}
|
|
420
|
+
getAccessToken() {
|
|
421
|
+
// Return cached token if available, avoiding redundant storage access
|
|
422
|
+
if (this.token)
|
|
423
|
+
return this.token;
|
|
424
|
+
const raw = this.storage.getItem(this.keyPrefix);
|
|
425
|
+
if (!raw)
|
|
426
|
+
return null;
|
|
427
|
+
this.token = raw;
|
|
428
|
+
Logger.debug("Token loaded from storage");
|
|
429
|
+
return this.token;
|
|
430
|
+
}
|
|
431
|
+
clearToken() {
|
|
432
|
+
this.token = null;
|
|
433
|
+
this.storage.removeItem(this.keyPrefix);
|
|
434
|
+
Logger.debug("Token cleared");
|
|
435
|
+
}
|
|
436
|
+
isExpired() {
|
|
437
|
+
const token = this.getAccessToken();
|
|
260
438
|
if (!token)
|
|
261
|
-
return
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
439
|
+
return true;
|
|
440
|
+
try {
|
|
441
|
+
const parts = token.split(".");
|
|
442
|
+
if (parts.length < 3)
|
|
443
|
+
return true; // Invalid JWT format
|
|
444
|
+
const payload = JSON.parse(atob(parts[1]));
|
|
445
|
+
if (typeof payload.exp !== "number")
|
|
446
|
+
return true;
|
|
447
|
+
const exp = payload.exp * 1000;
|
|
448
|
+
return Date.now() > exp;
|
|
449
|
+
}
|
|
450
|
+
catch (error) {
|
|
451
|
+
Logger.warn("Failed to parse JWT token", {
|
|
452
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
453
|
+
});
|
|
454
|
+
return true;
|
|
265
455
|
}
|
|
266
|
-
return true;
|
|
267
456
|
}
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
const token = this.tokenManager.loadToken();
|
|
457
|
+
isPaddedExpired() {
|
|
458
|
+
const token = this.getAccessToken();
|
|
271
459
|
if (!token)
|
|
272
|
-
return
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
460
|
+
return true;
|
|
461
|
+
try {
|
|
462
|
+
const parts = token.split(".");
|
|
463
|
+
if (parts.length < 3)
|
|
464
|
+
return true; // Invalid JWT format
|
|
465
|
+
const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
466
|
+
const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=");
|
|
467
|
+
const payload = JSON.parse(atob(padded));
|
|
468
|
+
if (typeof payload.exp !== "number")
|
|
469
|
+
return true;
|
|
470
|
+
const exp = payload.exp * 1000;
|
|
471
|
+
return Date.now() > exp;
|
|
276
472
|
}
|
|
277
|
-
|
|
473
|
+
catch (error) {
|
|
474
|
+
Logger.warn("Failed to parse JWT token", {
|
|
475
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
476
|
+
});
|
|
477
|
+
return true;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
checkTokenExpiration() {
|
|
481
|
+
if (this.isExpired()) {
|
|
482
|
+
Logger.info("Token expired");
|
|
483
|
+
if (this.events.onTokenExpired)
|
|
484
|
+
this.events.onTokenExpired();
|
|
485
|
+
return true;
|
|
486
|
+
}
|
|
487
|
+
return false;
|
|
488
|
+
}
|
|
489
|
+
isAuthenticated() {
|
|
490
|
+
const token = this.getAccessToken();
|
|
491
|
+
if (!token) {
|
|
492
|
+
Logger.debug("No token found");
|
|
493
|
+
return false;
|
|
494
|
+
}
|
|
495
|
+
if (this.checkTokenExpiration()) {
|
|
496
|
+
return false;
|
|
497
|
+
}
|
|
498
|
+
Logger.debug("Token is valid");
|
|
499
|
+
return true;
|
|
278
500
|
}
|
|
279
501
|
decodeBase64Url(str) {
|
|
280
|
-
//
|
|
281
|
-
|
|
502
|
+
// Work with a copy to avoid mutating input
|
|
503
|
+
let result = str.replace(/-/g, "+").replace(/_/g, "/");
|
|
282
504
|
// Add padding if needed
|
|
283
|
-
while (
|
|
284
|
-
|
|
505
|
+
while (result.length % 4) {
|
|
506
|
+
result += "=";
|
|
285
507
|
}
|
|
286
|
-
return atob(
|
|
508
|
+
return atob(result);
|
|
287
509
|
}
|
|
288
510
|
async getProfile() {
|
|
289
|
-
const storedToken = this.
|
|
290
|
-
if (!
|
|
511
|
+
const storedToken = this.getAccessToken();
|
|
512
|
+
if (!storedToken)
|
|
291
513
|
return null;
|
|
514
|
+
// Check token expiration before processing
|
|
515
|
+
if (this.checkTokenExpiration()) {
|
|
516
|
+
return null;
|
|
517
|
+
}
|
|
292
518
|
try {
|
|
293
|
-
const parts = storedToken.
|
|
294
|
-
if (parts.length >= 3) {
|
|
519
|
+
const parts = storedToken.split(".");
|
|
520
|
+
if (parts.length >= 3) {
|
|
521
|
+
// JWT has header.payload.signature format
|
|
295
522
|
try {
|
|
296
523
|
const payload = JSON.parse(this.decodeBase64Url(parts[1]));
|
|
297
524
|
return ProfileSchema.parse(payload);
|
|
298
525
|
}
|
|
299
526
|
catch (decodeError) {
|
|
300
|
-
|
|
527
|
+
Logger.warn("Failed to decode JWT payload", {
|
|
528
|
+
error: decodeError instanceof Error
|
|
529
|
+
? decodeError.message
|
|
530
|
+
: "Unknown error",
|
|
531
|
+
});
|
|
301
532
|
}
|
|
302
533
|
}
|
|
303
534
|
}
|
|
304
535
|
catch (error) {
|
|
305
|
-
|
|
536
|
+
Logger.warn("Failed to extract profile from token", {
|
|
537
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
538
|
+
});
|
|
306
539
|
}
|
|
307
540
|
return null;
|
|
308
541
|
}
|
|
309
542
|
}
|
|
543
|
+
// 🔹 Safe fallback for Node/SSR
|
|
544
|
+
function getDefaultStorage() {
|
|
545
|
+
if (typeof window !== "undefined" && window.localStorage) {
|
|
546
|
+
return window.localStorage;
|
|
547
|
+
}
|
|
548
|
+
const memoryStore = {};
|
|
549
|
+
return {
|
|
550
|
+
getItem: (key) => (key in memoryStore ? memoryStore[key] : null),
|
|
551
|
+
setItem: (key, value) => {
|
|
552
|
+
memoryStore[key] = value;
|
|
553
|
+
},
|
|
554
|
+
removeItem: (key) => {
|
|
555
|
+
delete memoryStore[key];
|
|
556
|
+
},
|
|
557
|
+
key: (i) => Object.keys(memoryStore)[i] ?? null,
|
|
558
|
+
get length() {
|
|
559
|
+
return Object.keys(memoryStore).length;
|
|
560
|
+
},
|
|
561
|
+
};
|
|
562
|
+
}
|
|
310
563
|
|
|
564
|
+
exports.AuthFailureMessageSchema = AuthFailureMessageSchema;
|
|
311
565
|
exports.CAMSError = CAMSError;
|
|
312
|
-
exports.
|
|
566
|
+
exports.CAMSSessionManager = CAMSSessionManager;
|
|
313
567
|
exports.ErrorMessageSchema = ErrorMessageSchema;
|
|
568
|
+
exports.Logger = Logger;
|
|
314
569
|
exports.ProfileSchema = ProfileSchema;
|
|
315
|
-
exports.TokenManager = TokenManager;
|
|
316
570
|
exports.TokenMessageSchema = TokenMessageSchema;
|
|
317
571
|
exports.TokenSchema = TokenSchema;
|
|
318
572
|
exports.URLSchema = URLSchema;
|