@nibssplc/cams-sdk 0.0.1-beta.12 → 0.0.1-beta.14
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 +2 -2
- package/dist/__tests__/tokenManager.test.d.ts +1 -0
- package/dist/auth.d.ts +1 -1
- package/dist/index.cjs.js +222 -130
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +222 -130
- package/dist/index.esm.js.map +1 -1
- package/dist/index.umd.js +222 -130
- package/dist/index.umd.js.map +1 -1
- package/dist/logger.d.ts +3 -2
- package/dist/session.d.ts +2 -1
- package/dist/types.d.ts +5 -4
- package/dist/validators.d.ts +6 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -46,7 +46,7 @@ try {
|
|
|
46
46
|
### Session Management (Recommended)
|
|
47
47
|
|
|
48
48
|
```typescript
|
|
49
|
-
import {
|
|
49
|
+
import { CAMSSessionManager, CAMSEvents } from '@nibssplc/cams-sdk';
|
|
50
50
|
|
|
51
51
|
const events: CAMSEvents = {
|
|
52
52
|
onAuthStart: () => console.log('Authentication started'),
|
|
@@ -55,7 +55,7 @@ const events: CAMSEvents = {
|
|
|
55
55
|
onTokenExpired: () => console.log('Token expired'),
|
|
56
56
|
};
|
|
57
57
|
|
|
58
|
-
const session = new
|
|
58
|
+
const session = new CAMSSessionManager(sessionStorage, 'my_app_token', events);
|
|
59
59
|
|
|
60
60
|
// Login with retry logic
|
|
61
61
|
const config = {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/auth.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { CAMSConfig, CAMSTokenResponse } from "./types";
|
|
2
|
-
export declare function validateConfig(config: CAMSConfig):
|
|
2
|
+
export declare function validateConfig(config: CAMSConfig): URL;
|
|
3
3
|
export declare function openCAMSPopUpLogin(config: CAMSConfig): Promise<CAMSTokenResponse>;
|
package/dist/index.cjs.js
CHANGED
|
@@ -10,18 +10,25 @@ 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
34
|
error: zod.z.string().min(1, "Error message cannot be empty"),
|
|
@@ -41,14 +48,7 @@ const ProfileSchema = zod.z.object({
|
|
|
41
48
|
family_name: zod.z.string().optional(),
|
|
42
49
|
roles: zod.z.array(zod.z.string()).optional(),
|
|
43
50
|
});
|
|
44
|
-
|
|
45
|
-
const internalIpRegex = /^(http:\/\/|https:\/\/)((10\.\d{1,3}\.\d{1,3}\.\d{1,3})|(192\.168\.\d{1,3}\.\d{1,3})|(172\.(1[6-9]|2\d|3[0-1])\.\d{1,3}\.\d{1,3}))(:\d+)?$/;
|
|
46
|
-
const URLSchema = zod.z.url().refine((url) => url.startsWith("https://") || // normal HTTPS
|
|
47
|
-
/^http:\/\/localhost(:\d+)?$/i.test(url) || // localhost
|
|
48
|
-
internalIpRegex.test(url), // internal LAN IPs
|
|
49
|
-
{
|
|
50
|
-
message: "Only HTTPS, http://localhost, or internal IPs (192.168.x.x, 10.x.x.x, 172.16–31.x.x) are allowed",
|
|
51
|
-
});
|
|
51
|
+
const URLSchema = zod.z.url();
|
|
52
52
|
|
|
53
53
|
exports.LogLevel = void 0;
|
|
54
54
|
(function (LogLevel) {
|
|
@@ -58,185 +58,256 @@ exports.LogLevel = void 0;
|
|
|
58
58
|
LogLevel[LogLevel["DEBUG"] = 3] = "DEBUG";
|
|
59
59
|
})(exports.LogLevel || (exports.LogLevel = {}));
|
|
60
60
|
class Logger {
|
|
61
|
+
static level = exports.LogLevel.WARN;
|
|
62
|
+
static prefix = '[CAMS-SDK]';
|
|
63
|
+
static isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';
|
|
61
64
|
static setLevel(level) {
|
|
62
65
|
Logger.level = level;
|
|
63
66
|
}
|
|
67
|
+
static sanitizeForLog(input) {
|
|
68
|
+
if (typeof input === 'string') {
|
|
69
|
+
// Remove newlines and control characters to prevent log injection
|
|
70
|
+
return input.replace(/[\r\n\t]/g, ' ').replace(/[\x00-\x1F\x7F]/g, '');
|
|
71
|
+
}
|
|
72
|
+
if (typeof input === 'object' && input !== null) {
|
|
73
|
+
const sanitized = {};
|
|
74
|
+
for (const [key, value] of Object.entries(input)) {
|
|
75
|
+
sanitized[Logger.sanitizeForLog(key)] = Logger.sanitizeForLog(value);
|
|
76
|
+
}
|
|
77
|
+
return sanitized;
|
|
78
|
+
}
|
|
79
|
+
return input;
|
|
80
|
+
}
|
|
64
81
|
static error(message, context) {
|
|
65
82
|
if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.ERROR) {
|
|
66
|
-
console.error(`${Logger.prefix} ERROR:`, message, context || '');
|
|
83
|
+
console.error(`${Logger.prefix} ERROR:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
|
|
67
84
|
}
|
|
68
85
|
}
|
|
69
86
|
static warn(message, context) {
|
|
70
87
|
if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.WARN) {
|
|
71
|
-
console.warn(`${Logger.prefix} WARN:`, message, context || '');
|
|
88
|
+
console.warn(`${Logger.prefix} WARN:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
|
|
72
89
|
}
|
|
73
90
|
}
|
|
74
91
|
static info(message, context) {
|
|
75
92
|
if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.INFO) {
|
|
76
|
-
console.info(`${Logger.prefix} INFO:`, message, context || '');
|
|
93
|
+
console.info(`${Logger.prefix} INFO:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
|
|
77
94
|
}
|
|
78
95
|
}
|
|
79
96
|
static debug(message, context) {
|
|
80
97
|
if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.DEBUG) {
|
|
81
|
-
console.debug(`${Logger.prefix} DEBUG:`, message, context || '');
|
|
98
|
+
console.debug(`${Logger.prefix} DEBUG:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
|
|
82
99
|
}
|
|
83
100
|
}
|
|
84
101
|
}
|
|
85
|
-
Logger.level = exports.LogLevel.WARN;
|
|
86
|
-
Logger.prefix = '[CAMS-SDK]';
|
|
87
|
-
Logger.isTestEnv = typeof process !== 'undefined' && process.env?.NODE_ENV === 'test';
|
|
88
102
|
|
|
89
103
|
function validateConfig(config) {
|
|
90
|
-
// Validate URL format
|
|
104
|
+
// Validate URL format and parse once
|
|
91
105
|
const urlValidation = URLSchema.safeParse(config.camsUrl);
|
|
92
106
|
if (!urlValidation.success) {
|
|
93
|
-
throw new CAMSError(exports.CAMSErrorType.INVALID_URL,
|
|
107
|
+
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Invalid CAMS URL format");
|
|
94
108
|
}
|
|
95
109
|
// Domain validation is mandatory for security
|
|
96
|
-
if (!config.
|
|
97
|
-
throw new CAMSError(exports.CAMSErrorType.INVALID_URL,
|
|
98
|
-
}
|
|
99
|
-
const url = new URL(config.camsUrl); // URLSchema already validated this
|
|
100
|
-
const isAllowed = config.allowedDomains.some(domain => url.hostname === domain || url.hostname.endsWith('.' + domain));
|
|
101
|
-
if (!isAllowed) {
|
|
102
|
-
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'URL not in allowed domains list');
|
|
110
|
+
if (!config.messageOrigin) {
|
|
111
|
+
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Message Origin must be specified for security");
|
|
103
112
|
}
|
|
113
|
+
const url = new URL(config.camsUrl);
|
|
114
|
+
return url;
|
|
104
115
|
}
|
|
105
116
|
function openCAMSPopUpLogin(config) {
|
|
106
117
|
return new Promise((resolve, reject) => {
|
|
107
118
|
if (config.debug)
|
|
108
119
|
Logger.setLevel(exports.LogLevel.DEBUG);
|
|
109
|
-
Logger.info(
|
|
120
|
+
Logger.info("Starting CAMS authentication", { url: config.camsUrl });
|
|
121
|
+
let validatedUrl;
|
|
110
122
|
try {
|
|
111
|
-
validateConfig(config);
|
|
112
|
-
Logger.debug(
|
|
123
|
+
validatedUrl = validateConfig(config);
|
|
124
|
+
Logger.debug("Config validation passed");
|
|
113
125
|
}
|
|
114
126
|
catch (error) {
|
|
115
|
-
Logger.error(
|
|
127
|
+
Logger.error("Config validation failed", {
|
|
128
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
129
|
+
});
|
|
116
130
|
reject(error);
|
|
117
131
|
return;
|
|
118
132
|
}
|
|
119
|
-
const {
|
|
133
|
+
const { messageOrigin, windowHeight, windowWidth, authTimeout = 300000, // 5 minutes as a final failsafe
|
|
134
|
+
idleTimeout = 60000, // 1 minute of inactivity
|
|
135
|
+
} = config;
|
|
120
136
|
let authWindow;
|
|
121
|
-
let
|
|
137
|
+
let authTimeoutId = null;
|
|
138
|
+
let idleTimeoutId = null;
|
|
122
139
|
let checkClosedInterval = null;
|
|
123
140
|
try {
|
|
124
|
-
Logger.debug(
|
|
125
|
-
|
|
141
|
+
Logger.debug("Opening popup window", {
|
|
142
|
+
width: windowWidth,
|
|
143
|
+
height: windowHeight,
|
|
144
|
+
});
|
|
145
|
+
// Center the popup window
|
|
146
|
+
const left = (window.screen.width - windowWidth) / 2;
|
|
147
|
+
const top = (window.screen.height - windowHeight) / 2;
|
|
148
|
+
authWindow = window.open(validatedUrl.toString(), "_blank", `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes`);
|
|
126
149
|
}
|
|
127
150
|
catch (error) {
|
|
128
|
-
Logger.error(
|
|
129
|
-
|
|
151
|
+
Logger.error("Failed to open popup window", {
|
|
152
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
153
|
+
});
|
|
154
|
+
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window: " +
|
|
155
|
+
(error instanceof Error ? error.message : "Unknown error")));
|
|
130
156
|
return;
|
|
131
157
|
}
|
|
132
158
|
if (!authWindow) {
|
|
133
|
-
Logger.error(
|
|
159
|
+
Logger.error("Popup window blocked");
|
|
134
160
|
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window. Please allow popups."));
|
|
135
161
|
return;
|
|
136
162
|
}
|
|
137
|
-
Logger.debug(
|
|
163
|
+
Logger.debug("Popup window opened successfully");
|
|
138
164
|
const cleanup = () => {
|
|
139
165
|
window.removeEventListener("message", listener);
|
|
140
|
-
if (
|
|
141
|
-
clearTimeout(
|
|
166
|
+
if (idleTimeoutId)
|
|
167
|
+
clearTimeout(idleTimeoutId);
|
|
168
|
+
if (authTimeoutId)
|
|
169
|
+
clearTimeout(authTimeoutId);
|
|
142
170
|
if (checkClosedInterval)
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
try {
|
|
148
|
-
if (authWindow && !authWindow.closed) {
|
|
149
|
-
authWindow.close();
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
catch {
|
|
153
|
-
// Ignore close errors
|
|
154
|
-
}
|
|
155
|
-
if (error)
|
|
156
|
-
reject(error);
|
|
171
|
+
clearTimeout(checkClosedInterval);
|
|
172
|
+
idleTimeoutId = null;
|
|
173
|
+
authTimeoutId = null;
|
|
174
|
+
checkClosedInterval = null;
|
|
157
175
|
};
|
|
158
176
|
const listener = (event) => {
|
|
159
|
-
Logger.debug(
|
|
160
|
-
|
|
161
|
-
|
|
177
|
+
Logger.debug("Received message", {
|
|
178
|
+
origin: event.origin,
|
|
179
|
+
expectedOrigin: messageOrigin,
|
|
180
|
+
data: event.data,
|
|
181
|
+
});
|
|
182
|
+
const originUrl = new URL(event.origin);
|
|
183
|
+
const isAllowedOrigin = originUrl.hostname === messageOrigin ||
|
|
184
|
+
originUrl.hostname.endsWith("." + messageOrigin);
|
|
185
|
+
if (!isAllowedOrigin) {
|
|
186
|
+
Logger.warn("Blocked message from unauthorized origin", {
|
|
187
|
+
origin: event.origin,
|
|
188
|
+
expected: messageOrigin,
|
|
189
|
+
});
|
|
162
190
|
return;
|
|
163
191
|
}
|
|
164
192
|
// ✅ Validate payload
|
|
165
193
|
const tokenMsg = TokenMessageSchema.safeParse(event.data);
|
|
166
194
|
if (tokenMsg.success) {
|
|
167
|
-
Logger.info(
|
|
195
|
+
Logger.info("Authentication successful");
|
|
168
196
|
cleanupAndClose();
|
|
169
|
-
resolve({ token: tokenMsg.data.
|
|
197
|
+
resolve({ token: tokenMsg.data.accessToken });
|
|
170
198
|
return;
|
|
171
199
|
}
|
|
172
200
|
const errorMsg = ErrorMessageSchema.safeParse(event.data);
|
|
173
201
|
if (errorMsg.success) {
|
|
174
|
-
Logger.warn(
|
|
202
|
+
Logger.warn("Authentication error received", {
|
|
203
|
+
error: errorMsg.data.error,
|
|
204
|
+
});
|
|
175
205
|
cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication failed: " + errorMsg.data.error));
|
|
176
206
|
return;
|
|
177
207
|
}
|
|
178
|
-
Logger.error(
|
|
208
|
+
Logger.error("Invalid message format received", {
|
|
179
209
|
messageData: event.data,
|
|
180
210
|
dataType: typeof event.data,
|
|
181
|
-
tokenValidationError: tokenMsg.error
|
|
182
|
-
|
|
211
|
+
tokenValidationError: tokenMsg.error
|
|
212
|
+
? tokenMsg.error.issues
|
|
213
|
+
: undefined,
|
|
214
|
+
errorValidationError: errorMsg.error
|
|
215
|
+
? errorMsg.error.issues
|
|
216
|
+
: undefined,
|
|
183
217
|
});
|
|
184
218
|
cleanupAndClose(new CAMSError(exports.CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
|
|
185
219
|
};
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
220
|
+
const cleanupAndClose = (error) => {
|
|
221
|
+
cleanup();
|
|
222
|
+
try {
|
|
223
|
+
if (authWindow && !authWindow.closed) {
|
|
224
|
+
authWindow.close();
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
// Ignore close errors
|
|
229
|
+
}
|
|
230
|
+
if (error)
|
|
231
|
+
reject(error);
|
|
232
|
+
};
|
|
233
|
+
const resetIdleTimeout = () => {
|
|
234
|
+
// Timeout handler
|
|
235
|
+
if (idleTimeoutId)
|
|
236
|
+
clearTimeout(idleTimeoutId);
|
|
237
|
+
Logger.debug("Resetting idle timeout", { idleTimeout });
|
|
238
|
+
idleTimeoutId = setTimeout(() => {
|
|
239
|
+
Logger.warn("Authentication idle timeout reached", { idleTimeout });
|
|
240
|
+
cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timed out due to inactivity after ${idleTimeout}ms`));
|
|
241
|
+
}, idleTimeout);
|
|
242
|
+
};
|
|
243
|
+
Logger.debug("Setting auth timeout", { authTimeout });
|
|
244
|
+
authTimeoutId = setTimeout(() => {
|
|
245
|
+
Logger.warn("Authentication auth timeout reached", { authTimeout });
|
|
246
|
+
cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication process exceeded auth time limit of ${authTimeout}ms`));
|
|
247
|
+
}, authTimeout);
|
|
248
|
+
resetIdleTimeout();
|
|
249
|
+
// Use exponential backoff for popup closure checking
|
|
250
|
+
let pollInterval = 1000; // Start with 1 second
|
|
251
|
+
const maxPollInterval = 5000; // Max 5 seconds
|
|
252
|
+
const checkClosed = () => {
|
|
253
|
+
if (authWindow?.closed) {
|
|
254
|
+
Logger.info("Authentication window closed by user");
|
|
195
255
|
cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
|
|
256
|
+
return;
|
|
196
257
|
}
|
|
197
|
-
|
|
258
|
+
// Exponential backoff: increase interval up to max
|
|
259
|
+
pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);
|
|
260
|
+
checkClosedInterval = setTimeout(checkClosed, pollInterval);
|
|
261
|
+
};
|
|
262
|
+
checkClosedInterval = setTimeout(checkClosed, pollInterval);
|
|
198
263
|
try {
|
|
199
264
|
window.addEventListener("message", listener);
|
|
265
|
+
Logger.debug("Message listener attached");
|
|
200
266
|
}
|
|
201
267
|
catch (error) {
|
|
268
|
+
Logger.error("Failed to attach message listener", {
|
|
269
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
270
|
+
});
|
|
202
271
|
cleanup();
|
|
203
|
-
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " +
|
|
272
|
+
reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " +
|
|
273
|
+
(error instanceof Error ? error.message : "Unknown error")));
|
|
204
274
|
return;
|
|
205
275
|
}
|
|
276
|
+
// Add focus to the popup for better UX
|
|
277
|
+
try {
|
|
278
|
+
if (authWindow) {
|
|
279
|
+
authWindow.focus();
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
catch {
|
|
283
|
+
// Ignore focus errors (cross-origin restrictions)
|
|
284
|
+
}
|
|
206
285
|
});
|
|
207
286
|
}
|
|
208
287
|
|
|
209
288
|
class TokenManager {
|
|
289
|
+
storage;
|
|
290
|
+
token = null;
|
|
291
|
+
storageKey;
|
|
210
292
|
constructor(storage = sessionStorage, storageKey) {
|
|
211
293
|
this.storage = storage;
|
|
212
|
-
this.token = null;
|
|
213
294
|
this.storageKey = storageKey || "cams_token";
|
|
214
295
|
}
|
|
215
296
|
setToken(token) {
|
|
216
|
-
|
|
217
|
-
this.storage.setItem(this.storageKey,
|
|
297
|
+
this.token = token;
|
|
298
|
+
this.storage.setItem(this.storageKey, token);
|
|
218
299
|
Logger.debug("Token stored", { storageKey: this.storageKey });
|
|
219
300
|
}
|
|
220
301
|
loadToken() {
|
|
302
|
+
// Return cached token if available
|
|
221
303
|
if (this.token)
|
|
222
304
|
return this.token;
|
|
223
305
|
const raw = this.storage.getItem(this.storageKey);
|
|
224
306
|
if (!raw)
|
|
225
307
|
return null;
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
return this.token;
|
|
230
|
-
}
|
|
231
|
-
catch (validationError) {
|
|
232
|
-
Logger.warn("Token validation failed", {
|
|
233
|
-
error: validationError instanceof Error
|
|
234
|
-
? validationError.message
|
|
235
|
-
: "Unknown error",
|
|
236
|
-
});
|
|
237
|
-
this.storage.removeItem(this.storageKey);
|
|
238
|
-
return null;
|
|
239
|
-
}
|
|
308
|
+
this.token = raw;
|
|
309
|
+
Logger.debug("Token loaded from storage");
|
|
310
|
+
return this.token;
|
|
240
311
|
}
|
|
241
312
|
clearToken() {
|
|
242
313
|
this.token = null;
|
|
@@ -244,38 +315,37 @@ class TokenManager {
|
|
|
244
315
|
Logger.debug("Token cleared");
|
|
245
316
|
}
|
|
246
317
|
getAccessToken() {
|
|
247
|
-
|
|
248
|
-
|
|
318
|
+
// Return cached token if available, avoiding redundant storage access
|
|
319
|
+
if (this.token)
|
|
320
|
+
return this.token;
|
|
321
|
+
return this.loadToken();
|
|
249
322
|
}
|
|
250
323
|
isExpired() {
|
|
251
324
|
const token = this.loadToken();
|
|
252
325
|
if (!token)
|
|
253
326
|
return true;
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
const payload = JSON.parse(atob(parts[1]));
|
|
261
|
-
if (typeof payload.exp !== "number")
|
|
262
|
-
return true;
|
|
263
|
-
const exp = payload.exp * 1000;
|
|
264
|
-
return Date.now() > exp;
|
|
265
|
-
}
|
|
266
|
-
catch (error) {
|
|
267
|
-
Logger.warn("Failed to parse JWT token", {
|
|
268
|
-
error: error instanceof Error ? error.message : "Unknown error",
|
|
269
|
-
});
|
|
327
|
+
try {
|
|
328
|
+
const parts = token.split(".");
|
|
329
|
+
if (parts.length < 3)
|
|
330
|
+
return true; // Invalid JWT format
|
|
331
|
+
const payload = JSON.parse(atob(parts[1]));
|
|
332
|
+
if (typeof payload.exp !== "number")
|
|
270
333
|
return true;
|
|
271
|
-
|
|
334
|
+
const exp = payload.exp * 1000;
|
|
335
|
+
return Date.now() > exp;
|
|
336
|
+
}
|
|
337
|
+
catch (error) {
|
|
338
|
+
Logger.warn("Failed to parse JWT token", {
|
|
339
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
340
|
+
});
|
|
341
|
+
return true;
|
|
272
342
|
}
|
|
273
|
-
// Fallback: return true for safety when expiration cannot be determined
|
|
274
|
-
return true;
|
|
275
343
|
}
|
|
276
344
|
}
|
|
277
345
|
|
|
278
|
-
class
|
|
346
|
+
class CAMSSessionManager {
|
|
347
|
+
tokenManager;
|
|
348
|
+
events;
|
|
279
349
|
constructor(storage = sessionStorage, storageKey, events = {}) {
|
|
280
350
|
this.tokenManager = new TokenManager(storage, storageKey);
|
|
281
351
|
this.events = events;
|
|
@@ -283,17 +353,27 @@ class CAMSSession {
|
|
|
283
353
|
async login(config) {
|
|
284
354
|
try {
|
|
285
355
|
Logger.info('Session login started');
|
|
286
|
-
|
|
356
|
+
if (this.events.onAuthStart)
|
|
357
|
+
this.events.onAuthStart();
|
|
287
358
|
let attempts = 0;
|
|
288
|
-
const maxAttempts = (config.retryAttempts
|
|
359
|
+
const maxAttempts = (config.retryAttempts !== undefined ? config.retryAttempts : 0) + 1;
|
|
289
360
|
Logger.debug('Login retry configuration', { maxAttempts });
|
|
290
361
|
while (attempts < maxAttempts) {
|
|
291
362
|
try {
|
|
292
363
|
attempts++;
|
|
293
364
|
Logger.debug('Login attempt', { attempt: attempts, maxAttempts });
|
|
365
|
+
// Add exponential backoff delay for retries
|
|
366
|
+
if (attempts > 1) {
|
|
367
|
+
const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay
|
|
368
|
+
Logger.debug('Retry delay', { delay });
|
|
369
|
+
await new Promise(resolve => setTimeout(resolve, delay));
|
|
370
|
+
}
|
|
294
371
|
const response = await openCAMSPopUpLogin(config);
|
|
372
|
+
Logger.debug('Login Response', response);
|
|
373
|
+
this.tokenManager.setToken(response.token);
|
|
295
374
|
Logger.info('Session login successful');
|
|
296
|
-
|
|
375
|
+
if (this.events.onAuthSuccess)
|
|
376
|
+
this.events.onAuthSuccess(response);
|
|
297
377
|
return response;
|
|
298
378
|
}
|
|
299
379
|
catch (error) {
|
|
@@ -311,10 +391,12 @@ class CAMSSession {
|
|
|
311
391
|
throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED, 'Max retry attempts exceeded');
|
|
312
392
|
}
|
|
313
393
|
catch (error) {
|
|
394
|
+
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
314
395
|
const camsError = error instanceof CAMSError ? error :
|
|
315
|
-
new CAMSError(exports.CAMSErrorType.USER_CANCELLED,
|
|
396
|
+
new CAMSError(exports.CAMSErrorType.USER_CANCELLED, errorMessage);
|
|
316
397
|
Logger.error('Session login failed', { error: camsError.message, type: camsError.type });
|
|
317
|
-
|
|
398
|
+
if (this.events.onAuthError)
|
|
399
|
+
this.events.onAuthError(camsError);
|
|
318
400
|
throw camsError;
|
|
319
401
|
}
|
|
320
402
|
}
|
|
@@ -322,15 +404,22 @@ class CAMSSession {
|
|
|
322
404
|
Logger.info('Session logout');
|
|
323
405
|
this.tokenManager.clearToken();
|
|
324
406
|
}
|
|
407
|
+
checkTokenExpiration() {
|
|
408
|
+
if (this.tokenManager.isExpired()) {
|
|
409
|
+
Logger.info('Token expired');
|
|
410
|
+
if (this.events.onTokenExpired)
|
|
411
|
+
this.events.onTokenExpired();
|
|
412
|
+
return true;
|
|
413
|
+
}
|
|
414
|
+
return false;
|
|
415
|
+
}
|
|
325
416
|
isAuthenticated() {
|
|
326
417
|
const token = this.tokenManager.loadToken();
|
|
327
418
|
if (!token) {
|
|
328
419
|
Logger.debug('No token found');
|
|
329
420
|
return false;
|
|
330
421
|
}
|
|
331
|
-
if (this.
|
|
332
|
-
Logger.info('Token expired');
|
|
333
|
-
this.events.onTokenExpired?.();
|
|
422
|
+
if (this.checkTokenExpiration()) {
|
|
334
423
|
return false;
|
|
335
424
|
}
|
|
336
425
|
Logger.debug('Token is valid');
|
|
@@ -340,25 +429,28 @@ class CAMSSession {
|
|
|
340
429
|
const token = this.tokenManager.loadToken();
|
|
341
430
|
if (!token)
|
|
342
431
|
return null;
|
|
343
|
-
if (this.
|
|
344
|
-
this.events.onTokenExpired?.();
|
|
432
|
+
if (this.checkTokenExpiration()) {
|
|
345
433
|
return null;
|
|
346
434
|
}
|
|
347
435
|
return token;
|
|
348
436
|
}
|
|
349
437
|
decodeBase64Url(str) {
|
|
350
|
-
//
|
|
351
|
-
|
|
438
|
+
// Work with a copy to avoid mutating input
|
|
439
|
+
let result = str.replace(/-/g, '+').replace(/_/g, '/');
|
|
352
440
|
// Add padding if needed
|
|
353
|
-
while (
|
|
354
|
-
|
|
441
|
+
while (result.length % 4) {
|
|
442
|
+
result += '=';
|
|
355
443
|
}
|
|
356
|
-
return atob(
|
|
444
|
+
return atob(result);
|
|
357
445
|
}
|
|
358
446
|
async getProfile() {
|
|
359
447
|
const storedToken = this.tokenManager.loadToken();
|
|
360
448
|
if (!storedToken)
|
|
361
449
|
return null;
|
|
450
|
+
// Check token expiration before processing
|
|
451
|
+
if (this.checkTokenExpiration()) {
|
|
452
|
+
return null;
|
|
453
|
+
}
|
|
362
454
|
try {
|
|
363
455
|
const parts = storedToken.split('.');
|
|
364
456
|
if (parts.length >= 3) { // JWT has header.payload.signature format
|
|
@@ -379,7 +471,7 @@ class CAMSSession {
|
|
|
379
471
|
}
|
|
380
472
|
|
|
381
473
|
exports.CAMSError = CAMSError;
|
|
382
|
-
exports.
|
|
474
|
+
exports.CAMSSessionManager = CAMSSessionManager;
|
|
383
475
|
exports.ErrorMessageSchema = ErrorMessageSchema;
|
|
384
476
|
exports.Logger = Logger;
|
|
385
477
|
exports.ProfileSchema = ProfileSchema;
|