@nibssplc/cams-sdk 0.0.1-beta.12 → 0.0.1-beta.13
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/index.cjs.js +18 -22
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +18 -22
- package/dist/index.esm.js.map +1 -1
- package/dist/index.umd.js +18 -22
- package/dist/index.umd.js.map +1 -1
- package/dist/session.d.ts +1 -1
- 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 = {
|
package/dist/index.cjs.js
CHANGED
|
@@ -21,7 +21,12 @@ class CAMSError extends Error {
|
|
|
21
21
|
|
|
22
22
|
// Validate the returned token - Base64 format with minimum 20 chars
|
|
23
23
|
const TokenMessageSchema = zod.z.object({
|
|
24
|
-
|
|
24
|
+
type: zod.z.literal("AUTH_SUCCESS"),
|
|
25
|
+
accessToken: zod.z.string().min(1, "Access token cannot be empty"),
|
|
26
|
+
user: zod.z.object({
|
|
27
|
+
name: zod.z.string(),
|
|
28
|
+
image: zod.z.string().nullable(),
|
|
29
|
+
}).optional(),
|
|
25
30
|
});
|
|
26
31
|
const ErrorMessageSchema = zod.z.object({
|
|
27
32
|
error: zod.z.string().min(1, "Error message cannot be empty"),
|
|
@@ -166,7 +171,7 @@ function openCAMSPopUpLogin(config) {
|
|
|
166
171
|
if (tokenMsg.success) {
|
|
167
172
|
Logger.info('Authentication successful');
|
|
168
173
|
cleanupAndClose();
|
|
169
|
-
resolve({ token: tokenMsg.data.
|
|
174
|
+
resolve({ token: tokenMsg.data.accessToken });
|
|
170
175
|
return;
|
|
171
176
|
}
|
|
172
177
|
const errorMsg = ErrorMessageSchema.safeParse(event.data);
|
|
@@ -190,7 +195,7 @@ function openCAMSPopUpLogin(config) {
|
|
|
190
195
|
cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));
|
|
191
196
|
}, timeout);
|
|
192
197
|
checkClosedInterval = setInterval(() => {
|
|
193
|
-
if (authWindow
|
|
198
|
+
if (authWindow?.closed) {
|
|
194
199
|
Logger.info('Authentication window closed by user');
|
|
195
200
|
cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
|
|
196
201
|
}
|
|
@@ -213,8 +218,8 @@ class TokenManager {
|
|
|
213
218
|
this.storageKey = storageKey || "cams_token";
|
|
214
219
|
}
|
|
215
220
|
setToken(token) {
|
|
216
|
-
|
|
217
|
-
this.storage.setItem(this.storageKey,
|
|
221
|
+
this.token = token;
|
|
222
|
+
this.storage.setItem(this.storageKey, token);
|
|
218
223
|
Logger.debug("Token stored", { storageKey: this.storageKey });
|
|
219
224
|
}
|
|
220
225
|
loadToken() {
|
|
@@ -223,20 +228,9 @@ class TokenManager {
|
|
|
223
228
|
const raw = this.storage.getItem(this.storageKey);
|
|
224
229
|
if (!raw)
|
|
225
230
|
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
|
-
}
|
|
231
|
+
this.token = raw;
|
|
232
|
+
Logger.debug("Token loaded from storage");
|
|
233
|
+
return this.token;
|
|
240
234
|
}
|
|
241
235
|
clearToken() {
|
|
242
236
|
this.token = null;
|
|
@@ -275,7 +269,7 @@ class TokenManager {
|
|
|
275
269
|
}
|
|
276
270
|
}
|
|
277
271
|
|
|
278
|
-
class
|
|
272
|
+
class CAMSSessionManager {
|
|
279
273
|
constructor(storage = sessionStorage, storageKey, events = {}) {
|
|
280
274
|
this.tokenManager = new TokenManager(storage, storageKey);
|
|
281
275
|
this.events = events;
|
|
@@ -292,6 +286,7 @@ class CAMSSession {
|
|
|
292
286
|
attempts++;
|
|
293
287
|
Logger.debug('Login attempt', { attempt: attempts, maxAttempts });
|
|
294
288
|
const response = await openCAMSPopUpLogin(config);
|
|
289
|
+
this.tokenManager.setToken(response.token);
|
|
295
290
|
Logger.info('Session login successful');
|
|
296
291
|
this.events.onAuthSuccess && this.events.onAuthSuccess(response);
|
|
297
292
|
return response;
|
|
@@ -311,8 +306,9 @@ class CAMSSession {
|
|
|
311
306
|
throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED, 'Max retry attempts exceeded');
|
|
312
307
|
}
|
|
313
308
|
catch (error) {
|
|
309
|
+
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
314
310
|
const camsError = error instanceof CAMSError ? error :
|
|
315
|
-
new CAMSError(exports.CAMSErrorType.USER_CANCELLED,
|
|
311
|
+
new CAMSError(exports.CAMSErrorType.USER_CANCELLED, errorMessage);
|
|
316
312
|
Logger.error('Session login failed', { error: camsError.message, type: camsError.type });
|
|
317
313
|
this.events.onAuthError && this.events.onAuthError(camsError);
|
|
318
314
|
throw camsError;
|
|
@@ -379,7 +375,7 @@ class CAMSSession {
|
|
|
379
375
|
}
|
|
380
376
|
|
|
381
377
|
exports.CAMSError = CAMSError;
|
|
382
|
-
exports.
|
|
378
|
+
exports.CAMSSessionManager = CAMSSessionManager;
|
|
383
379
|
exports.ErrorMessageSchema = ErrorMessageSchema;
|
|
384
380
|
exports.Logger = Logger;
|
|
385
381
|
exports.ProfileSchema = ProfileSchema;
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/types.ts","../src/validators.ts","../src/logger.ts","../src/auth.ts","../src/tokenManager.ts","../src/session.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n allowedOrigin: string;\n windowWidth: number;\n windowHeight: number;\n timeout?: number; // Auth timeout in ms (default: 300000)\n allowedDomains?: string[]; // URL allowlist for security\n storageKey?: string; // Custom storage key\n retryAttempts?: number; // Auto-retry on failure (default: 0)\n debug?: boolean; // Enable debug logging (default: false)\n}\n\nexport enum CAMSErrorType {\n POPUP_BLOCKED = 'POPUP_BLOCKED',\n TIMEOUT = 'TIMEOUT',\n INVALID_ORIGIN = 'INVALID_ORIGIN',\n USER_CANCELLED = 'USER_CANCELLED',\n INVALID_URL = 'INVALID_URL',\n MAX_RETRIES_EXCEEDED = 'MAX_RETRIES_EXCEEDED'\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = 'CAMSError';\n }\n}\n\nexport interface CAMSTokenResponse {\n token: string;\n}\n\nexport interface CAMSErrorResponse {\n error: string;\n}\n","import { z } from \"zod\";\n\n// Validate the returned token - Base64 format with minimum 20 chars\nexport const TokenMessageSchema = z.object({\n access_token: z.string().min(1, \"NIBSS CAMS Access token cannot be empty\"),\n});\n\nexport type TokenMessage = z.infer<typeof TokenMessageSchema>;\n\nexport const ErrorMessageSchema = z.object({\n error: z.string().min(1, \"Error message cannot be empty\"),\n});\n\nexport const TokenSchema = z.object({\n access_token: z.string(),\n refresh_token: z.string().optional(),\n expires_in: z.number(), // in seconds\n token_type: z.string().default(\"Bearer\"),\n id_token: z.string().optional(),\n});\n\nexport type Token = z.infer<typeof TokenSchema>;\n\nexport const ProfileSchema = z.object({\n sub: z.string(), // user ID\n name: z.string().optional(),\n email: z.email({ message: \"Invalid email address\" }).optional(),\n given_name: z.string().optional(),\n family_name: z.string().optional(),\n roles: z.array(z.string()).optional(),\n});\n\nexport type Profile = z.infer<typeof ProfileSchema>;\n\n// Matches IPv4 addresses like 192.168.x.x, 10.x.x.x, 172.16–31.x.x\nconst internalIpRegex =\n /^(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+)?$/;\n\nexport const URLSchema = z.url().refine(\n (url) =>\n url.startsWith(\"https://\") || // normal HTTPS\n /^http:\\/\\/localhost(:\\d+)?$/i.test(url) || // localhost\n internalIpRegex.test(url), // internal LAN IPs\n {\n message:\n \"Only HTTPS, http://localhost, or internal IPs (192.168.x.x, 10.x.x.x, 172.16–31.x.x) are allowed\",\n }\n);","export enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3\n}\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nexport class Logger {\n private static level: LogLevel = LogLevel.WARN;\n private static prefix = '[CAMS-SDK]';\n private static isTestEnv = typeof process !== 'undefined' && process.env?.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, message, context || '');\n }\n }\n\n static warn(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {\n console.warn(`${Logger.prefix} WARN:`, message, context || '');\n }\n }\n\n static info(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {\n console.info(`${Logger.prefix} INFO:`, message, context || '');\n }\n }\n\n static debug(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {\n console.debug(`${Logger.prefix} DEBUG:`, message, context || '');\n }\n }\n}","import { CAMSConfig, CAMSTokenResponse, CAMSError, CAMSErrorType } from \"./types\";\nimport { TokenMessageSchema, ErrorMessageSchema, URLSchema } from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\nexport function validateConfig(config: CAMSConfig): void {\n // Validate URL format\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'Invalid CAMS URL format');\n }\n\n // Domain validation is mandatory for security\n if (!config.allowedDomains?.length) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');\n }\n\n const url = new URL(config.camsUrl); // URLSchema already validated this\n const isAllowed = config.allowedDomains.some(domain => \n url.hostname === domain || url.hostname.endsWith('.' + domain)\n );\n if (!isAllowed) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'URL not in allowed domains list');\n }\n}\n\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<CAMSTokenResponse> {\n return new Promise((resolve, reject) => {\n if (config.debug) Logger.setLevel(LogLevel.DEBUG);\n \n Logger.info('Starting CAMS authentication', { url: config.camsUrl });\n \n try {\n validateConfig(config);\n Logger.debug('Config validation passed');\n } catch (error) {\n Logger.error('Config validation failed', { error: error instanceof Error ? error.message : 'Unknown error' });\n reject(error as Error);\n return;\n }\n\n const { camsUrl, allowedOrigin, windowHeight, windowWidth, timeout = 300000 } = config;\n let authWindow: Window | null;\n let timeoutId: NodeJS.Timeout | null = null;\n let checkClosedInterval: NodeJS.Timeout | null = null;\n \n try {\n Logger.debug('Opening popup window', { width: windowWidth, height: windowHeight });\n authWindow = window.open(\n camsUrl,\n \"NIBSS CAMS Login\",\n `width=${windowWidth},height=${windowHeight}`\n );\n } catch (error) {\n Logger.error('Failed to open popup window', { error: error instanceof Error ? error.message : 'Unknown error' });\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to open authentication window: \" + (error instanceof Error ? error.message : \"Unknown error\")));\n return;\n }\n\n if (!authWindow) {\n Logger.error('Popup window blocked');\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to open authentication window. Please allow popups.\"));\n return;\n }\n \n Logger.debug('Popup window opened successfully');\n\n const cleanup = () => {\n window.removeEventListener(\"message\", listener);\n if (timeoutId) clearTimeout(timeoutId);\n if (checkClosedInterval) clearInterval(checkClosedInterval);\n };\n \n const cleanupAndClose = (error?: CAMSError) => {\n cleanup();\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.close();\n }\n } catch {\n // Ignore close errors\n }\n if (error) reject(error);\n };\n\n const listener = (event: MessageEvent) => {\n Logger.debug('Received message', { origin: event.origin, expectedOrigin: allowedOrigin, data: event.data });\n \n if (event.origin !== allowedOrigin) {\n Logger.warn('Blocked message from unauthorized origin', { origin: event.origin, expected: allowedOrigin });\n return;\n }\n\n // ✅ Validate payload\n const tokenMsg = TokenMessageSchema.safeParse(event.data);\n if (tokenMsg.success) {\n Logger.info('Authentication successful');\n cleanupAndClose();\n resolve({ token: tokenMsg.data.access_token });\n return;\n }\n\n const errorMsg = ErrorMessageSchema.safeParse(event.data);\n if (errorMsg.success) {\n Logger.warn('Authentication error received', { error: errorMsg.data.error });\n cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, \"Authentication failed: \" + errorMsg.data.error));\n return;\n }\n\n Logger.error('Invalid message format received', { \n messageData: event.data, \n dataType: typeof event.data,\n tokenValidationError: tokenMsg.error?.issues,\n errorValidationError: errorMsg.error?.issues\n });\n cleanupAndClose(new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\"));\n };\n\n // Timeout handler\n Logger.debug('Setting timeout', { timeout });\n timeoutId = setTimeout(() => {\n Logger.warn('Authentication timeout', { timeout });\n cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));\n }, timeout);\n\n checkClosedInterval = setInterval(() => {\n if (authWindow && authWindow.closed) {\n Logger.info('Authentication window closed by user');\n cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, \"Authentication window was closed\"));\n }\n }, 2000); // Reduced polling frequency\n\n try {\n window.addEventListener(\"message\", listener);\n } catch (error) {\n cleanup();\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to set up message listener: \" + (error instanceof Error ? error.message : \"Unknown error\")));\n return;\n }\n });\n}\n","import { TokenMessageSchema } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport class TokenManager {\n private token: string | null = null;\n private readonly storageKey: string;\n\n constructor(\n private readonly storage: Storage = sessionStorage,\n storageKey?: string\n ) {\n this.storageKey = storageKey || \"cams_token\";\n }\n\n setToken(token: string) {\n const parsed = TokenMessageSchema.parse(token);\n this.storage.setItem(this.storageKey, parsed.access_token);\n\n Logger.debug(\"Token stored\", { storageKey: this.storageKey });\n }\n\n loadToken(): string | null {\n if (this.token) return this.token;\n const raw = this.storage.getItem(this.storageKey);\n if (!raw) return null;\n\n try {\n this.token = TokenMessageSchema.parse(raw).access_token;\n Logger.debug(\"Token loaded from storage\");\n return this.token;\n } catch (validationError) {\n Logger.warn(\"Token validation failed\", {\n error:\n validationError instanceof Error\n ? validationError.message\n : \"Unknown error\",\n });\n this.storage.removeItem(this.storageKey);\n return null;\n }\n }\n\n clearToken() {\n this.token = null;\n this.storage.removeItem(this.storageKey);\n Logger.debug(\"Token cleared\");\n }\n\n getAccessToken(): string | null {\n const token = this.loadToken();\n return token;\n }\n\n isExpired(): boolean {\n const token = this.loadToken();\n if (!token) return true;\n\n // JWT expiration check if available\n if (token) {\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const payload = JSON.parse(atob(parts[1]));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n // Fallback: return true for safety when expiration cannot be determined\n return true;\n }\n}\n","import { CAMSConfig, CAMSTokenResponse, CAMSError, CAMSErrorType } from \"./types\";\nimport { TokenManager } from \"./tokenManager\";\nimport { openCAMSPopUpLogin } from \"./auth\";\nimport { Profile, ProfileSchema } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (token: CAMSTokenResponse) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSession {\n private readonly tokenManager: TokenManager;\n private readonly events: CAMSEvents;\n\n constructor(\n storage: Storage = sessionStorage,\n storageKey?: string,\n events: CAMSEvents = {}\n ) {\n this.tokenManager = new TokenManager(storage, storageKey);\n this.events = events;\n }\n\n async login(config: CAMSConfig): Promise<CAMSTokenResponse> {\n try {\n Logger.info('Session login started');\n this.events.onAuthStart && this.events.onAuthStart();\n \n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n Logger.debug('Login retry configuration', { maxAttempts });\n \n while (attempts < maxAttempts) {\n try {\n attempts++;\n Logger.debug('Login attempt', { attempt: attempts, maxAttempts });\n const response = await openCAMSPopUpLogin(config);\n Logger.info('Session login successful');\n this.events.onAuthSuccess && this.events.onAuthSuccess(response);\n return response;\n } catch (error) {\n Logger.warn('Login attempt failed', { attempt: attempts, error: error instanceof Error ? error.message : 'Unknown error' });\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {\n throw error;\n }\n Logger.info('Retrying login', { nextAttempt: attempts + 1 });\n }\n }\n \n throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, 'Max retry attempts exceeded');\n } catch (error) {\n const camsError = error instanceof CAMSError ? error : \n new CAMSError(CAMSErrorType.USER_CANCELLED, error instanceof Error ? error.message : 'Unknown error');\n Logger.error('Session login failed', { error: camsError.message, type: camsError.type });\n this.events.onAuthError && this.events.onAuthError(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n Logger.info('Session logout');\n this.tokenManager.clearToken();\n }\n\n isAuthenticated(): boolean {\n const token = this.tokenManager.loadToken();\n if (!token) {\n Logger.debug('No token found');\n return false;\n }\n \n if (this.tokenManager.isExpired()) {\n Logger.info('Token expired');\n this.events.onTokenExpired?.();\n return false;\n }\n \n Logger.debug('Token is valid');\n return true;\n }\n\n getAccessToken(): string | null {\n const token = this.tokenManager.loadToken();\n if (!token) return null;\n \n if (this.tokenManager.isExpired()) {\n this.events.onTokenExpired?.();\n return null;\n }\n \n return token;\n }\n\n private decodeBase64Url(str: string): string {\n // Convert base64url to base64\n str = str.replace(/-/g, '+').replace(/_/g, '/');\n // Add padding if needed\n while (str.length % 4) {\n str += '=';\n }\n return atob(str);\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.tokenManager.loadToken();\n if (!storedToken) return null;\n\n try {\n const parts = storedToken.split('.');\n if (parts.length >= 3) { // JWT has header.payload.signature format\n try {\n const payload = JSON.parse(this.decodeBase64Url(parts[1]));\n return ProfileSchema.parse(payload);\n } catch (decodeError) {\n Logger.warn('Failed to decode JWT payload', { error: decodeError instanceof Error ? decodeError.message : 'Unknown error' });\n }\n }\n } catch (error) {\n Logger.warn('Failed to extract profile from token', { error: error instanceof Error ? error.message : 'Unknown error' });\n }\n\n return null;\n }\n}"],"names":["CAMSErrorType","z","LogLevel"],"mappings":";;;;AAYYA;AAAZ,CAAA,UAAY,aAAa,EAAA;AACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;AAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAA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AE,YAAA,OAAO,IAAI;AAE7B,QAAA,IAAI;YACF,MAAM,KAAK,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC;YACpC,IAAI,KAAK,CAAC,MAAM,IAAI,CAAC,EAAE;AACrB,gBAAA,IAAI;AACF,oBAAA,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;AAC1D,oBAAA,OAAO,aAAa,CAAC,KAAK,CAAC,OAAO,CAAC;gBACrC;gBAAE,OAAO,WAAW,EAAE;oBACpB,MAAM,CAAC,IAAI,CAAC,8BAA8B,EAAE,EAAE,KAAK,EAAE,WAAW,YAAY,KAAK,GAAG,WAAW,CAAC,OAAO,GAAG,eAAe,EAAE,CAAC;gBAC9H;YACF;QACF;QAAE,OAAO,KAAK,EAAE;YACd,MAAM,CAAC,IAAI,CAAC,sCAAsC,EAAE,EAAE,KAAK,EAAE,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,eAAe,EAAE,CAAC;QAC1H;AAEA,QAAA,OAAO,IAAI;IACb;AACD;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/types.ts","../src/validators.ts","../src/logger.ts","../src/auth.ts","../src/tokenManager.ts","../src/session.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n allowedOrigin: string;\n windowWidth: number;\n windowHeight: number;\n timeout?: number; // Auth timeout in ms (default: 300000)\n allowedDomains?: string[]; // URL allowlist for security\n storageKey?: string; // Custom storage key\n retryAttempts?: number; // Auto-retry on failure (default: 0)\n debug?: boolean; // Enable debug logging (default: false)\n}\n\nexport enum CAMSErrorType {\n POPUP_BLOCKED = 'POPUP_BLOCKED',\n TIMEOUT = 'TIMEOUT',\n INVALID_ORIGIN = 'INVALID_ORIGIN',\n USER_CANCELLED = 'USER_CANCELLED',\n INVALID_URL = 'INVALID_URL',\n MAX_RETRIES_EXCEEDED = 'MAX_RETRIES_EXCEEDED'\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = 'CAMSError';\n }\n}\n\nexport interface CAMSTokenResponse {\n token: string;\n}\n\nexport interface CAMSErrorResponse {\n error: string;\n}\n","import { z } from \"zod\";\n\n// Validate the returned token - Base64 format with minimum 20 chars\nexport const TokenMessageSchema = z.object({\n type: z.literal(\"AUTH_SUCCESS\"),\n accessToken: z.string().min(1, \"Access token cannot be empty\"),\n user: z.object({\n name: z.string(),\n image: z.string().nullable(),\n }).optional(),\n});\n\nexport type TokenMessage = z.infer<typeof TokenMessageSchema>;\n\nexport const ErrorMessageSchema = z.object({\n error: z.string().min(1, \"Error message cannot be empty\"),\n});\n\nexport const TokenSchema = z.object({\n access_token: z.string(),\n refresh_token: z.string().optional(),\n expires_in: z.number(), // in seconds\n token_type: z.string().default(\"Bearer\"),\n id_token: z.string().optional(),\n});\n\nexport type Token = z.infer<typeof TokenSchema>;\n\nexport const ProfileSchema = z.object({\n sub: z.string(), // user ID\n name: z.string().optional(),\n email: z.email({ message: \"Invalid email address\" }).optional(),\n given_name: z.string().optional(),\n family_name: z.string().optional(),\n roles: z.array(z.string()).optional(),\n});\n\nexport type Profile = z.infer<typeof ProfileSchema>;\n\n// Matches IPv4 addresses like 192.168.x.x, 10.x.x.x, 172.16–31.x.x\nconst internalIpRegex =\n /^(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+)?$/;\n\nexport const URLSchema = z.url().refine(\n (url) =>\n url.startsWith(\"https://\") || // normal HTTPS\n /^http:\\/\\/localhost(:\\d+)?$/i.test(url) || // localhost\n internalIpRegex.test(url), // internal LAN IPs\n {\n message:\n \"Only HTTPS, http://localhost, or internal IPs (192.168.x.x, 10.x.x.x, 172.16–31.x.x) are allowed\",\n }\n);","export enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3\n}\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nexport class Logger {\n private static level: LogLevel = LogLevel.WARN;\n private static prefix = '[CAMS-SDK]';\n private static isTestEnv = typeof process !== 'undefined' && process.env?.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, message, context || '');\n }\n }\n\n static warn(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {\n console.warn(`${Logger.prefix} WARN:`, message, context || '');\n }\n }\n\n static info(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {\n console.info(`${Logger.prefix} INFO:`, message, context || '');\n }\n }\n\n static debug(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {\n console.debug(`${Logger.prefix} DEBUG:`, message, context || '');\n }\n }\n}","import { CAMSConfig, CAMSTokenResponse, CAMSError, CAMSErrorType } from \"./types\";\nimport { TokenMessageSchema, ErrorMessageSchema, URLSchema } from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\nexport function validateConfig(config: CAMSConfig): void {\n // Validate URL format\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'Invalid CAMS URL format');\n }\n\n // Domain validation is mandatory for security\n if (!config.allowedDomains?.length) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');\n }\n\n const url = new URL(config.camsUrl); // URLSchema already validated this\n const isAllowed = config.allowedDomains.some(domain => \n url.hostname === domain || url.hostname.endsWith('.' + domain)\n );\n if (!isAllowed) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'URL not in allowed domains list');\n }\n}\n\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<CAMSTokenResponse> {\n return new Promise((resolve, reject) => {\n if (config.debug) Logger.setLevel(LogLevel.DEBUG);\n \n Logger.info('Starting CAMS authentication', { url: config.camsUrl });\n \n try {\n validateConfig(config);\n Logger.debug('Config validation passed');\n } catch (error) {\n Logger.error('Config validation failed', { error: error instanceof Error ? error.message : 'Unknown error' });\n reject(error as Error);\n return;\n }\n\n const { camsUrl, allowedOrigin, windowHeight, windowWidth, timeout = 300000 } = config;\n let authWindow: Window | null;\n let timeoutId: NodeJS.Timeout | null = null;\n let checkClosedInterval: NodeJS.Timeout | null = null;\n \n try {\n Logger.debug('Opening popup window', { width: windowWidth, height: windowHeight });\n authWindow = window.open(\n camsUrl,\n \"NIBSS CAMS Login\",\n `width=${windowWidth},height=${windowHeight}`\n );\n } catch (error) {\n Logger.error('Failed to open popup window', { error: error instanceof Error ? error.message : 'Unknown error' });\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to open authentication window: \" + (error instanceof Error ? error.message : \"Unknown error\")));\n return;\n }\n\n if (!authWindow) {\n Logger.error('Popup window blocked');\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to open authentication window. Please allow popups.\"));\n return;\n }\n \n Logger.debug('Popup window opened successfully');\n\n const cleanup = () => {\n window.removeEventListener(\"message\", listener);\n if (timeoutId) clearTimeout(timeoutId);\n if (checkClosedInterval) clearInterval(checkClosedInterval);\n };\n \n const cleanupAndClose = (error?: CAMSError) => {\n cleanup();\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.close();\n }\n } catch {\n // Ignore close errors\n }\n if (error) reject(error);\n };\n\n const listener = (event: MessageEvent) => {\n Logger.debug('Received message', { origin: event.origin, expectedOrigin: allowedOrigin, data: event.data });\n \n if (event.origin !== allowedOrigin) {\n Logger.warn('Blocked message from unauthorized origin', { origin: event.origin, expected: allowedOrigin });\n return;\n }\n\n // ✅ Validate payload\n const tokenMsg = TokenMessageSchema.safeParse(event.data);\n if (tokenMsg.success) {\n Logger.info('Authentication successful');\n cleanupAndClose();\n resolve({ token: tokenMsg.data.accessToken });\n return;\n }\n\n const errorMsg = ErrorMessageSchema.safeParse(event.data);\n if (errorMsg.success) {\n Logger.warn('Authentication error received', { error: errorMsg.data.error });\n cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, \"Authentication failed: \" + errorMsg.data.error));\n return;\n }\n\n Logger.error('Invalid message format received', { \n messageData: event.data, \n dataType: typeof event.data,\n tokenValidationError: tokenMsg.error?.issues,\n errorValidationError: errorMsg.error?.issues\n });\n cleanupAndClose(new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\"));\n };\n\n // Timeout handler\n Logger.debug('Setting timeout', { timeout });\n timeoutId = setTimeout(() => {\n Logger.warn('Authentication timeout', { timeout });\n cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));\n }, timeout);\n\n checkClosedInterval = setInterval(() => {\n if (authWindow?.closed) {\n Logger.info('Authentication window closed by user');\n cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, \"Authentication window was closed\"));\n }\n }, 2000); // Reduced polling frequency\n\n try {\n window.addEventListener(\"message\", listener);\n } catch (error) {\n cleanup();\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to set up message listener: \" + (error instanceof Error ? error.message : \"Unknown error\")));\n return;\n }\n });\n}\n","import { Logger } from \"./logger\";\n\nexport class TokenManager {\n private token: string | null = null;\n private readonly storageKey: string;\n\n constructor(\n private readonly storage: Storage = sessionStorage,\n storageKey?: string\n ) {\n this.storageKey = storageKey || \"cams_token\";\n }\n\n setToken(token: string) {\n this.token = token;\n this.storage.setItem(this.storageKey, token);\n Logger.debug(\"Token stored\", { storageKey: this.storageKey });\n }\n\n loadToken(): string | null {\n if (this.token) return this.token;\n const raw = this.storage.getItem(this.storageKey);\n if (!raw) return null;\n \n this.token = raw;\n Logger.debug(\"Token loaded from storage\");\n return this.token;\n }\n\n clearToken() {\n this.token = null;\n this.storage.removeItem(this.storageKey);\n Logger.debug(\"Token cleared\");\n }\n\n getAccessToken(): string | null {\n const token = this.loadToken();\n return token;\n }\n\n isExpired(): boolean {\n const token = this.loadToken();\n if (!token) return true;\n\n // JWT expiration check if available\n if (token) {\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const payload = JSON.parse(atob(parts[1]));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n // Fallback: return true for safety when expiration cannot be determined\n return true;\n }\n}\n","import { CAMSConfig, CAMSTokenResponse, CAMSError, CAMSErrorType } from \"./types\";\nimport { TokenManager } from \"./tokenManager\";\nimport { openCAMSPopUpLogin } from \"./auth\";\nimport { Profile, ProfileSchema } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (token: CAMSTokenResponse) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSessionManager {\n private readonly tokenManager: TokenManager;\n private readonly events: CAMSEvents;\n\n constructor(\n storage: Storage = sessionStorage,\n storageKey?: string,\n events: CAMSEvents = {}\n ) {\n this.tokenManager = new TokenManager(storage, storageKey);\n this.events = events;\n }\n\n async login(config: CAMSConfig): Promise<CAMSTokenResponse> {\n try {\n Logger.info('Session login started');\n this.events.onAuthStart && this.events.onAuthStart();\n \n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n Logger.debug('Login retry configuration', { maxAttempts });\n \n while (attempts < maxAttempts) {\n try {\n attempts++;\n Logger.debug('Login attempt', { attempt: attempts, maxAttempts });\n const response = await openCAMSPopUpLogin(config);\n this.tokenManager.setToken(response.token);\n Logger.info('Session login successful');\n this.events.onAuthSuccess && this.events.onAuthSuccess(response);\n return response;\n } catch (error) {\n Logger.warn('Login attempt failed', { attempt: attempts, error: error instanceof Error ? error.message : 'Unknown error' });\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {\n throw error;\n }\n Logger.info('Retrying login', { nextAttempt: attempts + 1 });\n }\n }\n \n throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, 'Max retry attempts exceeded');\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n const camsError = error instanceof CAMSError ? error : \n new CAMSError(CAMSErrorType.USER_CANCELLED, errorMessage);\n Logger.error('Session login failed', { error: camsError.message, type: camsError.type });\n this.events.onAuthError && this.events.onAuthError(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n Logger.info('Session logout');\n this.tokenManager.clearToken();\n }\n\n isAuthenticated(): boolean {\n const token = this.tokenManager.loadToken();\n if (!token) {\n Logger.debug('No token found');\n return false;\n }\n \n if (this.tokenManager.isExpired()) {\n Logger.info('Token expired');\n this.events.onTokenExpired?.();\n return false;\n }\n \n Logger.debug('Token is valid');\n return true;\n }\n\n getAccessToken(): string | null {\n const token = this.tokenManager.loadToken();\n if (!token) return null;\n \n if (this.tokenManager.isExpired()) {\n this.events.onTokenExpired?.();\n return null;\n }\n \n return token;\n }\n\n private decodeBase64Url(str: string): string {\n // Convert base64url to base64\n str = str.replace(/-/g, '+').replace(/_/g, '/');\n // Add padding if needed\n while (str.length % 4) {\n str += '=';\n }\n return atob(str);\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.tokenManager.loadToken();\n if (!storedToken) return null;\n\n try {\n const parts = storedToken.split('.');\n if (parts.length >= 3) { // JWT has header.payload.signature format\n try {\n const payload = JSON.parse(this.decodeBase64Url(parts[1]));\n return ProfileSchema.parse(payload);\n } catch (decodeError) {\n Logger.warn('Failed to decode JWT payload', { error: decodeError instanceof Error ? decodeError.message : 'Unknown error' });\n }\n }\n } catch (error) {\n Logger.warn('Failed to extract profile from token', { error: error instanceof Error ? error.message : 'Unknown error' });\n }\n\n return null;\n }\n}"],"names":["CAMSErrorType","z","LogLevel"],"mappings":";;;;AAYYA;AAAZ,CAAA,UAAY,aAAa,EAAA;AACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;AAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;AAC3B,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC/C,CAAC,EAPWA,qBAAa,KAAbA,qBAAa,GAAA,EAAA,CAAA,CAAA;AASnB,MAAO,SAAU,SAAQ,KAAK,CAAA;IAClC,WAAA,CAAmB,IAAmB,EAAE,OAAe,EAAA;QACrD,KAAK,CAAC,OAAO,CAAC;QADG,IAAA,CAAA,IAAI,GAAJ,IAAI;AAErB,QAAA,IAAI,CAAC,IAAI,GAAG,WAAW;IACzB;AACD;;ACxBD;AACO,MAAM,kBAAkB,GAAGC,KAAC,CAAC,MAAM,CAAC;AACzC,IAAA,IAAI,EAAEA,KAAC,CAAC,OAAO,CAAC,cAAc,CAAC;IAC/B,WAAW,EAAEA,KAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,8BAA8B,CAAC;AAC9D,IAAA,IAAI,EAAEA,KAAC,CAAC,MAAM,CAAC;AACb,QAAA,IAAI,EAAEA,KAAC,CAAC,MAAM,EAAE;AAChB,QAAA,KAAK,EAAEA,KAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;KAC7B,CAAC,CAAC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20
|
// Validate the returned token - Base64 format with minimum 20 chars
|
|
21
21
|
const TokenMessageSchema = z.object({
|
|
22
|
-
|
|
22
|
+
type: z.literal("AUTH_SUCCESS"),
|
|
23
|
+
accessToken: z.string().min(1, "Access token cannot be empty"),
|
|
24
|
+
user: z.object({
|
|
25
|
+
name: z.string(),
|
|
26
|
+
image: z.string().nullable(),
|
|
27
|
+
}).optional(),
|
|
23
28
|
});
|
|
24
29
|
const ErrorMessageSchema = z.object({
|
|
25
30
|
error: z.string().min(1, "Error message cannot be empty"),
|
|
@@ -164,7 +169,7 @@ function openCAMSPopUpLogin(config) {
|
|
|
164
169
|
if (tokenMsg.success) {
|
|
165
170
|
Logger.info('Authentication successful');
|
|
166
171
|
cleanupAndClose();
|
|
167
|
-
resolve({ token: tokenMsg.data.
|
|
172
|
+
resolve({ token: tokenMsg.data.accessToken });
|
|
168
173
|
return;
|
|
169
174
|
}
|
|
170
175
|
const errorMsg = ErrorMessageSchema.safeParse(event.data);
|
|
@@ -188,7 +193,7 @@ function openCAMSPopUpLogin(config) {
|
|
|
188
193
|
cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));
|
|
189
194
|
}, timeout);
|
|
190
195
|
checkClosedInterval = setInterval(() => {
|
|
191
|
-
if (authWindow
|
|
196
|
+
if (authWindow?.closed) {
|
|
192
197
|
Logger.info('Authentication window closed by user');
|
|
193
198
|
cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
|
|
194
199
|
}
|
|
@@ -211,8 +216,8 @@ class TokenManager {
|
|
|
211
216
|
this.storageKey = storageKey || "cams_token";
|
|
212
217
|
}
|
|
213
218
|
setToken(token) {
|
|
214
|
-
|
|
215
|
-
this.storage.setItem(this.storageKey,
|
|
219
|
+
this.token = token;
|
|
220
|
+
this.storage.setItem(this.storageKey, token);
|
|
216
221
|
Logger.debug("Token stored", { storageKey: this.storageKey });
|
|
217
222
|
}
|
|
218
223
|
loadToken() {
|
|
@@ -221,20 +226,9 @@ class TokenManager {
|
|
|
221
226
|
const raw = this.storage.getItem(this.storageKey);
|
|
222
227
|
if (!raw)
|
|
223
228
|
return null;
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
return this.token;
|
|
228
|
-
}
|
|
229
|
-
catch (validationError) {
|
|
230
|
-
Logger.warn("Token validation failed", {
|
|
231
|
-
error: validationError instanceof Error
|
|
232
|
-
? validationError.message
|
|
233
|
-
: "Unknown error",
|
|
234
|
-
});
|
|
235
|
-
this.storage.removeItem(this.storageKey);
|
|
236
|
-
return null;
|
|
237
|
-
}
|
|
229
|
+
this.token = raw;
|
|
230
|
+
Logger.debug("Token loaded from storage");
|
|
231
|
+
return this.token;
|
|
238
232
|
}
|
|
239
233
|
clearToken() {
|
|
240
234
|
this.token = null;
|
|
@@ -273,7 +267,7 @@ class TokenManager {
|
|
|
273
267
|
}
|
|
274
268
|
}
|
|
275
269
|
|
|
276
|
-
class
|
|
270
|
+
class CAMSSessionManager {
|
|
277
271
|
constructor(storage = sessionStorage, storageKey, events = {}) {
|
|
278
272
|
this.tokenManager = new TokenManager(storage, storageKey);
|
|
279
273
|
this.events = events;
|
|
@@ -290,6 +284,7 @@ class CAMSSession {
|
|
|
290
284
|
attempts++;
|
|
291
285
|
Logger.debug('Login attempt', { attempt: attempts, maxAttempts });
|
|
292
286
|
const response = await openCAMSPopUpLogin(config);
|
|
287
|
+
this.tokenManager.setToken(response.token);
|
|
293
288
|
Logger.info('Session login successful');
|
|
294
289
|
this.events.onAuthSuccess && this.events.onAuthSuccess(response);
|
|
295
290
|
return response;
|
|
@@ -309,8 +304,9 @@ class CAMSSession {
|
|
|
309
304
|
throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, 'Max retry attempts exceeded');
|
|
310
305
|
}
|
|
311
306
|
catch (error) {
|
|
307
|
+
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
312
308
|
const camsError = error instanceof CAMSError ? error :
|
|
313
|
-
new CAMSError(CAMSErrorType.USER_CANCELLED,
|
|
309
|
+
new CAMSError(CAMSErrorType.USER_CANCELLED, errorMessage);
|
|
314
310
|
Logger.error('Session login failed', { error: camsError.message, type: camsError.type });
|
|
315
311
|
this.events.onAuthError && this.events.onAuthError(camsError);
|
|
316
312
|
throw camsError;
|
|
@@ -376,5 +372,5 @@ class CAMSSession {
|
|
|
376
372
|
}
|
|
377
373
|
}
|
|
378
374
|
|
|
379
|
-
export { CAMSError, CAMSErrorType,
|
|
375
|
+
export { CAMSError, CAMSErrorType, CAMSSessionManager, ErrorMessageSchema, LogLevel, Logger, ProfileSchema, TokenManager, TokenMessageSchema, TokenSchema, URLSchema, openCAMSPopUpLogin, validateConfig };
|
|
380
376
|
//# sourceMappingURL=index.esm.js.map
|
package/dist/index.esm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.js","sources":["../src/types.ts","../src/validators.ts","../src/logger.ts","../src/auth.ts","../src/tokenManager.ts","../src/session.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n allowedOrigin: string;\n windowWidth: number;\n windowHeight: number;\n timeout?: number; // Auth timeout in ms (default: 300000)\n allowedDomains?: string[]; // URL allowlist for security\n storageKey?: string; // Custom storage key\n retryAttempts?: number; // Auto-retry on failure (default: 0)\n debug?: boolean; // Enable debug logging (default: false)\n}\n\nexport enum CAMSErrorType {\n POPUP_BLOCKED = 'POPUP_BLOCKED',\n TIMEOUT = 'TIMEOUT',\n INVALID_ORIGIN = 'INVALID_ORIGIN',\n USER_CANCELLED = 'USER_CANCELLED',\n INVALID_URL = 'INVALID_URL',\n MAX_RETRIES_EXCEEDED = 'MAX_RETRIES_EXCEEDED'\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = 'CAMSError';\n }\n}\n\nexport interface CAMSTokenResponse {\n token: string;\n}\n\nexport interface CAMSErrorResponse {\n error: string;\n}\n","import { z } from \"zod\";\n\n// Validate the returned token - Base64 format with minimum 20 chars\nexport const TokenMessageSchema = z.object({\n access_token: z.string().min(1, \"NIBSS CAMS Access token cannot be empty\"),\n});\n\nexport type TokenMessage = z.infer<typeof TokenMessageSchema>;\n\nexport const ErrorMessageSchema = z.object({\n error: z.string().min(1, \"Error message cannot be empty\"),\n});\n\nexport const TokenSchema = z.object({\n access_token: z.string(),\n refresh_token: z.string().optional(),\n expires_in: z.number(), // in seconds\n token_type: z.string().default(\"Bearer\"),\n id_token: z.string().optional(),\n});\n\nexport type Token = z.infer<typeof TokenSchema>;\n\nexport const ProfileSchema = z.object({\n sub: z.string(), // user ID\n name: z.string().optional(),\n email: z.email({ message: \"Invalid email address\" }).optional(),\n given_name: z.string().optional(),\n family_name: z.string().optional(),\n roles: z.array(z.string()).optional(),\n});\n\nexport type Profile = z.infer<typeof ProfileSchema>;\n\n// Matches IPv4 addresses like 192.168.x.x, 10.x.x.x, 172.16–31.x.x\nconst internalIpRegex =\n /^(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+)?$/;\n\nexport const URLSchema = z.url().refine(\n (url) =>\n url.startsWith(\"https://\") || // normal HTTPS\n /^http:\\/\\/localhost(:\\d+)?$/i.test(url) || // localhost\n internalIpRegex.test(url), // internal LAN IPs\n {\n message:\n \"Only HTTPS, http://localhost, or internal IPs (192.168.x.x, 10.x.x.x, 172.16–31.x.x) are allowed\",\n }\n);","export enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3\n}\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nexport class Logger {\n private static level: LogLevel = LogLevel.WARN;\n private static prefix = '[CAMS-SDK]';\n private static isTestEnv = typeof process !== 'undefined' && process.env?.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, message, context || '');\n }\n }\n\n static warn(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {\n console.warn(`${Logger.prefix} WARN:`, message, context || '');\n }\n }\n\n static info(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {\n console.info(`${Logger.prefix} INFO:`, message, context || '');\n }\n }\n\n static debug(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {\n console.debug(`${Logger.prefix} DEBUG:`, message, context || '');\n }\n }\n}","import { CAMSConfig, CAMSTokenResponse, CAMSError, CAMSErrorType } from \"./types\";\nimport { TokenMessageSchema, ErrorMessageSchema, URLSchema } from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\nexport function validateConfig(config: CAMSConfig): void {\n // Validate URL format\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'Invalid CAMS URL format');\n }\n\n // Domain validation is mandatory for security\n if (!config.allowedDomains?.length) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');\n }\n\n const url = new URL(config.camsUrl); // URLSchema already validated this\n const isAllowed = config.allowedDomains.some(domain => \n url.hostname === domain || url.hostname.endsWith('.' + domain)\n );\n if (!isAllowed) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'URL not in allowed domains list');\n }\n}\n\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<CAMSTokenResponse> {\n return new Promise((resolve, reject) => {\n if (config.debug) Logger.setLevel(LogLevel.DEBUG);\n \n Logger.info('Starting CAMS authentication', { url: config.camsUrl });\n \n try {\n validateConfig(config);\n Logger.debug('Config validation passed');\n } catch (error) {\n Logger.error('Config validation failed', { error: error instanceof Error ? error.message : 'Unknown error' });\n reject(error as Error);\n return;\n }\n\n const { camsUrl, allowedOrigin, windowHeight, windowWidth, timeout = 300000 } = config;\n let authWindow: Window | null;\n let timeoutId: NodeJS.Timeout | null = null;\n let checkClosedInterval: NodeJS.Timeout | null = null;\n \n try {\n Logger.debug('Opening popup window', { width: windowWidth, height: windowHeight });\n authWindow = window.open(\n camsUrl,\n \"NIBSS CAMS Login\",\n `width=${windowWidth},height=${windowHeight}`\n );\n } catch (error) {\n Logger.error('Failed to open popup window', { error: error instanceof Error ? error.message : 'Unknown error' });\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to open authentication window: \" + (error instanceof Error ? error.message : \"Unknown error\")));\n return;\n }\n\n if (!authWindow) {\n Logger.error('Popup window blocked');\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to open authentication window. Please allow popups.\"));\n return;\n }\n \n Logger.debug('Popup window opened successfully');\n\n const cleanup = () => {\n window.removeEventListener(\"message\", listener);\n if (timeoutId) clearTimeout(timeoutId);\n if (checkClosedInterval) clearInterval(checkClosedInterval);\n };\n \n const cleanupAndClose = (error?: CAMSError) => {\n cleanup();\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.close();\n }\n } catch {\n // Ignore close errors\n }\n if (error) reject(error);\n };\n\n const listener = (event: MessageEvent) => {\n Logger.debug('Received message', { origin: event.origin, expectedOrigin: allowedOrigin, data: event.data });\n \n if (event.origin !== allowedOrigin) {\n Logger.warn('Blocked message from unauthorized origin', { origin: event.origin, expected: allowedOrigin });\n return;\n }\n\n // ✅ Validate payload\n const tokenMsg = TokenMessageSchema.safeParse(event.data);\n if (tokenMsg.success) {\n Logger.info('Authentication successful');\n cleanupAndClose();\n resolve({ token: tokenMsg.data.access_token });\n return;\n }\n\n const errorMsg = ErrorMessageSchema.safeParse(event.data);\n if (errorMsg.success) {\n Logger.warn('Authentication error received', { error: errorMsg.data.error });\n cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, \"Authentication failed: \" + errorMsg.data.error));\n return;\n }\n\n Logger.error('Invalid message format received', { \n messageData: event.data, \n dataType: typeof event.data,\n tokenValidationError: tokenMsg.error?.issues,\n errorValidationError: errorMsg.error?.issues\n });\n cleanupAndClose(new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\"));\n };\n\n // Timeout handler\n Logger.debug('Setting timeout', { timeout });\n timeoutId = setTimeout(() => {\n Logger.warn('Authentication timeout', { timeout });\n cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));\n }, timeout);\n\n checkClosedInterval = setInterval(() => {\n if (authWindow && authWindow.closed) {\n Logger.info('Authentication window closed by user');\n cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, \"Authentication window was closed\"));\n }\n }, 2000); // Reduced polling frequency\n\n try {\n window.addEventListener(\"message\", listener);\n } catch (error) {\n cleanup();\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to set up message listener: \" + (error instanceof Error ? error.message : \"Unknown error\")));\n return;\n }\n });\n}\n","import { TokenMessageSchema } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport class TokenManager {\n private token: string | null = null;\n private readonly storageKey: string;\n\n constructor(\n private readonly storage: Storage = sessionStorage,\n storageKey?: string\n ) {\n this.storageKey = storageKey || \"cams_token\";\n }\n\n setToken(token: string) {\n const parsed = TokenMessageSchema.parse(token);\n this.storage.setItem(this.storageKey, parsed.access_token);\n\n Logger.debug(\"Token stored\", { storageKey: this.storageKey });\n }\n\n loadToken(): string | null {\n if (this.token) return this.token;\n const raw = this.storage.getItem(this.storageKey);\n if (!raw) return null;\n\n try {\n this.token = TokenMessageSchema.parse(raw).access_token;\n Logger.debug(\"Token loaded from storage\");\n return this.token;\n } catch (validationError) {\n Logger.warn(\"Token validation failed\", {\n error:\n validationError instanceof Error\n ? validationError.message\n : \"Unknown error\",\n });\n this.storage.removeItem(this.storageKey);\n return null;\n }\n }\n\n clearToken() {\n this.token = null;\n this.storage.removeItem(this.storageKey);\n Logger.debug(\"Token cleared\");\n }\n\n getAccessToken(): string | null {\n const token = this.loadToken();\n return token;\n }\n\n isExpired(): boolean {\n const token = this.loadToken();\n if (!token) return true;\n\n // JWT expiration check if available\n if (token) {\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const payload = JSON.parse(atob(parts[1]));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n // Fallback: return true for safety when expiration cannot be determined\n return true;\n }\n}\n","import { CAMSConfig, CAMSTokenResponse, CAMSError, CAMSErrorType } from \"./types\";\nimport { TokenManager } from \"./tokenManager\";\nimport { openCAMSPopUpLogin } from \"./auth\";\nimport { Profile, ProfileSchema } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (token: CAMSTokenResponse) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSession {\n private readonly tokenManager: TokenManager;\n private readonly events: CAMSEvents;\n\n constructor(\n storage: Storage = sessionStorage,\n storageKey?: string,\n events: CAMSEvents = {}\n ) {\n this.tokenManager = new TokenManager(storage, storageKey);\n this.events = events;\n }\n\n async login(config: CAMSConfig): Promise<CAMSTokenResponse> {\n try {\n Logger.info('Session login started');\n this.events.onAuthStart && this.events.onAuthStart();\n \n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n Logger.debug('Login retry configuration', { maxAttempts });\n \n while (attempts < maxAttempts) {\n try {\n attempts++;\n Logger.debug('Login attempt', { attempt: attempts, maxAttempts });\n const response = await openCAMSPopUpLogin(config);\n Logger.info('Session login successful');\n this.events.onAuthSuccess && this.events.onAuthSuccess(response);\n return response;\n } catch (error) {\n Logger.warn('Login attempt failed', { attempt: attempts, error: error instanceof Error ? error.message : 'Unknown error' });\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {\n throw error;\n }\n Logger.info('Retrying login', { nextAttempt: attempts + 1 });\n }\n }\n \n throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, 'Max retry attempts exceeded');\n } catch (error) {\n const camsError = error instanceof CAMSError ? error : \n new CAMSError(CAMSErrorType.USER_CANCELLED, error instanceof Error ? error.message : 'Unknown error');\n Logger.error('Session login failed', { error: camsError.message, type: camsError.type });\n this.events.onAuthError && this.events.onAuthError(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n Logger.info('Session logout');\n this.tokenManager.clearToken();\n }\n\n isAuthenticated(): boolean {\n const token = this.tokenManager.loadToken();\n if (!token) {\n Logger.debug('No token found');\n return false;\n }\n \n if (this.tokenManager.isExpired()) {\n Logger.info('Token expired');\n this.events.onTokenExpired?.();\n return false;\n }\n \n Logger.debug('Token is valid');\n return true;\n }\n\n getAccessToken(): string | null {\n const token = this.tokenManager.loadToken();\n if (!token) return null;\n \n if (this.tokenManager.isExpired()) {\n this.events.onTokenExpired?.();\n return null;\n }\n \n return token;\n }\n\n private decodeBase64Url(str: string): string {\n // Convert base64url to base64\n str = str.replace(/-/g, '+').replace(/_/g, '/');\n // Add padding if needed\n while (str.length % 4) {\n str += '=';\n }\n return atob(str);\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.tokenManager.loadToken();\n if (!storedToken) return null;\n\n try {\n const parts = storedToken.split('.');\n if (parts.length >= 3) { // JWT has header.payload.signature format\n try {\n const payload = JSON.parse(this.decodeBase64Url(parts[1]));\n return ProfileSchema.parse(payload);\n } catch (decodeError) {\n Logger.warn('Failed to decode JWT payload', { error: decodeError instanceof Error ? decodeError.message : 'Unknown error' });\n }\n }\n } catch (error) {\n Logger.warn('Failed to extract profile from token', { error: error instanceof Error ? error.message : 'Unknown error' });\n }\n\n return null;\n }\n}"],"names":[],"mappings":";;IAYY;AAAZ,CAAA,UAAY,aAAa,EAAA;AACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;AAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;AAC3B,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC/C,CAAC,EAPW,aAAa,KAAb,aAAa,GAAA,EAAA,CAAA,CAAA;AASnB,MAAO,SAAU,SAAQ,KAAK,CAAA;IAClC,WAAA,CAAmB,IAAmB,EAAE,OAAe,EAAA;QACrD,KAAK,CAAC,OAAO,CAAC;QADG,IAAA,CAAA,IAAI,GAAJ,IAAI;AAErB,QAAA,IAAI,CAAC,IAAI,GAAG,WAAW;IACzB;AACD;;ACxBD;AACO,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAC;IACzC,YAAY,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,yCAAyC,CAAC;AAC3E,CAAA;AAIM,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAC;IACzC,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,+BAA+B,CAAC;AAC1D,CAAA;AAEM,MAAM,WAAW,GAAG,CAAC,CAAC,MAAM,CAAC;AAClC,IAAA,YAAY,EAAE,CAAC,CAAC,MAAM,EAAE;AACxB,IAAA,aAAa,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;AACpC,IAAA,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE;IACtB,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,MAAM,GAAG,CAAC,EAAE;YACrB,GAAG,IAAI,GAAG;QACZ;AACA,QAAA,OAAO,IAAI,CAAC,GAAG,CAAC;IAClB;AAEA,IAAA,MAAM,UAAU,GAAA;QACd,MAAM,WAAW,GAAG,IAAI,CAAC,YAAY,CAAC,SAAS,EAAE;AACjD,QAAA,IAAI,CAAC,WAAW;AAAE,YAAA,OAAO,IAAI;AAE7B,QAAA,IAAI;YACF,MAAM,KAAK,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC;YACpC,IAAI,KAAK,CAAC,MAAM,IAAI,CAAC,EAAE;AACrB,gBAAA,IAAI;AACF,oBAAA,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;AAC1D,oBAAA,OAAO,aAAa,CAAC,KAAK,CAAC,OAAO,CAAC;gBACrC;gBAAE,OAAO,WAAW,EAAE;oBACpB,MAAM,CAAC,IAAI,CAAC,8BAA8B,EAAE,EAAE,KAAK,EAAE,WAAW,YAAY,KAAK,GAAG,WAAW,CAAC,OAAO,GAAG,eAAe,EAAE,CAAC;gBAC9H;YACF;QACF;QAAE,OAAO,KAAK,EAAE;YACd,MAAM,CAAC,IAAI,CAAC,sCAAsC,EAAE,EAAE,KAAK,EAAE,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,eAAe,EAAE,CAAC;QAC1H;AAEA,QAAA,OAAO,IAAI;IACb;AACD;;;;"}
|
|
1
|
+
{"version":3,"file":"index.esm.js","sources":["../src/types.ts","../src/validators.ts","../src/logger.ts","../src/auth.ts","../src/tokenManager.ts","../src/session.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n allowedOrigin: string;\n windowWidth: number;\n windowHeight: number;\n timeout?: number; // Auth timeout in ms (default: 300000)\n allowedDomains?: string[]; // URL allowlist for security\n storageKey?: string; // Custom storage key\n retryAttempts?: number; // Auto-retry on failure (default: 0)\n debug?: boolean; // Enable debug logging (default: false)\n}\n\nexport enum CAMSErrorType {\n POPUP_BLOCKED = 'POPUP_BLOCKED',\n TIMEOUT = 'TIMEOUT',\n INVALID_ORIGIN = 'INVALID_ORIGIN',\n USER_CANCELLED = 'USER_CANCELLED',\n INVALID_URL = 'INVALID_URL',\n MAX_RETRIES_EXCEEDED = 'MAX_RETRIES_EXCEEDED'\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = 'CAMSError';\n }\n}\n\nexport interface CAMSTokenResponse {\n token: string;\n}\n\nexport interface CAMSErrorResponse {\n error: string;\n}\n","import { z } from \"zod\";\n\n// Validate the returned token - Base64 format with minimum 20 chars\nexport const TokenMessageSchema = z.object({\n type: z.literal(\"AUTH_SUCCESS\"),\n accessToken: z.string().min(1, \"Access token cannot be empty\"),\n user: z.object({\n name: z.string(),\n image: z.string().nullable(),\n }).optional(),\n});\n\nexport type TokenMessage = z.infer<typeof TokenMessageSchema>;\n\nexport const ErrorMessageSchema = z.object({\n error: z.string().min(1, \"Error message cannot be empty\"),\n});\n\nexport const TokenSchema = z.object({\n access_token: z.string(),\n refresh_token: z.string().optional(),\n expires_in: z.number(), // in seconds\n token_type: z.string().default(\"Bearer\"),\n id_token: z.string().optional(),\n});\n\nexport type Token = z.infer<typeof TokenSchema>;\n\nexport const ProfileSchema = z.object({\n sub: z.string(), // user ID\n name: z.string().optional(),\n email: z.email({ message: \"Invalid email address\" }).optional(),\n given_name: z.string().optional(),\n family_name: z.string().optional(),\n roles: z.array(z.string()).optional(),\n});\n\nexport type Profile = z.infer<typeof ProfileSchema>;\n\n// Matches IPv4 addresses like 192.168.x.x, 10.x.x.x, 172.16–31.x.x\nconst internalIpRegex =\n /^(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+)?$/;\n\nexport const URLSchema = z.url().refine(\n (url) =>\n url.startsWith(\"https://\") || // normal HTTPS\n /^http:\\/\\/localhost(:\\d+)?$/i.test(url) || // localhost\n internalIpRegex.test(url), // internal LAN IPs\n {\n message:\n \"Only HTTPS, http://localhost, or internal IPs (192.168.x.x, 10.x.x.x, 172.16–31.x.x) are allowed\",\n }\n);","export enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3\n}\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nexport class Logger {\n private static level: LogLevel = LogLevel.WARN;\n private static prefix = '[CAMS-SDK]';\n private static isTestEnv = typeof process !== 'undefined' && process.env?.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, message, context || '');\n }\n }\n\n static warn(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {\n console.warn(`${Logger.prefix} WARN:`, message, context || '');\n }\n }\n\n static info(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {\n console.info(`${Logger.prefix} INFO:`, message, context || '');\n }\n }\n\n static debug(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {\n console.debug(`${Logger.prefix} DEBUG:`, message, context || '');\n }\n }\n}","import { CAMSConfig, CAMSTokenResponse, CAMSError, CAMSErrorType } from \"./types\";\nimport { TokenMessageSchema, ErrorMessageSchema, URLSchema } from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\nexport function validateConfig(config: CAMSConfig): void {\n // Validate URL format\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'Invalid CAMS URL format');\n }\n\n // Domain validation is mandatory for security\n if (!config.allowedDomains?.length) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');\n }\n\n const url = new URL(config.camsUrl); // URLSchema already validated this\n const isAllowed = config.allowedDomains.some(domain => \n url.hostname === domain || url.hostname.endsWith('.' + domain)\n );\n if (!isAllowed) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'URL not in allowed domains list');\n }\n}\n\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<CAMSTokenResponse> {\n return new Promise((resolve, reject) => {\n if (config.debug) Logger.setLevel(LogLevel.DEBUG);\n \n Logger.info('Starting CAMS authentication', { url: config.camsUrl });\n \n try {\n validateConfig(config);\n Logger.debug('Config validation passed');\n } catch (error) {\n Logger.error('Config validation failed', { error: error instanceof Error ? error.message : 'Unknown error' });\n reject(error as Error);\n return;\n }\n\n const { camsUrl, allowedOrigin, windowHeight, windowWidth, timeout = 300000 } = config;\n let authWindow: Window | null;\n let timeoutId: NodeJS.Timeout | null = null;\n let checkClosedInterval: NodeJS.Timeout | null = null;\n \n try {\n Logger.debug('Opening popup window', { width: windowWidth, height: windowHeight });\n authWindow = window.open(\n camsUrl,\n \"NIBSS CAMS Login\",\n `width=${windowWidth},height=${windowHeight}`\n );\n } catch (error) {\n Logger.error('Failed to open popup window', { error: error instanceof Error ? error.message : 'Unknown error' });\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to open authentication window: \" + (error instanceof Error ? error.message : \"Unknown error\")));\n return;\n }\n\n if (!authWindow) {\n Logger.error('Popup window blocked');\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to open authentication window. Please allow popups.\"));\n return;\n }\n \n Logger.debug('Popup window opened successfully');\n\n const cleanup = () => {\n window.removeEventListener(\"message\", listener);\n if (timeoutId) clearTimeout(timeoutId);\n if (checkClosedInterval) clearInterval(checkClosedInterval);\n };\n \n const cleanupAndClose = (error?: CAMSError) => {\n cleanup();\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.close();\n }\n } catch {\n // Ignore close errors\n }\n if (error) reject(error);\n };\n\n const listener = (event: MessageEvent) => {\n Logger.debug('Received message', { origin: event.origin, expectedOrigin: allowedOrigin, data: event.data });\n \n if (event.origin !== allowedOrigin) {\n Logger.warn('Blocked message from unauthorized origin', { origin: event.origin, expected: allowedOrigin });\n return;\n }\n\n // ✅ Validate payload\n const tokenMsg = TokenMessageSchema.safeParse(event.data);\n if (tokenMsg.success) {\n Logger.info('Authentication successful');\n cleanupAndClose();\n resolve({ token: tokenMsg.data.accessToken });\n return;\n }\n\n const errorMsg = ErrorMessageSchema.safeParse(event.data);\n if (errorMsg.success) {\n Logger.warn('Authentication error received', { error: errorMsg.data.error });\n cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, \"Authentication failed: \" + errorMsg.data.error));\n return;\n }\n\n Logger.error('Invalid message format received', { \n messageData: event.data, \n dataType: typeof event.data,\n tokenValidationError: tokenMsg.error?.issues,\n errorValidationError: errorMsg.error?.issues\n });\n cleanupAndClose(new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\"));\n };\n\n // Timeout handler\n Logger.debug('Setting timeout', { timeout });\n timeoutId = setTimeout(() => {\n Logger.warn('Authentication timeout', { timeout });\n cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));\n }, timeout);\n\n checkClosedInterval = setInterval(() => {\n if (authWindow?.closed) {\n Logger.info('Authentication window closed by user');\n cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, \"Authentication window was closed\"));\n }\n }, 2000); // Reduced polling frequency\n\n try {\n window.addEventListener(\"message\", listener);\n } catch (error) {\n cleanup();\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to set up message listener: \" + (error instanceof Error ? error.message : \"Unknown error\")));\n return;\n }\n });\n}\n","import { Logger } from \"./logger\";\n\nexport class TokenManager {\n private token: string | null = null;\n private readonly storageKey: string;\n\n constructor(\n private readonly storage: Storage = sessionStorage,\n storageKey?: string\n ) {\n this.storageKey = storageKey || \"cams_token\";\n }\n\n setToken(token: string) {\n this.token = token;\n this.storage.setItem(this.storageKey, token);\n Logger.debug(\"Token stored\", { storageKey: this.storageKey });\n }\n\n loadToken(): string | null {\n if (this.token) return this.token;\n const raw = this.storage.getItem(this.storageKey);\n if (!raw) return null;\n \n this.token = raw;\n Logger.debug(\"Token loaded from storage\");\n return this.token;\n }\n\n clearToken() {\n this.token = null;\n this.storage.removeItem(this.storageKey);\n Logger.debug(\"Token cleared\");\n }\n\n getAccessToken(): string | null {\n const token = this.loadToken();\n return token;\n }\n\n isExpired(): boolean {\n const token = this.loadToken();\n if (!token) return true;\n\n // JWT expiration check if available\n if (token) {\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const payload = JSON.parse(atob(parts[1]));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n // Fallback: return true for safety when expiration cannot be determined\n return true;\n }\n}\n","import { CAMSConfig, CAMSTokenResponse, CAMSError, CAMSErrorType } from \"./types\";\nimport { TokenManager } from \"./tokenManager\";\nimport { openCAMSPopUpLogin } from \"./auth\";\nimport { Profile, ProfileSchema } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (token: CAMSTokenResponse) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSessionManager {\n private readonly tokenManager: TokenManager;\n private readonly events: CAMSEvents;\n\n constructor(\n storage: Storage = sessionStorage,\n storageKey?: string,\n events: CAMSEvents = {}\n ) {\n this.tokenManager = new TokenManager(storage, storageKey);\n this.events = events;\n }\n\n async login(config: CAMSConfig): Promise<CAMSTokenResponse> {\n try {\n Logger.info('Session login started');\n this.events.onAuthStart && this.events.onAuthStart();\n \n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n Logger.debug('Login retry configuration', { maxAttempts });\n \n while (attempts < maxAttempts) {\n try {\n attempts++;\n Logger.debug('Login attempt', { attempt: attempts, maxAttempts });\n const response = await openCAMSPopUpLogin(config);\n this.tokenManager.setToken(response.token);\n Logger.info('Session login successful');\n this.events.onAuthSuccess && this.events.onAuthSuccess(response);\n return response;\n } catch (error) {\n Logger.warn('Login attempt failed', { attempt: attempts, error: error instanceof Error ? error.message : 'Unknown error' });\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {\n throw error;\n }\n Logger.info('Retrying login', { nextAttempt: attempts + 1 });\n }\n }\n \n throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, 'Max retry attempts exceeded');\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n const camsError = error instanceof CAMSError ? error : \n new CAMSError(CAMSErrorType.USER_CANCELLED, errorMessage);\n Logger.error('Session login failed', { error: camsError.message, type: camsError.type });\n this.events.onAuthError && this.events.onAuthError(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n Logger.info('Session logout');\n this.tokenManager.clearToken();\n }\n\n isAuthenticated(): boolean {\n const token = this.tokenManager.loadToken();\n if (!token) {\n Logger.debug('No token found');\n return false;\n }\n \n if (this.tokenManager.isExpired()) {\n Logger.info('Token expired');\n this.events.onTokenExpired?.();\n return false;\n }\n \n Logger.debug('Token is valid');\n return true;\n }\n\n getAccessToken(): string | null {\n const token = this.tokenManager.loadToken();\n if (!token) return null;\n \n if (this.tokenManager.isExpired()) {\n this.events.onTokenExpired?.();\n return null;\n }\n \n return token;\n }\n\n private decodeBase64Url(str: string): string {\n // Convert base64url to base64\n str = str.replace(/-/g, '+').replace(/_/g, '/');\n // Add padding if needed\n while (str.length % 4) {\n str += '=';\n }\n return atob(str);\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.tokenManager.loadToken();\n if (!storedToken) return null;\n\n try {\n const parts = storedToken.split('.');\n if (parts.length >= 3) { // JWT has header.payload.signature format\n try {\n const payload = JSON.parse(this.decodeBase64Url(parts[1]));\n return ProfileSchema.parse(payload);\n } catch (decodeError) {\n Logger.warn('Failed to decode JWT payload', { error: decodeError instanceof Error ? decodeError.message : 'Unknown error' });\n }\n }\n } catch (error) {\n Logger.warn('Failed to extract profile from token', { error: error instanceof Error ? error.message : 'Unknown error' });\n }\n\n return null;\n }\n}"],"names":[],"mappings":";;IAYY;AAAZ,CAAA,UAAY,aAAa,EAAA;AACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;AAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;AAC3B,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC/C,CAAC,EAPW,aAAa,KAAb,aAAa,GAAA,EAAA,CAAA,CAAA;AASnB,MAAO,SAAU,SAAQ,KAAK,CAAA;IAClC,WAAA,CAAmB,IAAmB,EAAE,OAAe,EAAA;QACrD,KAAK,CAAC,OAAO,CAAC;QADG,IAAA,CAAA,IAAI,GAAJ,IAAI;AAErB,QAAA,IAAI,CAAC,IAAI,GAAG,WAAW;IACzB;AACD;;ACxBD;AACO,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAC;AACzC,IAAA,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,cAAc,CAAC;IAC/B,WAAW,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,8BAA8B,CAAC;AAC9D,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O,IAAI;IACb;AACD;;;;"}
|
package/dist/index.umd.js
CHANGED
|
@@ -23,7 +23,12 @@
|
|
|
23
23
|
|
|
24
24
|
// Validate the returned token - Base64 format with minimum 20 chars
|
|
25
25
|
const TokenMessageSchema = zod.z.object({
|
|
26
|
-
|
|
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(),
|
|
27
32
|
});
|
|
28
33
|
const ErrorMessageSchema = zod.z.object({
|
|
29
34
|
error: zod.z.string().min(1, "Error message cannot be empty"),
|
|
@@ -168,7 +173,7 @@
|
|
|
168
173
|
if (tokenMsg.success) {
|
|
169
174
|
Logger.info('Authentication successful');
|
|
170
175
|
cleanupAndClose();
|
|
171
|
-
resolve({ token: tokenMsg.data.
|
|
176
|
+
resolve({ token: tokenMsg.data.accessToken });
|
|
172
177
|
return;
|
|
173
178
|
}
|
|
174
179
|
const errorMsg = ErrorMessageSchema.safeParse(event.data);
|
|
@@ -192,7 +197,7 @@
|
|
|
192
197
|
cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));
|
|
193
198
|
}, timeout);
|
|
194
199
|
checkClosedInterval = setInterval(() => {
|
|
195
|
-
if (authWindow
|
|
200
|
+
if (authWindow?.closed) {
|
|
196
201
|
Logger.info('Authentication window closed by user');
|
|
197
202
|
cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
|
|
198
203
|
}
|
|
@@ -215,8 +220,8 @@
|
|
|
215
220
|
this.storageKey = storageKey || "cams_token";
|
|
216
221
|
}
|
|
217
222
|
setToken(token) {
|
|
218
|
-
|
|
219
|
-
this.storage.setItem(this.storageKey,
|
|
223
|
+
this.token = token;
|
|
224
|
+
this.storage.setItem(this.storageKey, token);
|
|
220
225
|
Logger.debug("Token stored", { storageKey: this.storageKey });
|
|
221
226
|
}
|
|
222
227
|
loadToken() {
|
|
@@ -225,20 +230,9 @@
|
|
|
225
230
|
const raw = this.storage.getItem(this.storageKey);
|
|
226
231
|
if (!raw)
|
|
227
232
|
return null;
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
return this.token;
|
|
232
|
-
}
|
|
233
|
-
catch (validationError) {
|
|
234
|
-
Logger.warn("Token validation failed", {
|
|
235
|
-
error: validationError instanceof Error
|
|
236
|
-
? validationError.message
|
|
237
|
-
: "Unknown error",
|
|
238
|
-
});
|
|
239
|
-
this.storage.removeItem(this.storageKey);
|
|
240
|
-
return null;
|
|
241
|
-
}
|
|
233
|
+
this.token = raw;
|
|
234
|
+
Logger.debug("Token loaded from storage");
|
|
235
|
+
return this.token;
|
|
242
236
|
}
|
|
243
237
|
clearToken() {
|
|
244
238
|
this.token = null;
|
|
@@ -277,7 +271,7 @@
|
|
|
277
271
|
}
|
|
278
272
|
}
|
|
279
273
|
|
|
280
|
-
class
|
|
274
|
+
class CAMSSessionManager {
|
|
281
275
|
constructor(storage = sessionStorage, storageKey, events = {}) {
|
|
282
276
|
this.tokenManager = new TokenManager(storage, storageKey);
|
|
283
277
|
this.events = events;
|
|
@@ -294,6 +288,7 @@
|
|
|
294
288
|
attempts++;
|
|
295
289
|
Logger.debug('Login attempt', { attempt: attempts, maxAttempts });
|
|
296
290
|
const response = await openCAMSPopUpLogin(config);
|
|
291
|
+
this.tokenManager.setToken(response.token);
|
|
297
292
|
Logger.info('Session login successful');
|
|
298
293
|
this.events.onAuthSuccess && this.events.onAuthSuccess(response);
|
|
299
294
|
return response;
|
|
@@ -313,8 +308,9 @@
|
|
|
313
308
|
throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED, 'Max retry attempts exceeded');
|
|
314
309
|
}
|
|
315
310
|
catch (error) {
|
|
311
|
+
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
316
312
|
const camsError = error instanceof CAMSError ? error :
|
|
317
|
-
new CAMSError(exports.CAMSErrorType.USER_CANCELLED,
|
|
313
|
+
new CAMSError(exports.CAMSErrorType.USER_CANCELLED, errorMessage);
|
|
318
314
|
Logger.error('Session login failed', { error: camsError.message, type: camsError.type });
|
|
319
315
|
this.events.onAuthError && this.events.onAuthError(camsError);
|
|
320
316
|
throw camsError;
|
|
@@ -381,7 +377,7 @@
|
|
|
381
377
|
}
|
|
382
378
|
|
|
383
379
|
exports.CAMSError = CAMSError;
|
|
384
|
-
exports.
|
|
380
|
+
exports.CAMSSessionManager = CAMSSessionManager;
|
|
385
381
|
exports.ErrorMessageSchema = ErrorMessageSchema;
|
|
386
382
|
exports.Logger = Logger;
|
|
387
383
|
exports.ProfileSchema = ProfileSchema;
|
package/dist/index.umd.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.umd.js","sources":["../src/types.ts","../src/validators.ts","../src/logger.ts","../src/auth.ts","../src/tokenManager.ts","../src/session.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n allowedOrigin: string;\n windowWidth: number;\n windowHeight: number;\n timeout?: number; // Auth timeout in ms (default: 300000)\n allowedDomains?: string[]; // URL allowlist for security\n storageKey?: string; // Custom storage key\n retryAttempts?: number; // Auto-retry on failure (default: 0)\n debug?: boolean; // Enable debug logging (default: false)\n}\n\nexport enum CAMSErrorType {\n POPUP_BLOCKED = 'POPUP_BLOCKED',\n TIMEOUT = 'TIMEOUT',\n INVALID_ORIGIN = 'INVALID_ORIGIN',\n USER_CANCELLED = 'USER_CANCELLED',\n INVALID_URL = 'INVALID_URL',\n MAX_RETRIES_EXCEEDED = 'MAX_RETRIES_EXCEEDED'\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = 'CAMSError';\n }\n}\n\nexport interface CAMSTokenResponse {\n token: string;\n}\n\nexport interface CAMSErrorResponse {\n error: string;\n}\n","import { z } from \"zod\";\n\n// Validate the returned token - Base64 format with minimum 20 chars\nexport const TokenMessageSchema = z.object({\n access_token: z.string().min(1, \"NIBSS CAMS Access token cannot be empty\"),\n});\n\nexport type TokenMessage = z.infer<typeof TokenMessageSchema>;\n\nexport const ErrorMessageSchema = z.object({\n error: z.string().min(1, \"Error message cannot be empty\"),\n});\n\nexport const TokenSchema = z.object({\n access_token: z.string(),\n refresh_token: z.string().optional(),\n expires_in: z.number(), // in seconds\n token_type: z.string().default(\"Bearer\"),\n id_token: z.string().optional(),\n});\n\nexport type Token = z.infer<typeof TokenSchema>;\n\nexport const ProfileSchema = z.object({\n sub: z.string(), // user ID\n name: z.string().optional(),\n email: z.email({ message: \"Invalid email address\" }).optional(),\n given_name: z.string().optional(),\n family_name: z.string().optional(),\n roles: z.array(z.string()).optional(),\n});\n\nexport type Profile = z.infer<typeof ProfileSchema>;\n\n// Matches IPv4 addresses like 192.168.x.x, 10.x.x.x, 172.16–31.x.x\nconst internalIpRegex =\n /^(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+)?$/;\n\nexport const URLSchema = z.url().refine(\n (url) =>\n url.startsWith(\"https://\") || // normal HTTPS\n /^http:\\/\\/localhost(:\\d+)?$/i.test(url) || // localhost\n internalIpRegex.test(url), // internal LAN IPs\n {\n message:\n \"Only HTTPS, http://localhost, or internal IPs (192.168.x.x, 10.x.x.x, 172.16–31.x.x) are allowed\",\n }\n);","export enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3\n}\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nexport class Logger {\n private static level: LogLevel = LogLevel.WARN;\n private static prefix = '[CAMS-SDK]';\n private static isTestEnv = typeof process !== 'undefined' && process.env?.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, message, context || '');\n }\n }\n\n static warn(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {\n console.warn(`${Logger.prefix} WARN:`, message, context || '');\n }\n }\n\n static info(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {\n console.info(`${Logger.prefix} INFO:`, message, context || '');\n }\n }\n\n static debug(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {\n console.debug(`${Logger.prefix} DEBUG:`, message, context || '');\n }\n }\n}","import { CAMSConfig, CAMSTokenResponse, CAMSError, CAMSErrorType } from \"./types\";\nimport { TokenMessageSchema, ErrorMessageSchema, URLSchema } from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\nexport function validateConfig(config: CAMSConfig): void {\n // Validate URL format\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'Invalid CAMS URL format');\n }\n\n // Domain validation is mandatory for security\n if (!config.allowedDomains?.length) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');\n }\n\n const url = new URL(config.camsUrl); // URLSchema already validated this\n const isAllowed = config.allowedDomains.some(domain => \n url.hostname === domain || url.hostname.endsWith('.' + domain)\n );\n if (!isAllowed) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'URL not in allowed domains list');\n }\n}\n\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<CAMSTokenResponse> {\n return new Promise((resolve, reject) => {\n if (config.debug) Logger.setLevel(LogLevel.DEBUG);\n \n Logger.info('Starting CAMS authentication', { url: config.camsUrl });\n \n try {\n validateConfig(config);\n Logger.debug('Config validation passed');\n } catch (error) {\n Logger.error('Config validation failed', { error: error instanceof Error ? error.message : 'Unknown error' });\n reject(error as Error);\n return;\n }\n\n const { camsUrl, allowedOrigin, windowHeight, windowWidth, timeout = 300000 } = config;\n let authWindow: Window | null;\n let timeoutId: NodeJS.Timeout | null = null;\n let checkClosedInterval: NodeJS.Timeout | null = null;\n \n try {\n Logger.debug('Opening popup window', { width: windowWidth, height: windowHeight });\n authWindow = window.open(\n camsUrl,\n \"NIBSS CAMS Login\",\n `width=${windowWidth},height=${windowHeight}`\n );\n } catch (error) {\n Logger.error('Failed to open popup window', { error: error instanceof Error ? error.message : 'Unknown error' });\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to open authentication window: \" + (error instanceof Error ? error.message : \"Unknown error\")));\n return;\n }\n\n if (!authWindow) {\n Logger.error('Popup window blocked');\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to open authentication window. Please allow popups.\"));\n return;\n }\n \n Logger.debug('Popup window opened successfully');\n\n const cleanup = () => {\n window.removeEventListener(\"message\", listener);\n if (timeoutId) clearTimeout(timeoutId);\n if (checkClosedInterval) clearInterval(checkClosedInterval);\n };\n \n const cleanupAndClose = (error?: CAMSError) => {\n cleanup();\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.close();\n }\n } catch {\n // Ignore close errors\n }\n if (error) reject(error);\n };\n\n const listener = (event: MessageEvent) => {\n Logger.debug('Received message', { origin: event.origin, expectedOrigin: allowedOrigin, data: event.data });\n \n if (event.origin !== allowedOrigin) {\n Logger.warn('Blocked message from unauthorized origin', { origin: event.origin, expected: allowedOrigin });\n return;\n }\n\n // ✅ Validate payload\n const tokenMsg = TokenMessageSchema.safeParse(event.data);\n if (tokenMsg.success) {\n Logger.info('Authentication successful');\n cleanupAndClose();\n resolve({ token: tokenMsg.data.access_token });\n return;\n }\n\n const errorMsg = ErrorMessageSchema.safeParse(event.data);\n if (errorMsg.success) {\n Logger.warn('Authentication error received', { error: errorMsg.data.error });\n cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, \"Authentication failed: \" + errorMsg.data.error));\n return;\n }\n\n Logger.error('Invalid message format received', { \n messageData: event.data, \n dataType: typeof event.data,\n tokenValidationError: tokenMsg.error?.issues,\n errorValidationError: errorMsg.error?.issues\n });\n cleanupAndClose(new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\"));\n };\n\n // Timeout handler\n Logger.debug('Setting timeout', { timeout });\n timeoutId = setTimeout(() => {\n Logger.warn('Authentication timeout', { timeout });\n cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));\n }, timeout);\n\n checkClosedInterval = setInterval(() => {\n if (authWindow && authWindow.closed) {\n Logger.info('Authentication window closed by user');\n cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, \"Authentication window was closed\"));\n }\n }, 2000); // Reduced polling frequency\n\n try {\n window.addEventListener(\"message\", listener);\n } catch (error) {\n cleanup();\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to set up message listener: \" + (error instanceof Error ? error.message : \"Unknown error\")));\n return;\n }\n });\n}\n","import { TokenMessageSchema } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport class TokenManager {\n private token: string | null = null;\n private readonly storageKey: string;\n\n constructor(\n private readonly storage: Storage = sessionStorage,\n storageKey?: string\n ) {\n this.storageKey = storageKey || \"cams_token\";\n }\n\n setToken(token: string) {\n const parsed = TokenMessageSchema.parse(token);\n this.storage.setItem(this.storageKey, parsed.access_token);\n\n Logger.debug(\"Token stored\", { storageKey: this.storageKey });\n }\n\n loadToken(): string | null {\n if (this.token) return this.token;\n const raw = this.storage.getItem(this.storageKey);\n if (!raw) return null;\n\n try {\n this.token = TokenMessageSchema.parse(raw).access_token;\n Logger.debug(\"Token loaded from storage\");\n return this.token;\n } catch (validationError) {\n Logger.warn(\"Token validation failed\", {\n error:\n validationError instanceof Error\n ? validationError.message\n : \"Unknown error\",\n });\n this.storage.removeItem(this.storageKey);\n return null;\n }\n }\n\n clearToken() {\n this.token = null;\n this.storage.removeItem(this.storageKey);\n Logger.debug(\"Token cleared\");\n }\n\n getAccessToken(): string | null {\n const token = this.loadToken();\n return token;\n }\n\n isExpired(): boolean {\n const token = this.loadToken();\n if (!token) return true;\n\n // JWT expiration check if available\n if (token) {\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const payload = JSON.parse(atob(parts[1]));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n // Fallback: return true for safety when expiration cannot be determined\n return true;\n }\n}\n","import { CAMSConfig, CAMSTokenResponse, CAMSError, CAMSErrorType } from \"./types\";\nimport { TokenManager } from \"./tokenManager\";\nimport { openCAMSPopUpLogin } from \"./auth\";\nimport { Profile, ProfileSchema } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (token: CAMSTokenResponse) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSession {\n private readonly tokenManager: TokenManager;\n private readonly events: CAMSEvents;\n\n constructor(\n storage: Storage = sessionStorage,\n storageKey?: string,\n events: CAMSEvents = {}\n ) {\n this.tokenManager = new TokenManager(storage, storageKey);\n this.events = events;\n }\n\n async login(config: CAMSConfig): Promise<CAMSTokenResponse> {\n try {\n Logger.info('Session login started');\n this.events.onAuthStart && this.events.onAuthStart();\n \n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n Logger.debug('Login retry configuration', { maxAttempts });\n \n while (attempts < maxAttempts) {\n try {\n attempts++;\n Logger.debug('Login attempt', { attempt: attempts, maxAttempts });\n const response = await openCAMSPopUpLogin(config);\n Logger.info('Session login successful');\n this.events.onAuthSuccess && this.events.onAuthSuccess(response);\n return response;\n } catch (error) {\n Logger.warn('Login attempt failed', { attempt: attempts, error: error instanceof Error ? error.message : 'Unknown error' });\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {\n throw error;\n }\n Logger.info('Retrying login', { nextAttempt: attempts + 1 });\n }\n }\n \n throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, 'Max retry attempts exceeded');\n } catch (error) {\n const camsError = error instanceof CAMSError ? error : \n new CAMSError(CAMSErrorType.USER_CANCELLED, error instanceof Error ? error.message : 'Unknown error');\n Logger.error('Session login failed', { error: camsError.message, type: camsError.type });\n this.events.onAuthError && this.events.onAuthError(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n Logger.info('Session logout');\n this.tokenManager.clearToken();\n }\n\n isAuthenticated(): boolean {\n const token = this.tokenManager.loadToken();\n if (!token) {\n Logger.debug('No token found');\n return false;\n }\n \n if (this.tokenManager.isExpired()) {\n Logger.info('Token expired');\n this.events.onTokenExpired?.();\n return false;\n }\n \n Logger.debug('Token is valid');\n return true;\n }\n\n getAccessToken(): string | null {\n const token = this.tokenManager.loadToken();\n if (!token) return null;\n \n if (this.tokenManager.isExpired()) {\n this.events.onTokenExpired?.();\n return null;\n }\n \n return token;\n }\n\n private decodeBase64Url(str: string): string {\n // Convert base64url to base64\n str = str.replace(/-/g, '+').replace(/_/g, '/');\n // Add padding if needed\n while (str.length % 4) {\n str += '=';\n }\n return atob(str);\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.tokenManager.loadToken();\n if (!storedToken) return null;\n\n try {\n const parts = storedToken.split('.');\n if (parts.length >= 3) { // JWT has header.payload.signature format\n try {\n const payload = JSON.parse(this.decodeBase64Url(parts[1]));\n return ProfileSchema.parse(payload);\n } catch (decodeError) {\n Logger.warn('Failed to decode JWT payload', { error: decodeError instanceof Error ? decodeError.message : 'Unknown error' });\n }\n }\n } catch (error) {\n Logger.warn('Failed to extract profile from token', { error: error instanceof Error ? error.message : 'Unknown error' });\n }\n\n return null;\n }\n}"],"names":["CAMSErrorType","z","LogLevel"],"mappings":";;;;;;AAYYA;IAAZ,CAAA,UAAY,aAAa,EAAA;IACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;IAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;IACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;IACjC,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;IACjC,IAAA,aAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;IAC3B,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;IAC/C,CAAC,EAPWA,qBAAa,KAAbA,qBAAa,GAAA,EAAA,CAAA,CAAA;IASnB,MAAO,SAAU,SAAQ,KAAK,CAAA;QAClC,WAAA,CAAmB,IAAmB,EAAE,OAAe,EAAA;YACrD,KAAK,CAAC,OAAO,CAAC;YADG,IAAA,CAAA,IAAI,GAAJ,IAAI;IAErB,QAAA,IAAI,CAAC,IAAI,GAAG,WAAW;QACzB;IACD;;ICxBD;AACO,UAAM,kBAAkB,GAAGC,KAAC,CAAC,MAAM,CAAC;QACzC,YAAY,EAAEA,KAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,yCAAyC,CAAC;IAC3E,CAAA;AAIM,UAAM,kBAAkB,GAAGA,KAAC,CAAC,MAAM,CAAC;QACzC,KAAK,EAAEA,KAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,+BAA+B,CAAC;IAC1D,CAAA;AAEM,UAAM,WAAW,GAAGA,KAAC,CAAC,MAAM,CAAC;IAClC,IAAA,YAAY,EAAEA,KAAC,CAAC,MAAM,EAAE;IACxB,IAAA,aAAa,EAAEA,KAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IACpC,I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QAAA,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC;;IAE/C,QAAA,OAAO,GAAG,CAAC,MAAM,GAAG,CAAC,EAAE;gBACrB,GAAG,IAAI,GAAG;YACZ;IACA,QAAA,OAAO,IAAI,CAAC,GAAG,CAAC;QAClB;IAEA,IAAA,MAAM,UAAU,GAAA;YACd,MAAM,WAAW,GAAG,IAAI,CAAC,YAAY,CAAC,SAAS,EAAE;IACjD,QAAA,IAAI,CAAC,WAAW;IAAE,YAAA,OAAO,IAAI;IAE7B,QAAA,IAAI;gBACF,MAAM,KAAK,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC;gBACpC,IAAI,KAAK,CAAC,MAAM,IAAI,CAAC,EAAE;IACrB,gBAAA,IAAI;IACF,oBAAA,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAC1D,oBAAA,OAAO,aAAa,CAAC,KAAK,CAAC,OAAO,CAAC;oBACrC;oBAAE,OAAO,WAAW,EAAE;wBACpB,MAAM,CAAC,IAAI,CAAC,8BAA8B,EAAE,EAAE,KAAK,EAAE,WAAW,YAAY,KAAK,GAAG,WAAW,CAAC,OAAO,GAAG,eAAe,EAAE,CAAC;oBAC9H;gBACF;YACF;YAAE,OAAO,KAAK,EAAE;gBACd,MAAM,CAAC,IAAI,CAAC,sCAAsC,EAAE,EAAE,KAAK,EAAE,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,eAAe,EAAE,CAAC;YAC1H;IAEA,QAAA,OAAO,IAAI;QACb;IACD;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.umd.js","sources":["../src/types.ts","../src/validators.ts","../src/logger.ts","../src/auth.ts","../src/tokenManager.ts","../src/session.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n allowedOrigin: string;\n windowWidth: number;\n windowHeight: number;\n timeout?: number; // Auth timeout in ms (default: 300000)\n allowedDomains?: string[]; // URL allowlist for security\n storageKey?: string; // Custom storage key\n retryAttempts?: number; // Auto-retry on failure (default: 0)\n debug?: boolean; // Enable debug logging (default: false)\n}\n\nexport enum CAMSErrorType {\n POPUP_BLOCKED = 'POPUP_BLOCKED',\n TIMEOUT = 'TIMEOUT',\n INVALID_ORIGIN = 'INVALID_ORIGIN',\n USER_CANCELLED = 'USER_CANCELLED',\n INVALID_URL = 'INVALID_URL',\n MAX_RETRIES_EXCEEDED = 'MAX_RETRIES_EXCEEDED'\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = 'CAMSError';\n }\n}\n\nexport interface CAMSTokenResponse {\n token: string;\n}\n\nexport interface CAMSErrorResponse {\n error: string;\n}\n","import { z } from \"zod\";\n\n// Validate the returned token - Base64 format with minimum 20 chars\nexport const TokenMessageSchema = z.object({\n type: z.literal(\"AUTH_SUCCESS\"),\n accessToken: z.string().min(1, \"Access token cannot be empty\"),\n user: z.object({\n name: z.string(),\n image: z.string().nullable(),\n }).optional(),\n});\n\nexport type TokenMessage = z.infer<typeof TokenMessageSchema>;\n\nexport const ErrorMessageSchema = z.object({\n error: z.string().min(1, \"Error message cannot be empty\"),\n});\n\nexport const TokenSchema = z.object({\n access_token: z.string(),\n refresh_token: z.string().optional(),\n expires_in: z.number(), // in seconds\n token_type: z.string().default(\"Bearer\"),\n id_token: z.string().optional(),\n});\n\nexport type Token = z.infer<typeof TokenSchema>;\n\nexport const ProfileSchema = z.object({\n sub: z.string(), // user ID\n name: z.string().optional(),\n email: z.email({ message: \"Invalid email address\" }).optional(),\n given_name: z.string().optional(),\n family_name: z.string().optional(),\n roles: z.array(z.string()).optional(),\n});\n\nexport type Profile = z.infer<typeof ProfileSchema>;\n\n// Matches IPv4 addresses like 192.168.x.x, 10.x.x.x, 172.16–31.x.x\nconst internalIpRegex =\n /^(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+)?$/;\n\nexport const URLSchema = z.url().refine(\n (url) =>\n url.startsWith(\"https://\") || // normal HTTPS\n /^http:\\/\\/localhost(:\\d+)?$/i.test(url) || // localhost\n internalIpRegex.test(url), // internal LAN IPs\n {\n message:\n \"Only HTTPS, http://localhost, or internal IPs (192.168.x.x, 10.x.x.x, 172.16–31.x.x) are allowed\",\n }\n);","export enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3\n}\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nexport class Logger {\n private static level: LogLevel = LogLevel.WARN;\n private static prefix = '[CAMS-SDK]';\n private static isTestEnv = typeof process !== 'undefined' && process.env?.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, message, context || '');\n }\n }\n\n static warn(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {\n console.warn(`${Logger.prefix} WARN:`, message, context || '');\n }\n }\n\n static info(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {\n console.info(`${Logger.prefix} INFO:`, message, context || '');\n }\n }\n\n static debug(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {\n console.debug(`${Logger.prefix} DEBUG:`, message, context || '');\n }\n }\n}","import { CAMSConfig, CAMSTokenResponse, CAMSError, CAMSErrorType } from \"./types\";\nimport { TokenMessageSchema, ErrorMessageSchema, URLSchema } from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\nexport function validateConfig(config: CAMSConfig): void {\n // Validate URL format\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'Invalid CAMS URL format');\n }\n\n // Domain validation is mandatory for security\n if (!config.allowedDomains?.length) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');\n }\n\n const url = new URL(config.camsUrl); // URLSchema already validated this\n const isAllowed = config.allowedDomains.some(domain => \n url.hostname === domain || url.hostname.endsWith('.' + domain)\n );\n if (!isAllowed) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'URL not in allowed domains list');\n }\n}\n\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<CAMSTokenResponse> {\n return new Promise((resolve, reject) => {\n if (config.debug) Logger.setLevel(LogLevel.DEBUG);\n \n Logger.info('Starting CAMS authentication', { url: config.camsUrl });\n \n try {\n validateConfig(config);\n Logger.debug('Config validation passed');\n } catch (error) {\n Logger.error('Config validation failed', { error: error instanceof Error ? error.message : 'Unknown error' });\n reject(error as Error);\n return;\n }\n\n const { camsUrl, allowedOrigin, windowHeight, windowWidth, timeout = 300000 } = config;\n let authWindow: Window | null;\n let timeoutId: NodeJS.Timeout | null = null;\n let checkClosedInterval: NodeJS.Timeout | null = null;\n \n try {\n Logger.debug('Opening popup window', { width: windowWidth, height: windowHeight });\n authWindow = window.open(\n camsUrl,\n \"NIBSS CAMS Login\",\n `width=${windowWidth},height=${windowHeight}`\n );\n } catch (error) {\n Logger.error('Failed to open popup window', { error: error instanceof Error ? error.message : 'Unknown error' });\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to open authentication window: \" + (error instanceof Error ? error.message : \"Unknown error\")));\n return;\n }\n\n if (!authWindow) {\n Logger.error('Popup window blocked');\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to open authentication window. Please allow popups.\"));\n return;\n }\n \n Logger.debug('Popup window opened successfully');\n\n const cleanup = () => {\n window.removeEventListener(\"message\", listener);\n if (timeoutId) clearTimeout(timeoutId);\n if (checkClosedInterval) clearInterval(checkClosedInterval);\n };\n \n const cleanupAndClose = (error?: CAMSError) => {\n cleanup();\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.close();\n }\n } catch {\n // Ignore close errors\n }\n if (error) reject(error);\n };\n\n const listener = (event: MessageEvent) => {\n Logger.debug('Received message', { origin: event.origin, expectedOrigin: allowedOrigin, data: event.data });\n \n if (event.origin !== allowedOrigin) {\n Logger.warn('Blocked message from unauthorized origin', { origin: event.origin, expected: allowedOrigin });\n return;\n }\n\n // ✅ Validate payload\n const tokenMsg = TokenMessageSchema.safeParse(event.data);\n if (tokenMsg.success) {\n Logger.info('Authentication successful');\n cleanupAndClose();\n resolve({ token: tokenMsg.data.accessToken });\n return;\n }\n\n const errorMsg = ErrorMessageSchema.safeParse(event.data);\n if (errorMsg.success) {\n Logger.warn('Authentication error received', { error: errorMsg.data.error });\n cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, \"Authentication failed: \" + errorMsg.data.error));\n return;\n }\n\n Logger.error('Invalid message format received', { \n messageData: event.data, \n dataType: typeof event.data,\n tokenValidationError: tokenMsg.error?.issues,\n errorValidationError: errorMsg.error?.issues\n });\n cleanupAndClose(new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\"));\n };\n\n // Timeout handler\n Logger.debug('Setting timeout', { timeout });\n timeoutId = setTimeout(() => {\n Logger.warn('Authentication timeout', { timeout });\n cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));\n }, timeout);\n\n checkClosedInterval = setInterval(() => {\n if (authWindow?.closed) {\n Logger.info('Authentication window closed by user');\n cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, \"Authentication window was closed\"));\n }\n }, 2000); // Reduced polling frequency\n\n try {\n window.addEventListener(\"message\", listener);\n } catch (error) {\n cleanup();\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to set up message listener: \" + (error instanceof Error ? error.message : \"Unknown error\")));\n return;\n }\n });\n}\n","import { Logger } from \"./logger\";\n\nexport class TokenManager {\n private token: string | null = null;\n private readonly storageKey: string;\n\n constructor(\n private readonly storage: Storage = sessionStorage,\n storageKey?: string\n ) {\n this.storageKey = storageKey || \"cams_token\";\n }\n\n setToken(token: string) {\n this.token = token;\n this.storage.setItem(this.storageKey, token);\n Logger.debug(\"Token stored\", { storageKey: this.storageKey });\n }\n\n loadToken(): string | null {\n if (this.token) return this.token;\n const raw = this.storage.getItem(this.storageKey);\n if (!raw) return null;\n \n this.token = raw;\n Logger.debug(\"Token loaded from storage\");\n return this.token;\n }\n\n clearToken() {\n this.token = null;\n this.storage.removeItem(this.storageKey);\n Logger.debug(\"Token cleared\");\n }\n\n getAccessToken(): string | null {\n const token = this.loadToken();\n return token;\n }\n\n isExpired(): boolean {\n const token = this.loadToken();\n if (!token) return true;\n\n // JWT expiration check if available\n if (token) {\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const payload = JSON.parse(atob(parts[1]));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n // Fallback: return true for safety when expiration cannot be determined\n return true;\n }\n}\n","import { CAMSConfig, CAMSTokenResponse, CAMSError, CAMSErrorType } from \"./types\";\nimport { TokenManager } from \"./tokenManager\";\nimport { openCAMSPopUpLogin } from \"./auth\";\nimport { Profile, ProfileSchema } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (token: CAMSTokenResponse) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSessionManager {\n private readonly tokenManager: TokenManager;\n private readonly events: CAMSEvents;\n\n constructor(\n storage: Storage = sessionStorage,\n storageKey?: string,\n events: CAMSEvents = {}\n ) {\n this.tokenManager = new TokenManager(storage, storageKey);\n this.events = events;\n }\n\n async login(config: CAMSConfig): Promise<CAMSTokenResponse> {\n try {\n Logger.info('Session login started');\n this.events.onAuthStart && this.events.onAuthStart();\n \n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n Logger.debug('Login retry configuration', { maxAttempts });\n \n while (attempts < maxAttempts) {\n try {\n attempts++;\n Logger.debug('Login attempt', { attempt: attempts, maxAttempts });\n const response = await openCAMSPopUpLogin(config);\n this.tokenManager.setToken(response.token);\n Logger.info('Session login successful');\n this.events.onAuthSuccess && this.events.onAuthSuccess(response);\n return response;\n } catch (error) {\n Logger.warn('Login attempt failed', { attempt: attempts, error: error instanceof Error ? error.message : 'Unknown error' });\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {\n throw error;\n }\n Logger.info('Retrying login', { nextAttempt: attempts + 1 });\n }\n }\n \n throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, 'Max retry attempts exceeded');\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n const camsError = error instanceof CAMSError ? error : \n new CAMSError(CAMSErrorType.USER_CANCELLED, errorMessage);\n Logger.error('Session login failed', { error: camsError.message, type: camsError.type });\n this.events.onAuthError && this.events.onAuthError(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n Logger.info('Session logout');\n this.tokenManager.clearToken();\n }\n\n isAuthenticated(): boolean {\n const token = this.tokenManager.loadToken();\n if (!token) {\n Logger.debug('No token found');\n return false;\n }\n \n if (this.tokenManager.isExpired()) {\n Logger.info('Token expired');\n this.events.onTokenExpired?.();\n return false;\n }\n \n Logger.debug('Token is valid');\n return true;\n }\n\n getAccessToken(): string | null {\n const token = this.tokenManager.loadToken();\n if (!token) return null;\n \n if (this.tokenManager.isExpired()) {\n this.events.onTokenExpired?.();\n return null;\n }\n \n return token;\n }\n\n private decodeBase64Url(str: string): string {\n // Convert base64url to base64\n str = str.replace(/-/g, '+').replace(/_/g, '/');\n // Add padding if needed\n while (str.length % 4) {\n str += '=';\n }\n return atob(str);\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.tokenManager.loadToken();\n if (!storedToken) return null;\n\n try {\n const parts = storedToken.split('.');\n if (parts.length >= 3) { // JWT has header.payload.signature format\n try {\n const payload = JSON.parse(this.decodeBase64Url(parts[1]));\n return ProfileSchema.parse(payload);\n } catch (decodeError) {\n Logger.warn('Failed to decode JWT payload', { error: decodeError instanceof Error ? decodeError.message : 'Unknown error' });\n }\n }\n } catch (error) {\n Logger.warn('Failed to extract profile from token', { error: error instanceof Error ? error.message : 'Unknown error' });\n }\n\n return null;\n }\n}"],"names":["CAMSErrorType","z","LogLevel"],"mappings":";;;;;;AAYYA;IAAZ,CAAA,UAAY,aAAa,EAAA;IACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;IAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;IACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;IACjC,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;IACjC,IAAA,aAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;IAC3B,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;IAC/C,CAAC,EAPWA,qBAAa,KAAbA,qBAAa,GAAA,EAAA,CAAA,CAAA;IASnB,MAAO,SAAU,SAAQ,KAAK,CAAA;QAClC,WAAA,CAAmB,IAAmB,EAAE,OAAe,EAAA;YACrD,KAAK,CAAC,OAAO,CAAC;YADG,IAAA,CAAA,IAAI,GAAJ,IAAI;IAErB,QAAA,IAAI,CAAC,IAAI,GAAG,WAAW;QACzB;IACD;;ICxBD;AACO,UAAM,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I,CAAC,8BAA8B,EAAE,EAAE,KAAK,EAAE,WAAW,YAAY,KAAK,GAAG,WAAW,CAAC,OAAO,GAAG,eAAe,EAAE,CAAC;oBAC9H;gBACF;YACF;YAAE,OAAO,KAAK,EAAE;gBACd,MAAM,CAAC,IAAI,CAAC,sCAAsC,EAAE,EAAE,KAAK,EAAE,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,eAAe,EAAE,CAAC;YAC1H;IAEA,QAAA,OAAO,IAAI;QACb;IACD;;;;;;;;;;;;;;;;;;"}
|
package/dist/session.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ export interface CAMSEvents {
|
|
|
6
6
|
onAuthError?: (error: CAMSError) => void;
|
|
7
7
|
onTokenExpired?: () => void;
|
|
8
8
|
}
|
|
9
|
-
export declare class
|
|
9
|
+
export declare class CAMSSessionManager {
|
|
10
10
|
private readonly tokenManager;
|
|
11
11
|
private readonly events;
|
|
12
12
|
constructor(storage?: Storage, storageKey?: string, events?: CAMSEvents);
|
package/dist/validators.d.ts
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
export declare const TokenMessageSchema: z.ZodObject<{
|
|
3
|
-
|
|
3
|
+
type: z.ZodLiteral<"AUTH_SUCCESS">;
|
|
4
|
+
accessToken: z.ZodString;
|
|
5
|
+
user: z.ZodOptional<z.ZodObject<{
|
|
6
|
+
name: z.ZodString;
|
|
7
|
+
image: z.ZodNullable<z.ZodString>;
|
|
8
|
+
}, z.core.$strip>>;
|
|
4
9
|
}, z.core.$strip>;
|
|
5
10
|
export type TokenMessage = z.infer<typeof TokenMessageSchema>;
|
|
6
11
|
export declare const ErrorMessageSchema: z.ZodObject<{
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nibssplc/cams-sdk",
|
|
3
|
-
"version": "0.0.1-beta.
|
|
3
|
+
"version": "0.0.1-beta.13",
|
|
4
4
|
"description": "Central Authentication Management Service (CAMS) SDK for popup-based authentication with Azure AD + custom 2FA",
|
|
5
5
|
"main": "dist/index.cjs.js",
|
|
6
6
|
"module": "dist/index.esm.js",
|