@nibssplc/cams-sdk 0.0.1-beta.14 → 0.0.1-beta.16
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/dist/index.cjs.js +31 -4
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.esm.js +31 -4
- package/dist/index.esm.js.map +1 -1
- package/dist/index.umd.js +31 -4
- package/dist/index.umd.js.map +1 -1
- package/dist/tokenManager.d.ts +1 -0
- package/package.json +1 -1
- /package/dist/{session.d.ts → sessionManager.d.ts} +0 -0
package/dist/index.cjs.js
CHANGED
|
@@ -131,7 +131,7 @@ function openCAMSPopUpLogin(config) {
|
|
|
131
131
|
return;
|
|
132
132
|
}
|
|
133
133
|
const { messageOrigin, windowHeight, windowWidth, authTimeout = 300000, // 5 minutes as a final failsafe
|
|
134
|
-
idleTimeout =
|
|
134
|
+
idleTimeout = 120000, // 2 minutes of inactivity
|
|
135
135
|
} = config;
|
|
136
136
|
let authWindow;
|
|
137
137
|
let authTimeoutId = null;
|
|
@@ -180,12 +180,16 @@ function openCAMSPopUpLogin(config) {
|
|
|
180
180
|
data: event.data,
|
|
181
181
|
});
|
|
182
182
|
const originUrl = new URL(event.origin);
|
|
183
|
-
const
|
|
184
|
-
|
|
183
|
+
const expectedHostname = messageOrigin.startsWith('http')
|
|
184
|
+
? new URL(messageOrigin).hostname
|
|
185
|
+
: messageOrigin;
|
|
186
|
+
const isAllowedOrigin = originUrl.hostname === expectedHostname ||
|
|
187
|
+
originUrl.hostname.endsWith("." + expectedHostname);
|
|
185
188
|
if (!isAllowedOrigin) {
|
|
186
189
|
Logger.warn("Blocked message from unauthorized origin", {
|
|
187
190
|
origin: event.origin,
|
|
188
191
|
expected: messageOrigin,
|
|
192
|
+
data: event.data,
|
|
189
193
|
});
|
|
190
194
|
return;
|
|
191
195
|
}
|
|
@@ -341,6 +345,29 @@ class TokenManager {
|
|
|
341
345
|
return true;
|
|
342
346
|
}
|
|
343
347
|
}
|
|
348
|
+
isPaddedExpired() {
|
|
349
|
+
const token = this.loadToken();
|
|
350
|
+
if (!token)
|
|
351
|
+
return true;
|
|
352
|
+
try {
|
|
353
|
+
const parts = token.split(".");
|
|
354
|
+
if (parts.length < 3)
|
|
355
|
+
return true; // Invalid JWT format
|
|
356
|
+
const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
357
|
+
const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=");
|
|
358
|
+
const payload = JSON.parse(atob(padded));
|
|
359
|
+
if (typeof payload.exp !== "number")
|
|
360
|
+
return true;
|
|
361
|
+
const exp = payload.exp * 1000;
|
|
362
|
+
return Date.now() > exp;
|
|
363
|
+
}
|
|
364
|
+
catch (error) {
|
|
365
|
+
Logger.warn("Failed to parse JWT token", {
|
|
366
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
367
|
+
});
|
|
368
|
+
return true;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
344
371
|
}
|
|
345
372
|
|
|
346
373
|
class CAMSSessionManager {
|
|
@@ -356,7 +383,7 @@ class CAMSSessionManager {
|
|
|
356
383
|
if (this.events.onAuthStart)
|
|
357
384
|
this.events.onAuthStart();
|
|
358
385
|
let attempts = 0;
|
|
359
|
-
const maxAttempts = (config.retryAttempts
|
|
386
|
+
const maxAttempts = (config.retryAttempts ?? 0) + 1;
|
|
360
387
|
Logger.debug('Login retry configuration', { maxAttempts });
|
|
361
388
|
while (attempts < maxAttempts) {
|
|
362
389
|
try {
|
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 messageOrigin: string; // Expected message origin\n windowWidth: number;\n windowHeight: number;\n authTimeout?: number; // Auth timeout in ms (default: 300000) // 5 minutes as a final failsafe\n idleTimeout?: number; // 1 minute of inactivity\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 API_VALIDATION_ERROR = \"API_VALIDATION_ERROR\",\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = this.constructor.name;\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 - non-empty string\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\nexport const URLSchema = z.url();","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 readonly prefix = '[CAMS-SDK]';\n private static readonly isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n private static sanitizeForLog(input: any): any {\n if (typeof input === 'string') {\n // Remove newlines and control characters to prevent log injection\n return input.replace(/[\\r\\n\\t]/g, ' ').replace(/[\\x00-\\x1F\\x7F]/g, '');\n }\n if (typeof input === 'object' && input !== null) {\n const sanitized: any = {};\n for (const [key, value] of Object.entries(input)) {\n sanitized[Logger.sanitizeForLog(key)] = Logger.sanitizeForLog(value);\n }\n return sanitized;\n }\n return input;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(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:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(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:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(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:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));\n }\n }\n}","import {\n CAMSConfig,\n CAMSTokenResponse,\n CAMSError,\n CAMSErrorType,\n} from \"./types\";\nimport {\n TokenMessageSchema,\n ErrorMessageSchema,\n URLSchema,\n} from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\nexport function validateConfig(config: CAMSConfig): URL {\n // Validate URL format and parse once\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.messageOrigin) {\n throw new CAMSError(\n CAMSErrorType.INVALID_URL,\n \"Message Origin must be specified for security\"\n );\n }\n\n const url = new URL(config.camsUrl);\n\n return url;\n}\n\nexport function openCAMSPopUpLogin(\n config: CAMSConfig\n): 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 let validatedUrl: URL;\n try {\n validatedUrl = validateConfig(config);\n Logger.debug(\"Config validation passed\");\n } catch (error) {\n Logger.error(\"Config validation failed\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(error as Error);\n return;\n }\n\n const {\n messageOrigin,\n windowHeight,\n windowWidth,\n authTimeout = 300000, // 5 minutes as a final failsafe\n idleTimeout = 60000, // 1 minute of inactivity\n } = config;\n let authWindow: Window | null;\n let authTimeoutId: NodeJS.Timeout | null = null;\n let idleTimeoutId: NodeJS.Timeout | null = null;\n let checkClosedInterval: NodeJS.Timeout | null = null;\n\n try {\n Logger.debug(\"Opening popup window\", {\n width: windowWidth,\n height: windowHeight,\n });\n\n // Center the popup window\n const left = (window.screen.width - windowWidth) / 2;\n const top = (window.screen.height - windowHeight) / 2;\n\n authWindow = window.open(\n validatedUrl.toString(),\n \"_blank\",\n `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes`\n );\n } catch (error) {\n Logger.error(\"Failed to open popup window\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to open authentication window: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n return;\n }\n\n if (!authWindow) {\n Logger.error(\"Popup window blocked\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to open authentication window. Please allow popups.\"\n )\n );\n return;\n }\n\n Logger.debug(\"Popup window opened successfully\");\n\n const cleanup = () => {\n window.removeEventListener(\"message\", listener);\n\n if (idleTimeoutId) clearTimeout(idleTimeoutId);\n if (authTimeoutId) clearTimeout(authTimeoutId);\n if (checkClosedInterval) clearTimeout(checkClosedInterval);\n idleTimeoutId = null;\n authTimeoutId = null;\n checkClosedInterval = null;\n };\n\n const listener = (event: MessageEvent) => {\n Logger.debug(\"Received message\", {\n origin: event.origin,\n expectedOrigin: messageOrigin,\n data: event.data,\n });\n\n const originUrl = new URL(event.origin);\n const isAllowedOrigin =\n originUrl.hostname === messageOrigin ||\n originUrl.hostname.endsWith(\".\" + messageOrigin);\n if (!isAllowedOrigin) {\n Logger.warn(\"Blocked message from unauthorized origin\", {\n origin: event.origin,\n expected: messageOrigin,\n });\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\", {\n error: errorMsg.data.error,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication failed: \" + errorMsg.data.error\n )\n );\n return;\n }\n\n Logger.error(\"Invalid message format received\", {\n messageData: event.data,\n dataType: typeof event.data,\n tokenValidationError: tokenMsg.error\n ? tokenMsg.error.issues\n : undefined,\n errorValidationError: errorMsg.error\n ? errorMsg.error.issues\n : undefined,\n });\n cleanupAndClose(\n new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\")\n );\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 resetIdleTimeout = () => {\n // Timeout handler\n if (idleTimeoutId) clearTimeout(idleTimeoutId);\n Logger.debug(\"Resetting idle timeout\", { idleTimeout });\n idleTimeoutId = setTimeout(() => {\n Logger.warn(\"Authentication idle timeout reached\", { idleTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication timed out due to inactivity after ${idleTimeout}ms`\n )\n );\n }, idleTimeout);\n };\n\n Logger.debug(\"Setting auth timeout\", { authTimeout });\n authTimeoutId = setTimeout(() => {\n Logger.warn(\"Authentication auth timeout reached\", { authTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication process exceeded auth time limit of ${authTimeout}ms`\n )\n );\n }, authTimeout);\n\n resetIdleTimeout();\n\n // Use exponential backoff for popup closure checking\n let pollInterval = 1000; // Start with 1 second\n const maxPollInterval = 5000; // Max 5 seconds\n\n const checkClosed = () => {\n if (authWindow?.closed) {\n Logger.info(\"Authentication window closed by user\");\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication window was closed\"\n )\n );\n return;\n }\n\n // Exponential backoff: increase interval up to max\n pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);\n checkClosedInterval = setTimeout(checkClosed, pollInterval);\n };\n\n checkClosedInterval = setTimeout(checkClosed, pollInterval);\n\n try {\n window.addEventListener(\"message\", listener);\n Logger.debug(\"Message listener attached\");\n } catch (error) {\n Logger.error(\"Failed to attach message listener\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n cleanup();\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to set up message listener: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n return;\n }\n\n // Add focus to the popup for better UX\n try {\n if (authWindow) {\n authWindow.focus();\n }\n } catch {\n // Ignore focus errors (cross-origin restrictions)\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 // Return cached token if available\n if (this.token) return this.token;\n \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 // Return cached token if available, avoiding redundant storage access\n if (this.token) return this.token;\n return this.loadToken();\n }\n\n isExpired(): boolean {\n const token = this.loadToken();\n if (!token) return true;\n\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","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 if (this.events.onAuthStart) this.events.onAuthStart();\n \n let attempts = 0;\n const maxAttempts = (config.retryAttempts !== undefined ? 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 \n // Add exponential backoff delay for retries\n if (attempts > 1) {\n const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay\n Logger.debug('Retry delay', { delay });\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n \n const response = await openCAMSPopUpLogin(config);\n\n Logger.debug('Login Response', response);\n this.tokenManager.setToken(response.token);\n Logger.info('Session login successful');\n if (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 if (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 private checkTokenExpiration(): boolean {\n if (this.tokenManager.isExpired()) {\n Logger.info('Token expired');\n if (this.events.onTokenExpired) this.events.onTokenExpired();\n return true;\n }\n return false;\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.checkTokenExpiration()) {\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.checkTokenExpiration()) {\n return null;\n }\n \n return token;\n }\n\n private decodeBase64Url(str: string): string {\n // Work with a copy to avoid mutating input\n let result = str.replace(/-/g, '+').replace(/_/g, '/');\n // Add padding if needed\n while (result.length % 4) {\n result += '=';\n }\n return atob(result);\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.tokenManager.loadToken();\n if (!storedToken) return null;\n\n // Check token expiration before processing\n if (this.checkTokenExpiration()) {\n return null;\n }\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;AAC7C,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC/C,CAAC,EARWA,qBAAa,KAAbA,qBAAa,GAAA,EAAA,CAAA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AAO,IAAI,CAAC,MAAM,CAAC;IACrB;AAEA,IAAA,MAAM,UAAU,GAAA;QACd,MAAM,WAAW,GAAG,IAAI,CAAC,YAAY,CAAC,SAAS,EAAE;AACjD,QAAA,IAAI,CAAC,WAAW;AAAE,YAAA,OAAO,IAAI;;AAG7B,QAAA,IAAI,IAAI,CAAC,oBAAoB,EAAE,EAAE;AAC/B,YAAA,OAAO,IAAI;QACb;AAEA,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/sessionManager.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n messageOrigin: string; // Expected message origin\n windowWidth: number;\n windowHeight: number;\n authTimeout?: number; // Auth timeout in ms (default: 300000) // 5 minutes as a final failsafe\n idleTimeout?: number; // 1 minute of inactivity\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 API_VALIDATION_ERROR = \"API_VALIDATION_ERROR\",\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = this.constructor.name;\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 - non-empty string\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\nexport const URLSchema = z.url();","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 readonly prefix = '[CAMS-SDK]';\n private static readonly isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n private static sanitizeForLog(input: any): any {\n if (typeof input === 'string') {\n // Remove newlines and control characters to prevent log injection\n return input.replace(/[\\r\\n\\t]/g, ' ').replace(/[\\x00-\\x1F\\x7F]/g, '');\n }\n if (typeof input === 'object' && input !== null) {\n const sanitized: any = {};\n for (const [key, value] of Object.entries(input)) {\n sanitized[Logger.sanitizeForLog(key)] = Logger.sanitizeForLog(value);\n }\n return sanitized;\n }\n return input;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(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:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(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:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(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:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));\n }\n }\n}","import {\n CAMSConfig,\n CAMSTokenResponse,\n CAMSError,\n CAMSErrorType,\n} from \"./types\";\nimport {\n TokenMessageSchema,\n ErrorMessageSchema,\n URLSchema,\n} from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\nexport function validateConfig(config: CAMSConfig): URL {\n // Validate URL format and parse once\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.messageOrigin) {\n throw new CAMSError(\n CAMSErrorType.INVALID_URL,\n \"Message Origin must be specified for security\"\n );\n }\n\n const url = new URL(config.camsUrl);\n\n return url;\n}\n\nexport function openCAMSPopUpLogin(\n config: CAMSConfig\n): 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 let validatedUrl: URL;\n try {\n validatedUrl = validateConfig(config);\n Logger.debug(\"Config validation passed\");\n } catch (error) {\n Logger.error(\"Config validation failed\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(error as Error);\n return;\n }\n\n const {\n messageOrigin,\n windowHeight,\n windowWidth,\n authTimeout = 300000, // 5 minutes as a final failsafe\n idleTimeout = 120000, // 2 minutes of inactivity\n } = config;\n let authWindow: Window | null;\n let authTimeoutId: NodeJS.Timeout | null = null;\n let idleTimeoutId: NodeJS.Timeout | null = null;\n let checkClosedInterval: NodeJS.Timeout | null = null;\n\n try {\n Logger.debug(\"Opening popup window\", {\n width: windowWidth,\n height: windowHeight,\n });\n\n // Center the popup window\n const left = (window.screen.width - windowWidth) / 2;\n const top = (window.screen.height - windowHeight) / 2;\n\n authWindow = window.open(\n validatedUrl.toString(),\n \"_blank\",\n `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes`\n );\n } catch (error) {\n Logger.error(\"Failed to open popup window\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to open authentication window: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n return;\n }\n\n if (!authWindow) {\n Logger.error(\"Popup window blocked\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to open authentication window. Please allow popups.\"\n )\n );\n return;\n }\n\n Logger.debug(\"Popup window opened successfully\");\n\n const cleanup = () => {\n window.removeEventListener(\"message\", listener);\n\n if (idleTimeoutId) clearTimeout(idleTimeoutId);\n if (authTimeoutId) clearTimeout(authTimeoutId);\n if (checkClosedInterval) clearTimeout(checkClosedInterval);\n idleTimeoutId = null;\n authTimeoutId = null;\n checkClosedInterval = null;\n };\n\n const listener = (event: MessageEvent) => {\n Logger.debug(\"Received message\", {\n origin: event.origin,\n expectedOrigin: messageOrigin,\n data: event.data,\n });\n\n const originUrl = new URL(event.origin);\n const expectedHostname = messageOrigin.startsWith('http') \n ? new URL(messageOrigin).hostname \n : messageOrigin;\n const isAllowedOrigin =\n originUrl.hostname === expectedHostname ||\n originUrl.hostname.endsWith(\".\" + expectedHostname);\n if (!isAllowedOrigin) {\n Logger.warn(\"Blocked message from unauthorized origin\", {\n origin: event.origin,\n expected: messageOrigin,\n data: event.data,\n });\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\", {\n error: errorMsg.data.error,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication failed: \" + errorMsg.data.error\n )\n );\n return;\n }\n\n Logger.error(\"Invalid message format received\", {\n messageData: event.data,\n dataType: typeof event.data,\n tokenValidationError: tokenMsg.error\n ? tokenMsg.error.issues\n : undefined,\n errorValidationError: errorMsg.error\n ? errorMsg.error.issues\n : undefined,\n });\n cleanupAndClose(\n new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\")\n );\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 resetIdleTimeout = () => {\n // Timeout handler\n if (idleTimeoutId) clearTimeout(idleTimeoutId);\n Logger.debug(\"Resetting idle timeout\", { idleTimeout });\n idleTimeoutId = setTimeout(() => {\n Logger.warn(\"Authentication idle timeout reached\", { idleTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication timed out due to inactivity after ${idleTimeout}ms`\n )\n );\n }, idleTimeout);\n };\n\n Logger.debug(\"Setting auth timeout\", { authTimeout });\n authTimeoutId = setTimeout(() => {\n Logger.warn(\"Authentication auth timeout reached\", { authTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication process exceeded auth time limit of ${authTimeout}ms`\n )\n );\n }, authTimeout);\n\n resetIdleTimeout();\n\n // Use exponential backoff for popup closure checking\n let pollInterval = 1000; // Start with 1 second\n const maxPollInterval = 5000; // Max 5 seconds\n\n const checkClosed = () => {\n if (authWindow?.closed) {\n Logger.info(\"Authentication window closed by user\");\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication window was closed\"\n )\n );\n return;\n }\n\n // Exponential backoff: increase interval up to max\n pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);\n checkClosedInterval = setTimeout(checkClosed, pollInterval);\n };\n\n checkClosedInterval = setTimeout(checkClosed, pollInterval);\n\n try {\n window.addEventListener(\"message\", listener);\n Logger.debug(\"Message listener attached\");\n } catch (error) {\n Logger.error(\"Failed to attach message listener\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n cleanup();\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to set up message listener: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n return;\n }\n\n // Add focus to the popup for better UX\n try {\n if (authWindow) {\n authWindow.focus();\n }\n } catch {\n // Ignore focus errors (cross-origin restrictions)\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 // Return cached token if available\n if (this.token) return this.token;\n\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 // Return cached token if available, avoiding redundant storage access\n if (this.token) return this.token;\n return this.loadToken();\n }\n\n isExpired(): boolean {\n const token = this.loadToken();\n if (!token) return true;\n\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 isPaddedExpired(): boolean {\n const token = this.loadToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const base64 = parts[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n \"=\"\n );\n const payload = JSON.parse(atob(padded));\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","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 if (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 \n // Add exponential backoff delay for retries\n if (attempts > 1) {\n const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay\n Logger.debug('Retry delay', { delay });\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n \n const response = await openCAMSPopUpLogin(config);\n\n Logger.debug('Login Response', response);\n this.tokenManager.setToken(response.token);\n Logger.info('Session login successful');\n if (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 if (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 private checkTokenExpiration(): boolean {\n if (this.tokenManager.isExpired()) {\n Logger.info('Token expired');\n if (this.events.onTokenExpired) this.events.onTokenExpired();\n return true;\n }\n return false;\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.checkTokenExpiration()) {\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.checkTokenExpiration()) {\n return null;\n }\n \n return token;\n }\n\n private decodeBase64Url(str: string): string {\n // Work with a copy to avoid mutating input\n let result = str.replace(/-/g, '+').replace(/_/g, '/');\n // Add padding if needed\n while (result.length % 4) {\n result += '=';\n }\n return atob(result);\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.tokenManager.loadToken();\n if (!storedToken) return null;\n\n // Check token expiration before processing\n if (this.checkTokenExpiration()) {\n return null;\n }\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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,GAAG,KAAK,CAAC,OAAO,GAAG,eAAe,EAAE,CAAC;QAC1H;AAEA,QAAA,OAAO,IAAI;IACb;AACD;;;;;;;;;;;;;;"}
|
package/dist/index.d.ts
CHANGED
package/dist/index.esm.js
CHANGED
|
@@ -129,7 +129,7 @@ function openCAMSPopUpLogin(config) {
|
|
|
129
129
|
return;
|
|
130
130
|
}
|
|
131
131
|
const { messageOrigin, windowHeight, windowWidth, authTimeout = 300000, // 5 minutes as a final failsafe
|
|
132
|
-
idleTimeout =
|
|
132
|
+
idleTimeout = 120000, // 2 minutes of inactivity
|
|
133
133
|
} = config;
|
|
134
134
|
let authWindow;
|
|
135
135
|
let authTimeoutId = null;
|
|
@@ -178,12 +178,16 @@ function openCAMSPopUpLogin(config) {
|
|
|
178
178
|
data: event.data,
|
|
179
179
|
});
|
|
180
180
|
const originUrl = new URL(event.origin);
|
|
181
|
-
const
|
|
182
|
-
|
|
181
|
+
const expectedHostname = messageOrigin.startsWith('http')
|
|
182
|
+
? new URL(messageOrigin).hostname
|
|
183
|
+
: messageOrigin;
|
|
184
|
+
const isAllowedOrigin = originUrl.hostname === expectedHostname ||
|
|
185
|
+
originUrl.hostname.endsWith("." + expectedHostname);
|
|
183
186
|
if (!isAllowedOrigin) {
|
|
184
187
|
Logger.warn("Blocked message from unauthorized origin", {
|
|
185
188
|
origin: event.origin,
|
|
186
189
|
expected: messageOrigin,
|
|
190
|
+
data: event.data,
|
|
187
191
|
});
|
|
188
192
|
return;
|
|
189
193
|
}
|
|
@@ -339,6 +343,29 @@ class TokenManager {
|
|
|
339
343
|
return true;
|
|
340
344
|
}
|
|
341
345
|
}
|
|
346
|
+
isPaddedExpired() {
|
|
347
|
+
const token = this.loadToken();
|
|
348
|
+
if (!token)
|
|
349
|
+
return true;
|
|
350
|
+
try {
|
|
351
|
+
const parts = token.split(".");
|
|
352
|
+
if (parts.length < 3)
|
|
353
|
+
return true; // Invalid JWT format
|
|
354
|
+
const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
355
|
+
const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=");
|
|
356
|
+
const payload = JSON.parse(atob(padded));
|
|
357
|
+
if (typeof payload.exp !== "number")
|
|
358
|
+
return true;
|
|
359
|
+
const exp = payload.exp * 1000;
|
|
360
|
+
return Date.now() > exp;
|
|
361
|
+
}
|
|
362
|
+
catch (error) {
|
|
363
|
+
Logger.warn("Failed to parse JWT token", {
|
|
364
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
365
|
+
});
|
|
366
|
+
return true;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
342
369
|
}
|
|
343
370
|
|
|
344
371
|
class CAMSSessionManager {
|
|
@@ -354,7 +381,7 @@ class CAMSSessionManager {
|
|
|
354
381
|
if (this.events.onAuthStart)
|
|
355
382
|
this.events.onAuthStart();
|
|
356
383
|
let attempts = 0;
|
|
357
|
-
const maxAttempts = (config.retryAttempts
|
|
384
|
+
const maxAttempts = (config.retryAttempts ?? 0) + 1;
|
|
358
385
|
Logger.debug('Login retry configuration', { maxAttempts });
|
|
359
386
|
while (attempts < maxAttempts) {
|
|
360
387
|
try {
|
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 messageOrigin: string; // Expected message origin\n windowWidth: number;\n windowHeight: number;\n authTimeout?: number; // Auth timeout in ms (default: 300000) // 5 minutes as a final failsafe\n idleTimeout?: number; // 1 minute of inactivity\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 API_VALIDATION_ERROR = \"API_VALIDATION_ERROR\",\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = this.constructor.name;\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 - non-empty string\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\nexport const URLSchema = z.url();","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 readonly prefix = '[CAMS-SDK]';\n private static readonly isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n private static sanitizeForLog(input: any): any {\n if (typeof input === 'string') {\n // Remove newlines and control characters to prevent log injection\n return input.replace(/[\\r\\n\\t]/g, ' ').replace(/[\\x00-\\x1F\\x7F]/g, '');\n }\n if (typeof input === 'object' && input !== null) {\n const sanitized: any = {};\n for (const [key, value] of Object.entries(input)) {\n sanitized[Logger.sanitizeForLog(key)] = Logger.sanitizeForLog(value);\n }\n return sanitized;\n }\n return input;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(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:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(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:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(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:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));\n }\n }\n}","import {\n CAMSConfig,\n CAMSTokenResponse,\n CAMSError,\n CAMSErrorType,\n} from \"./types\";\nimport {\n TokenMessageSchema,\n ErrorMessageSchema,\n URLSchema,\n} from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\nexport function validateConfig(config: CAMSConfig): URL {\n // Validate URL format and parse once\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.messageOrigin) {\n throw new CAMSError(\n CAMSErrorType.INVALID_URL,\n \"Message Origin must be specified for security\"\n );\n }\n\n const url = new URL(config.camsUrl);\n\n return url;\n}\n\nexport function openCAMSPopUpLogin(\n config: CAMSConfig\n): 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 let validatedUrl: URL;\n try {\n validatedUrl = validateConfig(config);\n Logger.debug(\"Config validation passed\");\n } catch (error) {\n Logger.error(\"Config validation failed\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(error as Error);\n return;\n }\n\n const {\n messageOrigin,\n windowHeight,\n windowWidth,\n authTimeout = 300000, // 5 minutes as a final failsafe\n idleTimeout = 60000, // 1 minute of inactivity\n } = config;\n let authWindow: Window | null;\n let authTimeoutId: NodeJS.Timeout | null = null;\n let idleTimeoutId: NodeJS.Timeout | null = null;\n let checkClosedInterval: NodeJS.Timeout | null = null;\n\n try {\n Logger.debug(\"Opening popup window\", {\n width: windowWidth,\n height: windowHeight,\n });\n\n // Center the popup window\n const left = (window.screen.width - windowWidth) / 2;\n const top = (window.screen.height - windowHeight) / 2;\n\n authWindow = window.open(\n validatedUrl.toString(),\n \"_blank\",\n `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes`\n );\n } catch (error) {\n Logger.error(\"Failed to open popup window\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to open authentication window: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n return;\n }\n\n if (!authWindow) {\n Logger.error(\"Popup window blocked\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to open authentication window. Please allow popups.\"\n )\n );\n return;\n }\n\n Logger.debug(\"Popup window opened successfully\");\n\n const cleanup = () => {\n window.removeEventListener(\"message\", listener);\n\n if (idleTimeoutId) clearTimeout(idleTimeoutId);\n if (authTimeoutId) clearTimeout(authTimeoutId);\n if (checkClosedInterval) clearTimeout(checkClosedInterval);\n idleTimeoutId = null;\n authTimeoutId = null;\n checkClosedInterval = null;\n };\n\n const listener = (event: MessageEvent) => {\n Logger.debug(\"Received message\", {\n origin: event.origin,\n expectedOrigin: messageOrigin,\n data: event.data,\n });\n\n const originUrl = new URL(event.origin);\n const isAllowedOrigin =\n originUrl.hostname === messageOrigin ||\n originUrl.hostname.endsWith(\".\" + messageOrigin);\n if (!isAllowedOrigin) {\n Logger.warn(\"Blocked message from unauthorized origin\", {\n origin: event.origin,\n expected: messageOrigin,\n });\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\", {\n error: errorMsg.data.error,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication failed: \" + errorMsg.data.error\n )\n );\n return;\n }\n\n Logger.error(\"Invalid message format received\", {\n messageData: event.data,\n dataType: typeof event.data,\n tokenValidationError: tokenMsg.error\n ? tokenMsg.error.issues\n : undefined,\n errorValidationError: errorMsg.error\n ? errorMsg.error.issues\n : undefined,\n });\n cleanupAndClose(\n new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\")\n );\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 resetIdleTimeout = () => {\n // Timeout handler\n if (idleTimeoutId) clearTimeout(idleTimeoutId);\n Logger.debug(\"Resetting idle timeout\", { idleTimeout });\n idleTimeoutId = setTimeout(() => {\n Logger.warn(\"Authentication idle timeout reached\", { idleTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication timed out due to inactivity after ${idleTimeout}ms`\n )\n );\n }, idleTimeout);\n };\n\n Logger.debug(\"Setting auth timeout\", { authTimeout });\n authTimeoutId = setTimeout(() => {\n Logger.warn(\"Authentication auth timeout reached\", { authTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication process exceeded auth time limit of ${authTimeout}ms`\n )\n );\n }, authTimeout);\n\n resetIdleTimeout();\n\n // Use exponential backoff for popup closure checking\n let pollInterval = 1000; // Start with 1 second\n const maxPollInterval = 5000; // Max 5 seconds\n\n const checkClosed = () => {\n if (authWindow?.closed) {\n Logger.info(\"Authentication window closed by user\");\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication window was closed\"\n )\n );\n return;\n }\n\n // Exponential backoff: increase interval up to max\n pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);\n checkClosedInterval = setTimeout(checkClosed, pollInterval);\n };\n\n checkClosedInterval = setTimeout(checkClosed, pollInterval);\n\n try {\n window.addEventListener(\"message\", listener);\n Logger.debug(\"Message listener attached\");\n } catch (error) {\n Logger.error(\"Failed to attach message listener\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n cleanup();\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to set up message listener: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n return;\n }\n\n // Add focus to the popup for better UX\n try {\n if (authWindow) {\n authWindow.focus();\n }\n } catch {\n // Ignore focus errors (cross-origin restrictions)\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 // Return cached token if available\n if (this.token) return this.token;\n \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 // Return cached token if available, avoiding redundant storage access\n if (this.token) return this.token;\n return this.loadToken();\n }\n\n isExpired(): boolean {\n const token = this.loadToken();\n if (!token) return true;\n\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","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 if (this.events.onAuthStart) this.events.onAuthStart();\n \n let attempts = 0;\n const maxAttempts = (config.retryAttempts !== undefined ? 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 \n // Add exponential backoff delay for retries\n if (attempts > 1) {\n const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay\n Logger.debug('Retry delay', { delay });\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n \n const response = await openCAMSPopUpLogin(config);\n\n Logger.debug('Login Response', response);\n this.tokenManager.setToken(response.token);\n Logger.info('Session login successful');\n if (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 if (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 private checkTokenExpiration(): boolean {\n if (this.tokenManager.isExpired()) {\n Logger.info('Token expired');\n if (this.events.onTokenExpired) this.events.onTokenExpired();\n return true;\n }\n return false;\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.checkTokenExpiration()) {\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.checkTokenExpiration()) {\n return null;\n }\n \n return token;\n }\n\n private decodeBase64Url(str: string): string {\n // Work with a copy to avoid mutating input\n let result = str.replace(/-/g, '+').replace(/_/g, '/');\n // Add padding if needed\n while (result.length % 4) {\n result += '=';\n }\n return atob(result);\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.tokenManager.loadToken();\n if (!storedToken) return null;\n\n // Check token expiration before processing\n if (this.checkTokenExpiration()) {\n return null;\n }\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;AAC7C,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC/C,CAAC,EARW,aAAa,KAAb,aAAa,GAAA,EAAA,CAAA,CAAA;AAUnB,MAAO,SAAU,SAAQ,KAAK,CAAA;AACf,IAAA,IAAA;IAAnB,WAAA,CAAmB,IAAmB,EAAE,OAAe,EAAA;QACrD,KAAK,CAAC,OAAO,CAAC;QADG,IAAA,CAAA,IAAI,GAAJ,IAAI;QAErB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI;IACnC;AACD;;ACzBD;AACO,MAAM,kBA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pC,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/sessionManager.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n messageOrigin: string; // Expected message origin\n windowWidth: number;\n windowHeight: number;\n authTimeout?: number; // Auth timeout in ms (default: 300000) // 5 minutes as a final failsafe\n idleTimeout?: number; // 1 minute of inactivity\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 API_VALIDATION_ERROR = \"API_VALIDATION_ERROR\",\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = this.constructor.name;\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 - non-empty string\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\nexport const URLSchema = z.url();","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 readonly prefix = '[CAMS-SDK]';\n private static readonly isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n private static sanitizeForLog(input: any): any {\n if (typeof input === 'string') {\n // Remove newlines and control characters to prevent log injection\n return input.replace(/[\\r\\n\\t]/g, ' ').replace(/[\\x00-\\x1F\\x7F]/g, '');\n }\n if (typeof input === 'object' && input !== null) {\n const sanitized: any = {};\n for (const [key, value] of Object.entries(input)) {\n sanitized[Logger.sanitizeForLog(key)] = Logger.sanitizeForLog(value);\n }\n return sanitized;\n }\n return input;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(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:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(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:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(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:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));\n }\n }\n}","import {\n CAMSConfig,\n CAMSTokenResponse,\n CAMSError,\n CAMSErrorType,\n} from \"./types\";\nimport {\n TokenMessageSchema,\n ErrorMessageSchema,\n URLSchema,\n} from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\nexport function validateConfig(config: CAMSConfig): URL {\n // Validate URL format and parse once\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.messageOrigin) {\n throw new CAMSError(\n CAMSErrorType.INVALID_URL,\n \"Message Origin must be specified for security\"\n );\n }\n\n const url = new URL(config.camsUrl);\n\n return url;\n}\n\nexport function openCAMSPopUpLogin(\n config: CAMSConfig\n): 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 let validatedUrl: URL;\n try {\n validatedUrl = validateConfig(config);\n Logger.debug(\"Config validation passed\");\n } catch (error) {\n Logger.error(\"Config validation failed\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(error as Error);\n return;\n }\n\n const {\n messageOrigin,\n windowHeight,\n windowWidth,\n authTimeout = 300000, // 5 minutes as a final failsafe\n idleTimeout = 120000, // 2 minutes of inactivity\n } = config;\n let authWindow: Window | null;\n let authTimeoutId: NodeJS.Timeout | null = null;\n let idleTimeoutId: NodeJS.Timeout | null = null;\n let checkClosedInterval: NodeJS.Timeout | null = null;\n\n try {\n Logger.debug(\"Opening popup window\", {\n width: windowWidth,\n height: windowHeight,\n });\n\n // Center the popup window\n const left = (window.screen.width - windowWidth) / 2;\n const top = (window.screen.height - windowHeight) / 2;\n\n authWindow = window.open(\n validatedUrl.toString(),\n \"_blank\",\n `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes`\n );\n } catch (error) {\n Logger.error(\"Failed to open popup window\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to open authentication window: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n return;\n }\n\n if (!authWindow) {\n Logger.error(\"Popup window blocked\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to open authentication window. Please allow popups.\"\n )\n );\n return;\n }\n\n Logger.debug(\"Popup window opened successfully\");\n\n const cleanup = () => {\n window.removeEventListener(\"message\", listener);\n\n if (idleTimeoutId) clearTimeout(idleTimeoutId);\n if (authTimeoutId) clearTimeout(authTimeoutId);\n if (checkClosedInterval) clearTimeout(checkClosedInterval);\n idleTimeoutId = null;\n authTimeoutId = null;\n checkClosedInterval = null;\n };\n\n const listener = (event: MessageEvent) => {\n Logger.debug(\"Received message\", {\n origin: event.origin,\n expectedOrigin: messageOrigin,\n data: event.data,\n });\n\n const originUrl = new URL(event.origin);\n const expectedHostname = messageOrigin.startsWith('http') \n ? new URL(messageOrigin).hostname \n : messageOrigin;\n const isAllowedOrigin =\n originUrl.hostname === expectedHostname ||\n originUrl.hostname.endsWith(\".\" + expectedHostname);\n if (!isAllowedOrigin) {\n Logger.warn(\"Blocked message from unauthorized origin\", {\n origin: event.origin,\n expected: messageOrigin,\n data: event.data,\n });\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\", {\n error: errorMsg.data.error,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication failed: \" + errorMsg.data.error\n )\n );\n return;\n }\n\n Logger.error(\"Invalid message format received\", {\n messageData: event.data,\n dataType: typeof event.data,\n tokenValidationError: tokenMsg.error\n ? tokenMsg.error.issues\n : undefined,\n errorValidationError: errorMsg.error\n ? errorMsg.error.issues\n : undefined,\n });\n cleanupAndClose(\n new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\")\n );\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 resetIdleTimeout = () => {\n // Timeout handler\n if (idleTimeoutId) clearTimeout(idleTimeoutId);\n Logger.debug(\"Resetting idle timeout\", { idleTimeout });\n idleTimeoutId = setTimeout(() => {\n Logger.warn(\"Authentication idle timeout reached\", { idleTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication timed out due to inactivity after ${idleTimeout}ms`\n )\n );\n }, idleTimeout);\n };\n\n Logger.debug(\"Setting auth timeout\", { authTimeout });\n authTimeoutId = setTimeout(() => {\n Logger.warn(\"Authentication auth timeout reached\", { authTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication process exceeded auth time limit of ${authTimeout}ms`\n )\n );\n }, authTimeout);\n\n resetIdleTimeout();\n\n // Use exponential backoff for popup closure checking\n let pollInterval = 1000; // Start with 1 second\n const maxPollInterval = 5000; // Max 5 seconds\n\n const checkClosed = () => {\n if (authWindow?.closed) {\n Logger.info(\"Authentication window closed by user\");\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication window was closed\"\n )\n );\n return;\n }\n\n // Exponential backoff: increase interval up to max\n pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);\n checkClosedInterval = setTimeout(checkClosed, pollInterval);\n };\n\n checkClosedInterval = setTimeout(checkClosed, pollInterval);\n\n try {\n window.addEventListener(\"message\", listener);\n Logger.debug(\"Message listener attached\");\n } catch (error) {\n Logger.error(\"Failed to attach message listener\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n cleanup();\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to set up message listener: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n return;\n }\n\n // Add focus to the popup for better UX\n try {\n if (authWindow) {\n authWindow.focus();\n }\n } catch {\n // Ignore focus errors (cross-origin restrictions)\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 // Return cached token if available\n if (this.token) return this.token;\n\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 // Return cached token if available, avoiding redundant storage access\n if (this.token) return this.token;\n return this.loadToken();\n }\n\n isExpired(): boolean {\n const token = this.loadToken();\n if (!token) return true;\n\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 isPaddedExpired(): boolean {\n const token = this.loadToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const base64 = parts[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n \"=\"\n );\n const payload = JSON.parse(atob(padded));\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","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 if (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 \n // Add exponential backoff delay for retries\n if (attempts > 1) {\n const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay\n Logger.debug('Retry delay', { delay });\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n \n const response = await openCAMSPopUpLogin(config);\n\n Logger.debug('Login Response', response);\n this.tokenManager.setToken(response.token);\n Logger.info('Session login successful');\n if (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 if (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 private checkTokenExpiration(): boolean {\n if (this.tokenManager.isExpired()) {\n Logger.info('Token expired');\n if (this.events.onTokenExpired) this.events.onTokenExpired();\n return true;\n }\n return false;\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.checkTokenExpiration()) {\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.checkTokenExpiration()) {\n return null;\n }\n \n return token;\n }\n\n private decodeBase64Url(str: string): string {\n // Work with a copy to avoid mutating input\n let result = str.replace(/-/g, '+').replace(/_/g, '/');\n // Add padding if needed\n while (result.length % 4) {\n result += '=';\n }\n return atob(result);\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.tokenManager.loadToken();\n if (!storedToken) return null;\n\n // Check token expiration before processing\n if (this.checkTokenExpiration()) {\n return null;\n }\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;AAC7C,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC/C,CAAC,EARW,aAAa,KAAb,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GAAG,IAAI,CAAC,YAAY,CAAC,SAAS,EAAE;AACjD,QAAA,IAAI,CAAC,WAAW;AAAE,YAAA,OAAO,IAAI;;AAG7B,QAAA,IAAI,IAAI,CAAC,oBAAoB,EAAE,EAAE;AAC/B,YAAA,OAAO,IAAI;QACb;AAEA,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;;;;"}
|
package/dist/index.umd.js
CHANGED
|
@@ -133,7 +133,7 @@
|
|
|
133
133
|
return;
|
|
134
134
|
}
|
|
135
135
|
const { messageOrigin, windowHeight, windowWidth, authTimeout = 300000, // 5 minutes as a final failsafe
|
|
136
|
-
idleTimeout =
|
|
136
|
+
idleTimeout = 120000, // 2 minutes of inactivity
|
|
137
137
|
} = config;
|
|
138
138
|
let authWindow;
|
|
139
139
|
let authTimeoutId = null;
|
|
@@ -182,12 +182,16 @@
|
|
|
182
182
|
data: event.data,
|
|
183
183
|
});
|
|
184
184
|
const originUrl = new URL(event.origin);
|
|
185
|
-
const
|
|
186
|
-
|
|
185
|
+
const expectedHostname = messageOrigin.startsWith('http')
|
|
186
|
+
? new URL(messageOrigin).hostname
|
|
187
|
+
: messageOrigin;
|
|
188
|
+
const isAllowedOrigin = originUrl.hostname === expectedHostname ||
|
|
189
|
+
originUrl.hostname.endsWith("." + expectedHostname);
|
|
187
190
|
if (!isAllowedOrigin) {
|
|
188
191
|
Logger.warn("Blocked message from unauthorized origin", {
|
|
189
192
|
origin: event.origin,
|
|
190
193
|
expected: messageOrigin,
|
|
194
|
+
data: event.data,
|
|
191
195
|
});
|
|
192
196
|
return;
|
|
193
197
|
}
|
|
@@ -343,6 +347,29 @@
|
|
|
343
347
|
return true;
|
|
344
348
|
}
|
|
345
349
|
}
|
|
350
|
+
isPaddedExpired() {
|
|
351
|
+
const token = this.loadToken();
|
|
352
|
+
if (!token)
|
|
353
|
+
return true;
|
|
354
|
+
try {
|
|
355
|
+
const parts = token.split(".");
|
|
356
|
+
if (parts.length < 3)
|
|
357
|
+
return true; // Invalid JWT format
|
|
358
|
+
const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
359
|
+
const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=");
|
|
360
|
+
const payload = JSON.parse(atob(padded));
|
|
361
|
+
if (typeof payload.exp !== "number")
|
|
362
|
+
return true;
|
|
363
|
+
const exp = payload.exp * 1000;
|
|
364
|
+
return Date.now() > exp;
|
|
365
|
+
}
|
|
366
|
+
catch (error) {
|
|
367
|
+
Logger.warn("Failed to parse JWT token", {
|
|
368
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
369
|
+
});
|
|
370
|
+
return true;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
346
373
|
}
|
|
347
374
|
|
|
348
375
|
class CAMSSessionManager {
|
|
@@ -358,7 +385,7 @@
|
|
|
358
385
|
if (this.events.onAuthStart)
|
|
359
386
|
this.events.onAuthStart();
|
|
360
387
|
let attempts = 0;
|
|
361
|
-
const maxAttempts = (config.retryAttempts
|
|
388
|
+
const maxAttempts = (config.retryAttempts ?? 0) + 1;
|
|
362
389
|
Logger.debug('Login retry configuration', { maxAttempts });
|
|
363
390
|
while (attempts < maxAttempts) {
|
|
364
391
|
try {
|
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 messageOrigin: string; // Expected message origin\n windowWidth: number;\n windowHeight: number;\n authTimeout?: number; // Auth timeout in ms (default: 300000) // 5 minutes as a final failsafe\n idleTimeout?: number; // 1 minute of inactivity\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 API_VALIDATION_ERROR = \"API_VALIDATION_ERROR\",\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = this.constructor.name;\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 - non-empty string\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\nexport const URLSchema = z.url();","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 readonly prefix = '[CAMS-SDK]';\n private static readonly isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n private static sanitizeForLog(input: any): any {\n if (typeof input === 'string') {\n // Remove newlines and control characters to prevent log injection\n return input.replace(/[\\r\\n\\t]/g, ' ').replace(/[\\x00-\\x1F\\x7F]/g, '');\n }\n if (typeof input === 'object' && input !== null) {\n const sanitized: any = {};\n for (const [key, value] of Object.entries(input)) {\n sanitized[Logger.sanitizeForLog(key)] = Logger.sanitizeForLog(value);\n }\n return sanitized;\n }\n return input;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(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:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(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:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(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:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));\n }\n }\n}","import {\n CAMSConfig,\n CAMSTokenResponse,\n CAMSError,\n CAMSErrorType,\n} from \"./types\";\nimport {\n TokenMessageSchema,\n ErrorMessageSchema,\n URLSchema,\n} from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\nexport function validateConfig(config: CAMSConfig): URL {\n // Validate URL format and parse once\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.messageOrigin) {\n throw new CAMSError(\n CAMSErrorType.INVALID_URL,\n \"Message Origin must be specified for security\"\n );\n }\n\n const url = new URL(config.camsUrl);\n\n return url;\n}\n\nexport function openCAMSPopUpLogin(\n config: CAMSConfig\n): 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 let validatedUrl: URL;\n try {\n validatedUrl = validateConfig(config);\n Logger.debug(\"Config validation passed\");\n } catch (error) {\n Logger.error(\"Config validation failed\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(error as Error);\n return;\n }\n\n const {\n messageOrigin,\n windowHeight,\n windowWidth,\n authTimeout = 300000, // 5 minutes as a final failsafe\n idleTimeout = 60000, // 1 minute of inactivity\n } = config;\n let authWindow: Window | null;\n let authTimeoutId: NodeJS.Timeout | null = null;\n let idleTimeoutId: NodeJS.Timeout | null = null;\n let checkClosedInterval: NodeJS.Timeout | null = null;\n\n try {\n Logger.debug(\"Opening popup window\", {\n width: windowWidth,\n height: windowHeight,\n });\n\n // Center the popup window\n const left = (window.screen.width - windowWidth) / 2;\n const top = (window.screen.height - windowHeight) / 2;\n\n authWindow = window.open(\n validatedUrl.toString(),\n \"_blank\",\n `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes`\n );\n } catch (error) {\n Logger.error(\"Failed to open popup window\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to open authentication window: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n return;\n }\n\n if (!authWindow) {\n Logger.error(\"Popup window blocked\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to open authentication window. Please allow popups.\"\n )\n );\n return;\n }\n\n Logger.debug(\"Popup window opened successfully\");\n\n const cleanup = () => {\n window.removeEventListener(\"message\", listener);\n\n if (idleTimeoutId) clearTimeout(idleTimeoutId);\n if (authTimeoutId) clearTimeout(authTimeoutId);\n if (checkClosedInterval) clearTimeout(checkClosedInterval);\n idleTimeoutId = null;\n authTimeoutId = null;\n checkClosedInterval = null;\n };\n\n const listener = (event: MessageEvent) => {\n Logger.debug(\"Received message\", {\n origin: event.origin,\n expectedOrigin: messageOrigin,\n data: event.data,\n });\n\n const originUrl = new URL(event.origin);\n const isAllowedOrigin =\n originUrl.hostname === messageOrigin ||\n originUrl.hostname.endsWith(\".\" + messageOrigin);\n if (!isAllowedOrigin) {\n Logger.warn(\"Blocked message from unauthorized origin\", {\n origin: event.origin,\n expected: messageOrigin,\n });\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\", {\n error: errorMsg.data.error,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication failed: \" + errorMsg.data.error\n )\n );\n return;\n }\n\n Logger.error(\"Invalid message format received\", {\n messageData: event.data,\n dataType: typeof event.data,\n tokenValidationError: tokenMsg.error\n ? tokenMsg.error.issues\n : undefined,\n errorValidationError: errorMsg.error\n ? errorMsg.error.issues\n : undefined,\n });\n cleanupAndClose(\n new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\")\n );\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 resetIdleTimeout = () => {\n // Timeout handler\n if (idleTimeoutId) clearTimeout(idleTimeoutId);\n Logger.debug(\"Resetting idle timeout\", { idleTimeout });\n idleTimeoutId = setTimeout(() => {\n Logger.warn(\"Authentication idle timeout reached\", { idleTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication timed out due to inactivity after ${idleTimeout}ms`\n )\n );\n }, idleTimeout);\n };\n\n Logger.debug(\"Setting auth timeout\", { authTimeout });\n authTimeoutId = setTimeout(() => {\n Logger.warn(\"Authentication auth timeout reached\", { authTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication process exceeded auth time limit of ${authTimeout}ms`\n )\n );\n }, authTimeout);\n\n resetIdleTimeout();\n\n // Use exponential backoff for popup closure checking\n let pollInterval = 1000; // Start with 1 second\n const maxPollInterval = 5000; // Max 5 seconds\n\n const checkClosed = () => {\n if (authWindow?.closed) {\n Logger.info(\"Authentication window closed by user\");\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication window was closed\"\n )\n );\n return;\n }\n\n // Exponential backoff: increase interval up to max\n pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);\n checkClosedInterval = setTimeout(checkClosed, pollInterval);\n };\n\n checkClosedInterval = setTimeout(checkClosed, pollInterval);\n\n try {\n window.addEventListener(\"message\", listener);\n Logger.debug(\"Message listener attached\");\n } catch (error) {\n Logger.error(\"Failed to attach message listener\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n cleanup();\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to set up message listener: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n return;\n }\n\n // Add focus to the popup for better UX\n try {\n if (authWindow) {\n authWindow.focus();\n }\n } catch {\n // Ignore focus errors (cross-origin restrictions)\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 // Return cached token if available\n if (this.token) return this.token;\n \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 // Return cached token if available, avoiding redundant storage access\n if (this.token) return this.token;\n return this.loadToken();\n }\n\n isExpired(): boolean {\n const token = this.loadToken();\n if (!token) return true;\n\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","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 if (this.events.onAuthStart) this.events.onAuthStart();\n \n let attempts = 0;\n const maxAttempts = (config.retryAttempts !== undefined ? 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 \n // Add exponential backoff delay for retries\n if (attempts > 1) {\n const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay\n Logger.debug('Retry delay', { delay });\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n \n const response = await openCAMSPopUpLogin(config);\n\n Logger.debug('Login Response', response);\n this.tokenManager.setToken(response.token);\n Logger.info('Session login successful');\n if (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 if (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 private checkTokenExpiration(): boolean {\n if (this.tokenManager.isExpired()) {\n Logger.info('Token expired');\n if (this.events.onTokenExpired) this.events.onTokenExpired();\n return true;\n }\n return false;\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.checkTokenExpiration()) {\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.checkTokenExpiration()) {\n return null;\n }\n \n return token;\n }\n\n private decodeBase64Url(str: string): string {\n // Work with a copy to avoid mutating input\n let result = str.replace(/-/g, '+').replace(/_/g, '/');\n // Add padding if needed\n while (result.length % 4) {\n result += '=';\n }\n return atob(result);\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.tokenManager.loadToken();\n if (!storedToken) return null;\n\n // Check token expiration before processing\n if (this.checkTokenExpiration()) {\n return null;\n }\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,C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C;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/sessionManager.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n messageOrigin: string; // Expected message origin\n windowWidth: number;\n windowHeight: number;\n authTimeout?: number; // Auth timeout in ms (default: 300000) // 5 minutes as a final failsafe\n idleTimeout?: number; // 1 minute of inactivity\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 API_VALIDATION_ERROR = \"API_VALIDATION_ERROR\",\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = this.constructor.name;\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 - non-empty string\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\nexport const URLSchema = z.url();","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 readonly prefix = '[CAMS-SDK]';\n private static readonly isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n private static sanitizeForLog(input: any): any {\n if (typeof input === 'string') {\n // Remove newlines and control characters to prevent log injection\n return input.replace(/[\\r\\n\\t]/g, ' ').replace(/[\\x00-\\x1F\\x7F]/g, '');\n }\n if (typeof input === 'object' && input !== null) {\n const sanitized: any = {};\n for (const [key, value] of Object.entries(input)) {\n sanitized[Logger.sanitizeForLog(key)] = Logger.sanitizeForLog(value);\n }\n return sanitized;\n }\n return input;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(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:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(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:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(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:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));\n }\n }\n}","import {\n CAMSConfig,\n CAMSTokenResponse,\n CAMSError,\n CAMSErrorType,\n} from \"./types\";\nimport {\n TokenMessageSchema,\n ErrorMessageSchema,\n URLSchema,\n} from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\nexport function validateConfig(config: CAMSConfig): URL {\n // Validate URL format and parse once\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.messageOrigin) {\n throw new CAMSError(\n CAMSErrorType.INVALID_URL,\n \"Message Origin must be specified for security\"\n );\n }\n\n const url = new URL(config.camsUrl);\n\n return url;\n}\n\nexport function openCAMSPopUpLogin(\n config: CAMSConfig\n): 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 let validatedUrl: URL;\n try {\n validatedUrl = validateConfig(config);\n Logger.debug(\"Config validation passed\");\n } catch (error) {\n Logger.error(\"Config validation failed\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(error as Error);\n return;\n }\n\n const {\n messageOrigin,\n windowHeight,\n windowWidth,\n authTimeout = 300000, // 5 minutes as a final failsafe\n idleTimeout = 120000, // 2 minutes of inactivity\n } = config;\n let authWindow: Window | null;\n let authTimeoutId: NodeJS.Timeout | null = null;\n let idleTimeoutId: NodeJS.Timeout | null = null;\n let checkClosedInterval: NodeJS.Timeout | null = null;\n\n try {\n Logger.debug(\"Opening popup window\", {\n width: windowWidth,\n height: windowHeight,\n });\n\n // Center the popup window\n const left = (window.screen.width - windowWidth) / 2;\n const top = (window.screen.height - windowHeight) / 2;\n\n authWindow = window.open(\n validatedUrl.toString(),\n \"_blank\",\n `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes`\n );\n } catch (error) {\n Logger.error(\"Failed to open popup window\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to open authentication window: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n return;\n }\n\n if (!authWindow) {\n Logger.error(\"Popup window blocked\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to open authentication window. Please allow popups.\"\n )\n );\n return;\n }\n\n Logger.debug(\"Popup window opened successfully\");\n\n const cleanup = () => {\n window.removeEventListener(\"message\", listener);\n\n if (idleTimeoutId) clearTimeout(idleTimeoutId);\n if (authTimeoutId) clearTimeout(authTimeoutId);\n if (checkClosedInterval) clearTimeout(checkClosedInterval);\n idleTimeoutId = null;\n authTimeoutId = null;\n checkClosedInterval = null;\n };\n\n const listener = (event: MessageEvent) => {\n Logger.debug(\"Received message\", {\n origin: event.origin,\n expectedOrigin: messageOrigin,\n data: event.data,\n });\n\n const originUrl = new URL(event.origin);\n const expectedHostname = messageOrigin.startsWith('http') \n ? new URL(messageOrigin).hostname \n : messageOrigin;\n const isAllowedOrigin =\n originUrl.hostname === expectedHostname ||\n originUrl.hostname.endsWith(\".\" + expectedHostname);\n if (!isAllowedOrigin) {\n Logger.warn(\"Blocked message from unauthorized origin\", {\n origin: event.origin,\n expected: messageOrigin,\n data: event.data,\n });\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\", {\n error: errorMsg.data.error,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication failed: \" + errorMsg.data.error\n )\n );\n return;\n }\n\n Logger.error(\"Invalid message format received\", {\n messageData: event.data,\n dataType: typeof event.data,\n tokenValidationError: tokenMsg.error\n ? tokenMsg.error.issues\n : undefined,\n errorValidationError: errorMsg.error\n ? errorMsg.error.issues\n : undefined,\n });\n cleanupAndClose(\n new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\")\n );\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 resetIdleTimeout = () => {\n // Timeout handler\n if (idleTimeoutId) clearTimeout(idleTimeoutId);\n Logger.debug(\"Resetting idle timeout\", { idleTimeout });\n idleTimeoutId = setTimeout(() => {\n Logger.warn(\"Authentication idle timeout reached\", { idleTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication timed out due to inactivity after ${idleTimeout}ms`\n )\n );\n }, idleTimeout);\n };\n\n Logger.debug(\"Setting auth timeout\", { authTimeout });\n authTimeoutId = setTimeout(() => {\n Logger.warn(\"Authentication auth timeout reached\", { authTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication process exceeded auth time limit of ${authTimeout}ms`\n )\n );\n }, authTimeout);\n\n resetIdleTimeout();\n\n // Use exponential backoff for popup closure checking\n let pollInterval = 1000; // Start with 1 second\n const maxPollInterval = 5000; // Max 5 seconds\n\n const checkClosed = () => {\n if (authWindow?.closed) {\n Logger.info(\"Authentication window closed by user\");\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication window was closed\"\n )\n );\n return;\n }\n\n // Exponential backoff: increase interval up to max\n pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);\n checkClosedInterval = setTimeout(checkClosed, pollInterval);\n };\n\n checkClosedInterval = setTimeout(checkClosed, pollInterval);\n\n try {\n window.addEventListener(\"message\", listener);\n Logger.debug(\"Message listener attached\");\n } catch (error) {\n Logger.error(\"Failed to attach message listener\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n cleanup();\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to set up message listener: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n return;\n }\n\n // Add focus to the popup for better UX\n try {\n if (authWindow) {\n authWindow.focus();\n }\n } catch {\n // Ignore focus errors (cross-origin restrictions)\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 // Return cached token if available\n if (this.token) return this.token;\n\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 // Return cached token if available, avoiding redundant storage access\n if (this.token) return this.token;\n return this.loadToken();\n }\n\n isExpired(): boolean {\n const token = this.loadToken();\n if (!token) return true;\n\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 isPaddedExpired(): boolean {\n const token = this.loadToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const base64 = parts[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n \"=\"\n );\n const payload = JSON.parse(atob(padded));\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","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 if (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 \n // Add exponential backoff delay for retries\n if (attempts > 1) {\n const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay\n Logger.debug('Retry delay', { delay });\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n \n const response = await openCAMSPopUpLogin(config);\n\n Logger.debug('Login Response', response);\n this.tokenManager.setToken(response.token);\n Logger.info('Session login successful');\n if (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 if (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 private checkTokenExpiration(): boolean {\n if (this.tokenManager.isExpired()) {\n Logger.info('Token expired');\n if (this.events.onTokenExpired) this.events.onTokenExpired();\n return true;\n }\n return false;\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.checkTokenExpiration()) {\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.checkTokenExpiration()) {\n return null;\n }\n \n return token;\n }\n\n private decodeBase64Url(str: string): string {\n // Work with a copy to avoid mutating input\n let result = str.replace(/-/g, '+').replace(/_/g, '/');\n // Add padding if needed\n while (result.length % 4) {\n result += '=';\n }\n return atob(result);\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.tokenManager.loadToken();\n if (!storedToken) return null;\n\n // Check token expiration before processing\n if (this.checkTokenExpiration()) {\n return null;\n }\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;IAC7C,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;IAC/C,CAAC,EARWA,qBAAa,KAAbA,qBAAa,GAAA,EAAA,CAAA,CAAA;IAUnB,MAAO,SAAU,SAAQ,KAAK,CAAA;IACf,IAAA,IAAA;QAAnB,WAAA,CAAmB,IAAmB,EAAE,OAAe,EAAA;YACrD,KAAK,CAAC,OAAO,CAAC;YADG,IAAA,CAAA,IAAI,GAAJ,IAAI;YAErB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI;QACnC;IACD;;ICzBD;AACO,UAAM,kBAAkB,GAAGC,KAAC,CAAC,MAAM,CAAC;IACzC,IAAA,IAAI,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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;;;;;;;;;;;;;;;;;;"}
|
package/dist/tokenManager.d.ts
CHANGED
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.16",
|
|
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",
|
|
File without changes
|