@nibssplc/cams-sdk 0.0.1-beta.3 → 0.0.1-beta.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +384 -36
- package/dist/auth.d.ts +5 -3
- package/dist/index.cjs.js +430 -187
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +2 -3
- package/dist/index.esm.js +427 -184
- package/dist/index.esm.js.map +1 -1
- package/dist/index.umd.js +430 -187
- package/dist/index.umd.js.map +1 -1
- package/dist/logger.d.ts +19 -0
- package/dist/sessionManager.d.ts +39 -0
- package/dist/types.d.ts +6 -10
- package/dist/validators.d.ts +27 -20
- package/package.json +22 -5
- package/dist/session.d.ts +0 -19
- package/dist/tokenManager.d.ts +0 -12
package/dist/index.umd.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.umd.js","sources":["../src/types.ts","../src/validators.ts","../src/auth.ts","../src/tokenManager.ts","../src/session.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n allowedOrigin: string;\n windowWidth: number;\n windowHeight: number;\n timeout?: number; // Auth timeout in ms (default: 300000)\n allowedDomains?: string[]; // URL allowlist for security\n storageKey?: string; // Custom storage key\n retryAttempts?: number; // Auto-retry on failure (default: 0)\n}\n\nexport enum CAMSErrorType {\n POPUP_BLOCKED = 'POPUP_BLOCKED',\n TIMEOUT = 'TIMEOUT',\n INVALID_ORIGIN = 'INVALID_ORIGIN',\n USER_CANCELLED = 'USER_CANCELLED',\n INVALID_URL = 'INVALID_URL',\n MAX_RETRIES_EXCEEDED = 'MAX_RETRIES_EXCEEDED'\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = 'CAMSError';\n }\n}\n\nexport interface CAMSTokenResponse {\n token: string;\n}\n\nexport interface CAMSErrorResponse {\n error: string;\n}\n","import { z } from \"zod\";\n\n// Validate the returned token - Base64 format with minimum 20 chars\nexport const TokenMessageSchema = z.object({\n access_token: z.string().regex(/^[A-Za-z0-9+/]{20,}={0,2}$/, \"Invalid NIBSS CAMS token format\"),\n});\n\nexport type TokenMessage = z.infer<typeof TokenMessageSchema>;\n\nexport const ErrorMessageSchema = z.object({\n error: z.string(),\n});\n\nexport const TokenSchema = z.object({\n access_token: z.string(),\n refresh_token: z.string().optional(),\n expires_in: z.number(), // in seconds\n token_type: z.string().default(\"Bearer\"),\n id_token: z.string().optional(),\n});\n\nexport type Token = z.infer<typeof TokenSchema>;\n\nexport const ProfileSchema = z.object({\n sub: z.string(), // user ID\n name: z.string().optional(),\n email: z.email({ message: \"Invalid email address\" }).optional(),\n given_name: z.string().optional(),\n family_name: z.string().optional(),\n roles: z.array(z.string()).optional(),\n});\n\nexport type Profile = z.infer<typeof ProfileSchema>;\n\n// URL validation schema - only HTTPS for production security\nexport const URLSchema = z.string().url().refine(\n (url) => url.startsWith('https://'),\n { message: \"Only HTTPS URLs are allowed\" }\n);","import { CAMSConfig, CAMSTokenResponse, CAMSError, CAMSErrorType } from \"./types\";\nimport { TokenMessageSchema, ErrorMessageSchema, URLSchema } from \"./validators\";\n\nexport function validateConfig(config: CAMSConfig): void {\n // Validate URL format\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'Invalid CAMS URL format');\n }\n\n // Domain validation is mandatory for security\n if (!config.allowedDomains?.length) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');\n }\n\n const url = new URL(config.camsUrl); // URLSchema already validated this\n const isAllowed = config.allowedDomains.some(domain => \n url.hostname === domain || url.hostname.endsWith('.' + domain)\n );\n if (!isAllowed) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'URL not in allowed domains list');\n }\n}\n\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<CAMSTokenResponse> {\n return new Promise((resolve, reject) => {\n try {\n validateConfig(config);\n } catch (error) {\n reject(error);\n return;\n }\n\n const { camsUrl, allowedOrigin, windowHeight, windowWidth, timeout = 300000 } = config;\n let authWindow: Window | null;\n let timeoutId: NodeJS.Timeout | null = null;\n let checkClosedInterval: NodeJS.Timeout | null = null;\n \n try {\n authWindow = window.open(\n camsUrl,\n \"NIBSS CAMS Login\",\n `width=${windowWidth},height=${windowHeight}`\n );\n } catch (error) {\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to open authentication window: \" + (error instanceof Error ? error.message : \"Unknown error\")));\n return;\n }\n\n if (!authWindow) {\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to open authentication window. Please allow popups.\"));\n return;\n }\n\n const cleanup = () => {\n window.removeEventListener(\"message\", listener);\n if (timeoutId) clearTimeout(timeoutId);\n if (checkClosedInterval) clearInterval(checkClosedInterval);\n };\n \n const cleanupAndClose = (error?: CAMSError) => {\n cleanup();\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.close();\n }\n } catch {\n // Ignore close errors\n }\n if (error) reject(error);\n };\n\n const listener = (event: MessageEvent) => {\n if (event.origin !== allowedOrigin) {\n // Sanitize origin for logging to prevent log injection\n const sanitizedOrigin = event.origin.replace(/[\\r\\n]/g, '');\n console.warn(\"Blocked message from origin:\", sanitizedOrigin);\n return;\n }\n\n // ✅ Validate payload\n const tokenMsg = TokenMessageSchema.safeParse(event.data);\n if (tokenMsg.success) {\n cleanupAndClose();\n resolve({ token: tokenMsg.data.access_token });\n return;\n }\n\n const errorMsg = ErrorMessageSchema.safeParse(event.data);\n if (errorMsg.success) {\n cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, \"Authentication failed: \" + errorMsg.data.error));\n return;\n }\n\n cleanupAndClose(new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\"));\n };\n\n // Timeout handler\n timeoutId = setTimeout(() => {\n cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));\n }, timeout);\n\n checkClosedInterval = setInterval(() => {\n if (authWindow && authWindow.closed) {\n cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, \"Authentication window was closed\"));\n }\n }, 2000); // Reduced polling frequency\n\n try {\n window.addEventListener(\"message\", listener);\n } catch (error) {\n cleanup();\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to set up message listener: \" + (error instanceof Error ? error.message : \"Unknown error\")));\n return;\n }\n });\n}\n","import { Token, TokenSchema } from \"./validators\";\n\nexport class TokenManager {\n private token: Token | null = null;\n private readonly storageKey: string;\n\n constructor(\n private readonly storage: Storage = sessionStorage,\n storageKey: string = \"cams_token\"\n ) {\n this.storageKey = storageKey;\n }\n\n setToken(token: Token) {\n const parsed = TokenSchema.parse(token);\n this.token = parsed;\n this.storage.setItem(this.storageKey, JSON.stringify(parsed));\n }\n\n loadToken(): Token | null {\n if (this.token) return this.token;\n const raw = this.storage.getItem(this.storageKey);\n if (!raw) return null;\n \n try {\n const parsed = JSON.parse(raw);\n try {\n this.token = TokenSchema.parse(parsed);\n return this.token;\n } catch (validationError) {\n console.warn('Token validation failed:', validationError instanceof Error ? validationError.message : 'Unknown error');\n this.storage.removeItem(this.storageKey);\n return null;\n }\n } catch (parseError) {\n console.warn('Failed to parse stored token JSON:', parseError instanceof Error ? parseError.message : 'Unknown error');\n this.storage.removeItem(this.storageKey);\n return null;\n }\n }\n\n clearToken() {\n this.token = null;\n this.storage.removeItem(this.storageKey);\n }\n\n getAccessToken(): string | null {\n const token = this.loadToken();\n return token?.access_token ?? null;\n }\n\n isExpired(): boolean {\n const token = this.loadToken();\n if (!token) return true;\n\n // JWT expiration check if available\n if (token.id_token) {\n try {\n const parts = token.id_token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const payload = JSON.parse(atob(parts[1]));\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n console.warn('Failed to parse JWT token:', error instanceof Error ? error.message : 'Unknown error');\n return true;\n }\n }\n\n // Fallback: return true for safety when expiration cannot be determined\n return true;\n }\n}\n","import { CAMSConfig, CAMSTokenResponse, CAMSError, CAMSErrorType } from \"./types\";\nimport { TokenManager } from \"./tokenManager\";\nimport { openCAMSPopUpLogin } from \"./auth\";\nimport { Profile, ProfileSchema } from \"./validators\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (token: CAMSTokenResponse) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSession {\n private readonly tokenManager: TokenManager;\n private readonly events: CAMSEvents;\n\n constructor(\n storage: Storage = sessionStorage,\n storageKey?: string,\n events: CAMSEvents = {}\n ) {\n this.tokenManager = new TokenManager(storage, storageKey);\n this.events = events;\n }\n\n async login(config: CAMSConfig): Promise<CAMSTokenResponse> {\n try {\n this.events.onAuthStart?.();\n \n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n \n while (attempts < maxAttempts) {\n try {\n const response = await openCAMSPopUpLogin(config);\n this.events.onAuthSuccess?.(response);\n return response;\n } catch (error) {\n attempts++;\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 }\n }\n \n throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, 'Max retry attempts exceeded');\n } catch (error) {\n const camsError = error instanceof CAMSError ? error : \n new CAMSError(CAMSErrorType.USER_CANCELLED, error instanceof Error ? error.message : 'Unknown error');\n this.events.onAuthError?.(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n this.tokenManager.clearToken();\n }\n\n isAuthenticated(): boolean {\n const token = this.tokenManager.loadToken();\n if (!token) return false;\n \n if (this.tokenManager.isExpired()) {\n this.events.onTokenExpired?.();\n return false;\n }\n \n return true;\n }\n\n getAccessToken(): string | null {\n const token = this.tokenManager.loadToken();\n if (!token) return null;\n \n if (this.tokenManager.isExpired()) {\n this.events.onTokenExpired?.();\n return null;\n }\n \n return token.access_token;\n }\n\n private decodeBase64Url(str: string): string {\n // Convert base64url to base64\n str = str.replace(/-/g, '+').replace(/_/g, '/');\n // Add padding if needed\n while (str.length % 4) {\n str += '=';\n }\n return atob(str);\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.tokenManager.loadToken();\n if (!storedToken?.id_token) return null;\n\n try {\n const parts = storedToken.id_token.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 console.warn('Failed to decode JWT payload:', decodeError instanceof Error ? decodeError.message : 'Unknown error');\n }\n }\n } catch (error) {\n console.warn('Failed to extract profile from token:', error instanceof Error ? error.message : 'Unknown error');\n }\n\n return null;\n }\n}"],"names":["CAMSErrorType","z"],"mappings":";;;;;;AAWYA;IAAZ,CAAA,UAAY,aAAa,EAAA;IACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;IAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;IACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;IACjC,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;IACjC,IAAA,aAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;IAC3B,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;IAC/C,CAAC,EAPWA,qBAAa,KAAbA,qBAAa,GAAA,EAAA,CAAA,CAAA;IASnB,MAAO,SAAU,SAAQ,KAAK,CAAA;QAClC,WAAA,CAAmB,IAAmB,EAAE,OAAe,EAAA;YACrD,KAAK,CAAC,OAAO,CAAC;YADG,IAAA,CAAA,IAAI,GAAJ,IAAI;IAErB,QAAA,IAAI,CAAC,IAAI,GAAG,WAAW;QACzB;IACD;;ICvBD;AACO,UAAM,kBAAkB,GAAGC,KAAC,CAAC,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G,WAAW,CAAC,OAAO,GAAG,eAAe,CAAC;oBACrH;gBACF;YACF;YAAE,OAAO,KAAK,EAAE;IACd,YAAA,OAAO,CAAC,IAAI,CAAC,uCAAuC,EAAE,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,eAAe,CAAC;YACjH;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/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 = \"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}","import { z } from \"zod\";\n\n// Validate the returned token - non-empty string\nexport const ProfileSchema = z.object({\n type: z.literal(\"AUTH_SUCCESS\"),\n userProfile: z\n .object({\n name: z.string(),\n email: z.email(),\n mfaIsEnabled: z.boolean(),\n message: z.string(),\n isAuthenticated: z.boolean(),\n userType: z.enum([\"SUPER_ADMIN\", \"ADMIN\", \"USER\"]),\n redirectURL: z.url().optional(),\n tokens: z.object({\n Nonce: z.string(),\n Bearer: z.string(),\n }),\n }),\n});\n\nexport type Profile = z.infer<typeof ProfileSchema>;\n\nexport const ErrorMessageSchema = z.object({\n error: z.string().min(1, \"Error message cannot be empty\"),\n});\n\nexport const AuthFailureMessageSchema = z.object({\n type: z.literal(\"AUTH_FAILURE\"),\n error: z.string().min(1, \"Error message cannot be empty\"),\n errorCode: z.string(),\n errorDetails: z.object().or(z.any()),\n});\n\nexport type AuthFailureMessage = z.infer<typeof AuthFailureMessageSchema>;\n\nexport const URLSchema = z.url();\n","export enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3\n}\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nexport class Logger {\n private static level: LogLevel = LogLevel.WARN;\n private static 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 static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, message, context || '');\n }\n }\n\n static warn(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {\n console.warn(`${Logger.prefix} WARN:`, message, context || '');\n }\n }\n\n static info(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {\n console.info(`${Logger.prefix} INFO:`, message, context || '');\n }\n }\n\n static debug(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {\n console.debug(`${Logger.prefix} DEBUG:`, message, context || '');\n }\n }\n}","import { CAMSConfig, CAMSError, CAMSErrorType } from \"./types\";\nimport {\n ProfileSchema,\n ErrorMessageSchema,\n AuthFailureMessageSchema,\n URLSchema,\n Profile,\n} from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\n// Capture original functions to prevent tampering\nconst originalWindowOpen = window.open;\nconst originalAddEventListener = window.addEventListener;\nconst originalRemoveEventListener = window.removeEventListener;\nconst originalSetTimeout = window.setTimeout;\nconst originalClearTimeout = window.clearTimeout;\n\n// Generate random window name to prevent targeting\nexport const generateSecureWindowName = () =>\n `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;\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(config: CAMSConfig): Promise<Profile> {\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: number | null = null;\n let idleTimeoutId: number | null = null;\n let checkClosedInterval: number | 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 const secureWindowName = generateSecureWindowName();\n authWindow = originalWindowOpen.call(\n window,\n validatedUrl.toString(),\n secureWindowName,\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 \"Popup blocked by browser. Please allow popups and try again.\"\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 \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n // Only check for immediate closure (true popup blocking)\n if (authWindow.closed) {\n Logger.error(\"Popup immediately closed by blocker\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n Logger.debug(\"Popup window opened successfully\");\n\n const cleanup = () => {\n originalRemoveEventListener.call(window, \"message\", listener);\n\n if (idleTimeoutId) originalClearTimeout(idleTimeoutId);\n if (authTimeoutId) originalClearTimeout(authTimeoutId);\n if (checkClosedInterval) originalClearTimeout(checkClosedInterval);\n idleTimeoutId = null;\n authTimeoutId = null;\n checkClosedInterval = null;\n };\n\n const listener = (event: Event) => {\n const messageEvent = event as MessageEvent;\n Logger.debug(\"Received message\", {\n origin: messageEvent.origin,\n expectedOrigin: messageOrigin,\n data: messageEvent.data,\n });\n\n const originUrl = new URL(messageEvent.origin);\n const expectedHostname = messageOrigin.startsWith(\"http\")\n ? new URL(messageOrigin).hostname\n : messageOrigin;\n\n // Allow Microsoft redirect domains for Azure AD authentication\n const isMicrosoftDomain =\n originUrl.hostname.endsWith(\".microsoft.com\") ||\n originUrl.hostname.endsWith(\".microsoftonline.com\") ||\n originUrl.hostname.endsWith(\".live.com\");\n\n const isAllowedOrigin =\n originUrl.hostname === expectedHostname ||\n originUrl.hostname.endsWith(\".\" + expectedHostname) ||\n isMicrosoftDomain;\n\n if (!isAllowedOrigin) {\n Logger.warn(\"Blocked message from unauthorized origin\", {\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Validate event source\n if (messageEvent.source !== authWindow) {\n Logger.warn(\"Message from unexpected source\", {\n source: messageEvent.source,\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Validate event source\n if (messageEvent.source !== authWindow) {\n Logger.warn(\"Message from unexpected source\", {\n source: messageEvent.source,\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Ignore heartbeat messages\n if (messageEvent.data?.type === \"heartbeat\") {\n Logger.debug(\"Received heartbeat message\");\n resetIdleTimeout();\n return;\n }\n\n // ✅ Validate payload\n const tokenMsg = ProfileSchema.safeParse(messageEvent.data);\n if (tokenMsg.success) {\n Logger.info(\"Authentication successful\");\n cleanupAndClose();\n resolve(tokenMsg.data);\n return;\n }\n\n const authFailureMsg = AuthFailureMessageSchema.safeParse(\n messageEvent.data\n );\n if (authFailureMsg.success) {\n Logger.warn(\"Authentication failure received\", {\n errorDetails: authFailureMsg.data.errorDetails,\n error: authFailureMsg.data.error,\n errorCode: authFailureMsg.data.errorCode,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n \"Authentication failed: \" + authFailureMsg.data.error\n )\n );\n return;\n }\n\n const errorMsg = ErrorMessageSchema.safeParse(messageEvent.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: messageEvent.data,\n dataType: typeof messageEvent.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) originalClearTimeout(idleTimeoutId);\n Logger.debug(\"Resetting idle timeout\", { idleTimeout });\n idleTimeoutId = originalSetTimeout(() => {\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 = originalSetTimeout(() => {\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 = originalSetTimeout(checkClosed, pollInterval);\n };\n\n checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);\n\n try {\n originalAddEventListener.call(window, \"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 && !authWindow.closed) {\n authWindow.focus();\n }\n } catch {\n // Ignore focus errors (cross-origin restrictions)\n }\n });\n}\n","import {\n CAMSConfig,\n CAMSError,\n CAMSErrorType,\n} from \"./types\";\nimport { openCAMSPopUpLogin } from \"./auth\";\nimport { AuthFailureMessage, Profile } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (profile: Profile) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSessionManager {\n private readonly storage: StorageLike;\n private readonly keyPrefix: string;\n private readonly events: CAMSEvents;\n\n private token: string | null = null;\n private profile: Profile | null = null;\n\n constructor(\n storage: StorageLike | null = null,\n keyPrefix?: string,\n events: CAMSEvents = {}\n ) {\n this.storage = storage || getDefaultStorage();\n this.keyPrefix = keyPrefix ?? \"CAMS-SDK\";\n this.events = events;\n }\n\n setItem(key: string, value: string) {\n this.storage.setItem(`${this.keyPrefix}:${key}`, value);\n }\n\n getItem(key: string) {\n return this.storage.getItem(`${this.keyPrefix}:${key}`);\n }\n\n removeItem(key: string) {\n this.storage.removeItem(`${this.keyPrefix}:${key}`);\n }\n\n clear() {\n // clear only CAMS-prefixed items\n Object.keys(this.storage).forEach((k) => {\n if (k.startsWith(this.keyPrefix)) {\n this.storage.removeItem(k);\n }\n });\n }\n\n async login(config: CAMSConfig): Promise<Profile> {\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.profile = response;\n this.setToken(response.userProfile.tokens.Bearer);\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\", {\n attempt: attempts,\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (\n ![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(\n error.type\n )\n ) {\n throw error;\n }\n Logger.info(\"Retrying login\", { nextAttempt: attempts + 1 });\n }\n }\n\n throw new CAMSError(\n CAMSErrorType.MAX_RETRIES_EXCEEDED,\n \"Max retry attempts exceeded\"\n );\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown error\";\n const camsError =\n error instanceof CAMSError\n ? error\n : new CAMSError(CAMSErrorType.USER_CANCELLED, errorMessage);\n Logger.error(\"Session login failed\", {\n error: camsError.message,\n type: camsError.type,\n });\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.clearToken();\n }\n\n setToken(token: string) {\n this.token = token;\n this.storage.setItem(this.keyPrefix, token);\n Logger.debug(\"Token stored\", { storageKey: this.keyPrefix });\n }\n\n getAccessToken(): string | null {\n // Return cached token if available, avoiding redundant storage access\n if (this.token) return this.token;\n\n const raw = this.storage.getItem(this.keyPrefix);\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.keyPrefix);\n Logger.debug(\"Token cleared\");\n }\n\n private isExpired(): boolean {\n const token = this.getAccessToken();\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.getAccessToken();\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 private checkTokenExpiration(): boolean {\n if (this.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.getAccessToken();\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 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.getAccessToken();\n if (!storedToken) return null;\n\n // Check token expiration before processing\n if (this.checkTokenExpiration()) {\n return null;\n }\n\n return this.profile;\n }\n\n getSessionError(): AuthFailureMessage | null {\n return null;\n }\n}\n\ninterface StorageLike {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n [key: string]: any; // allows Object.keys to work\n}\n\n// 🔹 Safe fallback for Node/SSR\nfunction getDefaultStorage(): StorageLike {\n if (typeof window !== \"undefined\" && window.localStorage) {\n return window.localStorage;\n }\n\n const memoryStore: Record<string, string> = {};\n return {\n getItem: (key) => (key in memoryStore ? memoryStore[key] : null),\n setItem: (key, value) => {\n memoryStore[key] = value;\n },\n removeItem: (key) => {\n delete memoryStore[key];\n },\n key: (i: number) => Object.keys(memoryStore)[i] ?? null,\n get length() {\n return Object.keys(memoryStore).length;\n },\n };\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,kBAAyC;IAC3C,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,aAAa,GAAGC,KAAC,CAAC,MAAM,CAAC;IACpC,IAAA,IAAI,EAAEA,KAAC,CAAC,OAAO,CAAC,cAAc,CAAC;IAC/B,IAAA,WAAW,EAAEA;IACV,SAAA,MAAM,CAAC;IACN,QAAA,IAAI,EAAEA,KAAC,CAAC,MAAM,EAAE;IAChB,QAAA,KAAK,EAAE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AE,EAAE;IAC/B,YAAA,OAAO,IAAI;YACb;YAEA,OAAO,IAAI,CAAC,OAAO;QACrB;QAEA,eAAe,GAAA;IACb,QAAA,OAAO,IAAI;QACb;IACD;IASD;IACA,SAAS,iBAAiB,GAAA;QACxB,IAAI,OAAO,MAAM,KAAK,WAAW,IAAI,MAAM,CAAC,YAAY,EAAE;YACxD,OAAO,MAAM,CAAC,YAAY;QAC5B;QAEA,MAAM,WAAW,GAA2B,EAAE;QAC9C,OAAO;YACL,OAAO,EAAE,CAAC,GAAG,MAAM,GAAG,IAAI,WAAW,GAAG,WAAW,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;IAChE,QAAA,OAAO,EAAE,CAAC,GAAG,EAAE,KAAK,KAAI;IACtB,YAAA,WAAW,CAAC,GAAG,CAAC,GAAG,KAAK;YAC1B,CAAC;IACD,QAAA,UAAU,EAAE,CAAC,GAAG,KAAI;IAClB,YAAA,OAAO,WAAW,CAAC,GAAG,CAAC;YACzB,CAAC;IACD,QAAA,GAAG,EAAE,CAAC,CAAS,KAAK,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI;IACvD,QAAA,IAAI,MAAM,GAAA;gBACR,OAAO,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,MAAM;YACxC,CAAC;SACF;IACH;;;;;;;;;;;;;;;;;"}
|
package/dist/logger.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export declare enum LogLevel {
|
|
2
|
+
ERROR = 0,
|
|
3
|
+
WARN = 1,
|
|
4
|
+
INFO = 2,
|
|
5
|
+
DEBUG = 3
|
|
6
|
+
}
|
|
7
|
+
export interface LogContext {
|
|
8
|
+
[key: string]: any;
|
|
9
|
+
}
|
|
10
|
+
export declare class Logger {
|
|
11
|
+
private static level;
|
|
12
|
+
private static readonly prefix;
|
|
13
|
+
private static readonly isTestEnv;
|
|
14
|
+
static setLevel(level: LogLevel): void;
|
|
15
|
+
static error(message: string, context?: LogContext): void;
|
|
16
|
+
static warn(message: string, context?: LogContext): void;
|
|
17
|
+
static info(message: string, context?: LogContext): void;
|
|
18
|
+
static debug(message: string, context?: LogContext): void;
|
|
19
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { CAMSConfig, CAMSError } from "./types";
|
|
2
|
+
import { AuthFailureMessage, Profile } from "./validators";
|
|
3
|
+
export interface CAMSEvents {
|
|
4
|
+
onAuthStart?: () => void;
|
|
5
|
+
onAuthSuccess?: (profile: Profile) => void;
|
|
6
|
+
onAuthError?: (error: CAMSError) => void;
|
|
7
|
+
onTokenExpired?: () => void;
|
|
8
|
+
}
|
|
9
|
+
export declare class CAMSSessionManager {
|
|
10
|
+
private readonly storage;
|
|
11
|
+
private readonly keyPrefix;
|
|
12
|
+
private readonly events;
|
|
13
|
+
private token;
|
|
14
|
+
private profile;
|
|
15
|
+
constructor(storage?: StorageLike | null, keyPrefix?: string, events?: CAMSEvents);
|
|
16
|
+
setItem(key: string, value: string): void;
|
|
17
|
+
getItem(key: string): string | null;
|
|
18
|
+
removeItem(key: string): void;
|
|
19
|
+
clear(): void;
|
|
20
|
+
login(config: CAMSConfig): Promise<Profile>;
|
|
21
|
+
logout(): Promise<void>;
|
|
22
|
+
setToken(token: string): void;
|
|
23
|
+
getAccessToken(): string | null;
|
|
24
|
+
clearToken(): void;
|
|
25
|
+
private isExpired;
|
|
26
|
+
isPaddedExpired(): boolean;
|
|
27
|
+
private checkTokenExpiration;
|
|
28
|
+
isAuthenticated(): boolean;
|
|
29
|
+
private decodeBase64Url;
|
|
30
|
+
getProfile(): Promise<Profile | null>;
|
|
31
|
+
getSessionError(): AuthFailureMessage | null;
|
|
32
|
+
}
|
|
33
|
+
interface StorageLike {
|
|
34
|
+
getItem(key: string): string | null;
|
|
35
|
+
setItem(key: string, value: string): void;
|
|
36
|
+
removeItem(key: string): void;
|
|
37
|
+
[key: string]: any;
|
|
38
|
+
}
|
|
39
|
+
export {};
|
package/dist/types.d.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
export interface CAMSConfig {
|
|
2
2
|
camsUrl: string;
|
|
3
|
-
|
|
3
|
+
messageOrigin: string;
|
|
4
4
|
windowWidth: number;
|
|
5
5
|
windowHeight: number;
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
authTimeout?: number;
|
|
7
|
+
idleTimeout?: number;
|
|
8
8
|
storageKey?: string;
|
|
9
9
|
retryAttempts?: number;
|
|
10
|
+
debug?: boolean;
|
|
10
11
|
}
|
|
11
12
|
export declare enum CAMSErrorType {
|
|
12
13
|
POPUP_BLOCKED = "POPUP_BLOCKED",
|
|
@@ -14,15 +15,10 @@ export declare enum CAMSErrorType {
|
|
|
14
15
|
INVALID_ORIGIN = "INVALID_ORIGIN",
|
|
15
16
|
USER_CANCELLED = "USER_CANCELLED",
|
|
16
17
|
INVALID_URL = "INVALID_URL",
|
|
17
|
-
MAX_RETRIES_EXCEEDED = "MAX_RETRIES_EXCEEDED"
|
|
18
|
+
MAX_RETRIES_EXCEEDED = "MAX_RETRIES_EXCEEDED",
|
|
19
|
+
API_VALIDATION_ERROR = "VALIDATION_ERROR"
|
|
18
20
|
}
|
|
19
21
|
export declare class CAMSError extends Error {
|
|
20
22
|
type: CAMSErrorType;
|
|
21
23
|
constructor(type: CAMSErrorType, message: string);
|
|
22
24
|
}
|
|
23
|
-
export interface CAMSTokenResponse {
|
|
24
|
-
token: string;
|
|
25
|
-
}
|
|
26
|
-
export interface CAMSErrorResponse {
|
|
27
|
-
error: string;
|
|
28
|
-
}
|
package/dist/validators.d.ts
CHANGED
|
@@ -1,26 +1,33 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
export declare const
|
|
3
|
-
|
|
2
|
+
export declare const ProfileSchema: z.ZodObject<{
|
|
3
|
+
type: z.ZodLiteral<"AUTH_SUCCESS">;
|
|
4
|
+
userProfile: z.ZodObject<{
|
|
5
|
+
name: z.ZodString;
|
|
6
|
+
email: z.ZodEmail;
|
|
7
|
+
mfaIsEnabled: z.ZodBoolean;
|
|
8
|
+
message: z.ZodString;
|
|
9
|
+
isAuthenticated: z.ZodBoolean;
|
|
10
|
+
userType: z.ZodEnum<{
|
|
11
|
+
SUPER_ADMIN: "SUPER_ADMIN";
|
|
12
|
+
ADMIN: "ADMIN";
|
|
13
|
+
USER: "USER";
|
|
14
|
+
}>;
|
|
15
|
+
redirectURL: z.ZodOptional<z.ZodURL>;
|
|
16
|
+
tokens: z.ZodObject<{
|
|
17
|
+
Nonce: z.ZodString;
|
|
18
|
+
Bearer: z.ZodString;
|
|
19
|
+
}, z.core.$strip>;
|
|
20
|
+
}, z.core.$strip>;
|
|
4
21
|
}, z.core.$strip>;
|
|
5
|
-
export type
|
|
22
|
+
export type Profile = z.infer<typeof ProfileSchema>;
|
|
6
23
|
export declare const ErrorMessageSchema: z.ZodObject<{
|
|
7
24
|
error: z.ZodString;
|
|
8
25
|
}, z.core.$strip>;
|
|
9
|
-
export declare const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
id_token: z.ZodOptional<z.ZodString>;
|
|
15
|
-
}, z.core.$strip>;
|
|
16
|
-
export type Token = z.infer<typeof TokenSchema>;
|
|
17
|
-
export declare const ProfileSchema: z.ZodObject<{
|
|
18
|
-
sub: z.ZodString;
|
|
19
|
-
name: z.ZodOptional<z.ZodString>;
|
|
20
|
-
email: z.ZodOptional<z.ZodEmail>;
|
|
21
|
-
given_name: z.ZodOptional<z.ZodString>;
|
|
22
|
-
family_name: z.ZodOptional<z.ZodString>;
|
|
23
|
-
roles: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
26
|
+
export declare const AuthFailureMessageSchema: z.ZodObject<{
|
|
27
|
+
type: z.ZodLiteral<"AUTH_FAILURE">;
|
|
28
|
+
error: z.ZodString;
|
|
29
|
+
errorCode: z.ZodString;
|
|
30
|
+
errorDetails: z.ZodUnion<[z.ZodObject<{}, z.core.$strip>, z.ZodAny]>;
|
|
24
31
|
}, z.core.$strip>;
|
|
25
|
-
export type
|
|
26
|
-
export declare const URLSchema: z.
|
|
32
|
+
export type AuthFailureMessage = z.infer<typeof AuthFailureMessageSchema>;
|
|
33
|
+
export declare const URLSchema: z.ZodURL;
|
package/package.json
CHANGED
|
@@ -1,17 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nibssplc/cams-sdk",
|
|
3
|
-
"version": "0.0.1-beta.
|
|
3
|
+
"version": "0.0.1-beta.31",
|
|
4
|
+
"workspaces": [
|
|
5
|
+
"packages/*"
|
|
6
|
+
],
|
|
4
7
|
"description": "Central Authentication Management Service (CAMS) SDK for popup-based authentication with Azure AD + custom 2FA",
|
|
5
8
|
"main": "dist/index.cjs.js",
|
|
6
9
|
"module": "dist/index.esm.js",
|
|
7
10
|
"unpkg": "dist/index.umd.js",
|
|
8
|
-
"types": "dist/
|
|
11
|
+
"types": "dist/index.d.ts",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"import": "./dist/index.esm.js",
|
|
16
|
+
"require": "./dist/index.cjs.js",
|
|
17
|
+
"default": "./dist/index.esm.js"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
9
20
|
"scripts": {
|
|
10
|
-
"
|
|
11
|
-
"
|
|
21
|
+
"clean": "rm -rf dist || true",
|
|
22
|
+
"build": "npx rollup -c",
|
|
12
23
|
"prepare": "npm run clean && npm run build",
|
|
13
24
|
"lint": "eslint src --ext .ts",
|
|
14
|
-
"test": "npx jest"
|
|
25
|
+
"test": "npx jest --verbose",
|
|
26
|
+
"build:react": "cd packages/react && npm run build",
|
|
27
|
+
"test:react": "cd packages/react && npm run test",
|
|
28
|
+
"publish:all": "./scripts/publish.sh",
|
|
29
|
+
"postpublish": "echo '✅ Published $(npm pkg get name)@$(npm pkg get version)'"
|
|
15
30
|
},
|
|
16
31
|
"keywords": [
|
|
17
32
|
"cams",
|
|
@@ -24,6 +39,8 @@
|
|
|
24
39
|
"author": "NIBSS PLC, Caleb Boluwade",
|
|
25
40
|
"license": "MIT",
|
|
26
41
|
"dependencies": {
|
|
42
|
+
"@types/react": "^19.1.13",
|
|
43
|
+
"react": "^19.1.1",
|
|
27
44
|
"tslib": "^2.6.0",
|
|
28
45
|
"zod": "^4.0.17"
|
|
29
46
|
},
|
package/dist/session.d.ts
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import { CAMSConfig, CAMSTokenResponse, CAMSError } from "./types";
|
|
2
|
-
import { Profile } from "./validators";
|
|
3
|
-
export interface CAMSEvents {
|
|
4
|
-
onAuthStart?: () => void;
|
|
5
|
-
onAuthSuccess?: (token: CAMSTokenResponse) => void;
|
|
6
|
-
onAuthError?: (error: CAMSError) => void;
|
|
7
|
-
onTokenExpired?: () => void;
|
|
8
|
-
}
|
|
9
|
-
export declare class CAMSSession {
|
|
10
|
-
private readonly tokenManager;
|
|
11
|
-
private readonly events;
|
|
12
|
-
constructor(storage?: Storage, storageKey?: string, events?: CAMSEvents);
|
|
13
|
-
login(config: CAMSConfig): Promise<CAMSTokenResponse>;
|
|
14
|
-
logout(): Promise<void>;
|
|
15
|
-
isAuthenticated(): boolean;
|
|
16
|
-
getAccessToken(): string | null;
|
|
17
|
-
private decodeBase64Url;
|
|
18
|
-
getProfile(): Promise<Profile | null>;
|
|
19
|
-
}
|
package/dist/tokenManager.d.ts
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import { Token } from "./validators";
|
|
2
|
-
export declare class TokenManager {
|
|
3
|
-
private readonly storage;
|
|
4
|
-
private token;
|
|
5
|
-
private readonly storageKey;
|
|
6
|
-
constructor(storage?: Storage, storageKey?: string);
|
|
7
|
-
setToken(token: Token): void;
|
|
8
|
-
loadToken(): Token | null;
|
|
9
|
-
clearToken(): void;
|
|
10
|
-
getAccessToken(): string | null;
|
|
11
|
-
isExpired(): boolean;
|
|
12
|
-
}
|