@nibssplc/cams-sdk 0.0.1-beta.7 → 0.0.1-beta.9
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 +21 -18
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +0 -3
- package/dist/index.esm.js +21 -18
- package/dist/index.esm.js.map +1 -1
- package/dist/index.umd.js +21 -18
- package/dist/index.umd.js.map +1 -1
- package/dist/validators.d.ts +1 -1
- package/package.json +10 -2
package/dist/index.cjs.js
CHANGED
|
@@ -41,18 +41,23 @@ const ProfileSchema = zod.z.object({
|
|
|
41
41
|
family_name: zod.z.string().optional(),
|
|
42
42
|
roles: zod.z.array(zod.z.string()).optional(),
|
|
43
43
|
});
|
|
44
|
-
//
|
|
45
|
-
const
|
|
44
|
+
// Matches IPv4 addresses like 192.168.x.x, 10.x.x.x, 172.16–31.x.x
|
|
45
|
+
const internalIpRegex = /^(http:\/\/|https:\/\/)((10\.\d{1,3}\.\d{1,3}\.\d{1,3})|(192\.168\.\d{1,3}\.\d{1,3})|(172\.(1[6-9]|2\d|3[0-1])\.\d{1,3}\.\d{1,3}))(:\d+)?$/;
|
|
46
|
+
const URLSchema = zod.z.url().refine((url) => url.startsWith("https://") || // normal HTTPS
|
|
47
|
+
/^http:\/\/localhost(:\d+)?$/i.test(url) || // localhost
|
|
48
|
+
internalIpRegex.test(url), // internal LAN IPs
|
|
49
|
+
{
|
|
50
|
+
message: "Only HTTPS, http://localhost, or internal IPs (192.168.x.x, 10.x.x.x, 172.16–31.x.x) are allowed",
|
|
51
|
+
});
|
|
46
52
|
|
|
47
53
|
function validateConfig(config) {
|
|
48
|
-
var _a;
|
|
49
54
|
// Validate URL format
|
|
50
55
|
const urlValidation = URLSchema.safeParse(config.camsUrl);
|
|
51
56
|
if (!urlValidation.success) {
|
|
52
57
|
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'Invalid CAMS URL format');
|
|
53
58
|
}
|
|
54
59
|
// Domain validation is mandatory for security
|
|
55
|
-
if (!
|
|
60
|
+
if (!config.allowedDomains?.length) {
|
|
56
61
|
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');
|
|
57
62
|
}
|
|
58
63
|
const url = new URL(config.camsUrl); // URLSchema already validated this
|
|
@@ -147,10 +152,10 @@ function openCAMSPopUpLogin(config) {
|
|
|
147
152
|
}
|
|
148
153
|
|
|
149
154
|
class TokenManager {
|
|
150
|
-
constructor(storage = sessionStorage, storageKey
|
|
155
|
+
constructor(storage = sessionStorage, storageKey) {
|
|
151
156
|
this.storage = storage;
|
|
152
157
|
this.token = null;
|
|
153
|
-
this.storageKey = storageKey;
|
|
158
|
+
this.storageKey = storageKey || "cams_token";
|
|
154
159
|
}
|
|
155
160
|
setToken(token) {
|
|
156
161
|
const parsed = TokenSchema.parse(token);
|
|
@@ -186,9 +191,8 @@ class TokenManager {
|
|
|
186
191
|
this.storage.removeItem(this.storageKey);
|
|
187
192
|
}
|
|
188
193
|
getAccessToken() {
|
|
189
|
-
var _a;
|
|
190
194
|
const token = this.loadToken();
|
|
191
|
-
return
|
|
195
|
+
return token ? token.access_token : null;
|
|
192
196
|
}
|
|
193
197
|
isExpired() {
|
|
194
198
|
const token = this.loadToken();
|
|
@@ -201,6 +205,8 @@ class TokenManager {
|
|
|
201
205
|
if (parts.length < 3)
|
|
202
206
|
return true; // Invalid JWT format
|
|
203
207
|
const payload = JSON.parse(atob(parts[1]));
|
|
208
|
+
if (typeof payload.exp !== 'number')
|
|
209
|
+
return true;
|
|
204
210
|
const exp = payload.exp * 1000;
|
|
205
211
|
return Date.now() > exp;
|
|
206
212
|
}
|
|
@@ -220,15 +226,14 @@ class CAMSSession {
|
|
|
220
226
|
this.events = events;
|
|
221
227
|
}
|
|
222
228
|
async login(config) {
|
|
223
|
-
var _a, _b, _c, _d, _e, _f, _g;
|
|
224
229
|
try {
|
|
225
|
-
|
|
230
|
+
this.events.onAuthStart && this.events.onAuthStart();
|
|
226
231
|
let attempts = 0;
|
|
227
|
-
const maxAttempts = (
|
|
232
|
+
const maxAttempts = (config.retryAttempts ?? 0) + 1;
|
|
228
233
|
while (attempts < maxAttempts) {
|
|
229
234
|
try {
|
|
230
235
|
const response = await openCAMSPopUpLogin(config);
|
|
231
|
-
|
|
236
|
+
this.events.onAuthSuccess && this.events.onAuthSuccess(response);
|
|
232
237
|
return response;
|
|
233
238
|
}
|
|
234
239
|
catch (error) {
|
|
@@ -247,7 +252,7 @@ class CAMSSession {
|
|
|
247
252
|
catch (error) {
|
|
248
253
|
const camsError = error instanceof CAMSError ? error :
|
|
249
254
|
new CAMSError(exports.CAMSErrorType.USER_CANCELLED, error instanceof Error ? error.message : 'Unknown error');
|
|
250
|
-
|
|
255
|
+
this.events.onAuthError && this.events.onAuthError(camsError);
|
|
251
256
|
throw camsError;
|
|
252
257
|
}
|
|
253
258
|
}
|
|
@@ -255,23 +260,21 @@ class CAMSSession {
|
|
|
255
260
|
this.tokenManager.clearToken();
|
|
256
261
|
}
|
|
257
262
|
isAuthenticated() {
|
|
258
|
-
var _a, _b;
|
|
259
263
|
const token = this.tokenManager.loadToken();
|
|
260
264
|
if (!token)
|
|
261
265
|
return false;
|
|
262
266
|
if (this.tokenManager.isExpired()) {
|
|
263
|
-
|
|
267
|
+
this.events.onTokenExpired?.();
|
|
264
268
|
return false;
|
|
265
269
|
}
|
|
266
270
|
return true;
|
|
267
271
|
}
|
|
268
272
|
getAccessToken() {
|
|
269
|
-
var _a, _b;
|
|
270
273
|
const token = this.tokenManager.loadToken();
|
|
271
274
|
if (!token)
|
|
272
275
|
return null;
|
|
273
276
|
if (this.tokenManager.isExpired()) {
|
|
274
|
-
|
|
277
|
+
this.events.onTokenExpired?.();
|
|
275
278
|
return null;
|
|
276
279
|
}
|
|
277
280
|
return token.access_token;
|
|
@@ -287,7 +290,7 @@ class CAMSSession {
|
|
|
287
290
|
}
|
|
288
291
|
async getProfile() {
|
|
289
292
|
const storedToken = this.tokenManager.loadToken();
|
|
290
|
-
if (!
|
|
293
|
+
if (!storedToken || !storedToken.id_token)
|
|
291
294
|
return null;
|
|
292
295
|
try {
|
|
293
296
|
const parts = storedToken.id_token.split('.');
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.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;AAAZ,CAAA,UAAY,aAAa,EAAA;AACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;AAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;AAC3B,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC/C,CAAC,EAPWA,qBAAa,KAAbA,qBAAa,GAAA,EAAA,CAAA,CAAA;AASnB,MAAO,SAAU,SAAQ,KAAK,CAAA;IAClC,WAAA,CAAmB,IAAmB,EAAE,OAAe,EAAA;QACrD,KAAK,CAAC,OAAO,CAAC;QADG,IAAA,CAAA,IAAI,GAAJ,IAAI;AAErB,QAAA,IAAI,CAAC,IAAI,GAAG,WAAW;IACzB;AACD;;ACvBD;AACO,MAAM,kBAAkB,GAAGC,KAAC,CAAC,MAAM,CAAC;IACzC,YAAY,EAAEA,KAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,4BAA4B,EAAE,iCAAiC,CAAC;AAChG,CAAA;AAIM,MAAM,kBAAkB,GAAGA,KAAC,CAAC,MAAM,CAAC;AACzC,IAAA,KAAK,EAAEA,KAAC,CAAC,MAAM,EAAE;AAClB,CAAA;AAEM,MAAM,WAAW,GAAGA,KAAC,CAAC,MAAM,CAAC;AAClC,IAAA,YAAY,EAAEA,KAAC,CAAC,MAAM,EAAE;AACxB,IAAA,aAAa,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AAE,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC;;AAE/C,QAAA,OAAO,GAAG,CAAC,MAAM,GAAG,CAAC,EAAE;YACrB,GAAG,IAAI,GAAG;QACZ;AACA,QAAA,OAAO,IAAI,CAAC,GAAG,CAAC;IAClB;AAEA,IAAA,MAAM,UAAU,GAAA;QACd,MAAM,WAAW,GAAG,IAAI,CAAC,YAAY,CAAC,SAAS,EAAE;QACjD,IAAI,EAAC,WAAW,KAAA,IAAA,IAAX,WAAW,KAAA,MAAA,GAAA,MAAA,GAAX,WAAW,CAAE,QAAQ,CAAA;AAAE,YAAA,OAAO,IAAI;AAEvC,QAAA,IAAI;YACF,MAAM,KAAK,GAAG,WAAW,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC;YAC7C,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;AACpB,oBAAA,OAAO,CAAC,IAAI,CAAC,+BAA+B,EAAE,WAAW,YAAY,KAAK,GAAG,WAAW,CAAC,OAAO,GAAG,eAAe,CAAC;gBACrH;YACF;QACF;QAAE,OAAO,KAAK,EAAE;AACd,YAAA,OAAO,CAAC,IAAI,CAAC,uCAAuC,EAAE,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,eAAe,CAAC;QACjH;AAEA,QAAA,OAAO,IAAI;IACb;AACD;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.cjs.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// Matches IPv4 addresses like 192.168.x.x, 10.x.x.x, 172.16–31.x.x\nconst internalIpRegex =\n /^(http:\\/\\/|https:\\/\\/)((10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})|(192\\.168\\.\\d{1,3}\\.\\d{1,3})|(172\\.(1[6-9]|2\\d|3[0-1])\\.\\d{1,3}\\.\\d{1,3}))(:\\d+)?$/;\n\nexport const URLSchema = z.url().refine(\n (url) =>\n url.startsWith(\"https://\") || // normal HTTPS\n /^http:\\/\\/localhost(:\\d+)?$/i.test(url) || // localhost\n internalIpRegex.test(url), // internal LAN IPs\n {\n message:\n \"Only HTTPS, http://localhost, or internal IPs (192.168.x.x, 10.x.x.x, 172.16–31.x.x) are allowed\",\n }\n);","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\n ) {\n this.storageKey = storageKey || \"cams_token\";\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 ? 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 if (typeof payload.exp !== 'number') return true;\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 && 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 && 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 && 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 || !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;AAAZ,CAAA,UAAY,aAAa,EAAA;AACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;AAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;AAC3B,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC/C,CAAC,EAPWA,qBAAa,KAAbA,qBAAa,GAAA,EAAA,CAAA,CAAA;AASnB,MAAO,SAAU,SAAQ,KAAK,CAAA;IAClC,WAAA,CAAmB,IAAmB,EAAE,OAAe,EAAA;QACrD,KAAK,CAAC,OAAO,CAAC;QADG,IAAA,CAAA,IAAI,GAAJ,IAAI;AAErB,QAAA,IAAI,CAAC,IAAI,GAAG,WAAW;IACzB;AACD;;ACvBD;AACO,MAAM,kBAAkB,GAAGC,KAAC,CAAC,MAAM,CAAC;IACzC,YAAY,EAAEA,KAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,4BAA4B,EAAE,iCAAiC,CAAC;AAChG,CAAA;AAIM,MAAM,kBAAkB,GAAGA,KAAC,CAAC,MAAM,CAAC;AACzC,IAAA,KAAK,EAAEA,KAAC,CAAC,MAAM,EAAE;AAClB,CAAA;AAEM,MAAM,WA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AEA,IAAA,MAAM,UAAU,GAAA;QACd,MAAM,WAAW,GAAG,IAAI,CAAC,YAAY,CAAC,SAAS,EAAE;AACjD,QAAA,IAAI,CAAC,WAAW,IAAI,CAAC,WAAW,CAAC,QAAQ;AAAE,YAAA,OAAO,IAAI;AAEtD,QAAA,IAAI;YACF,MAAM,KAAK,GAAG,WAAW,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC;YAC7C,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;AACpB,oBAAA,OAAO,CAAC,IAAI,CAAC,+BAA+B,EAAE,WAAW,YAAY,KAAK,GAAG,WAAW,CAAC,OAAO,GAAG,eAAe,CAAC;gBACrH;YACF;QACF;QAAE,OAAO,KAAK,EAAE;AACd,YAAA,OAAO,CAAC,IAAI,CAAC,uCAAuC,EAAE,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,eAAe,CAAC;QACjH;AAEA,QAAA,OAAO,IAAI;IACb;AACD;;;;;;;;;;;;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -3,6 +3,3 @@ export * from "./types";
|
|
|
3
3
|
export * from "./validators";
|
|
4
4
|
export * from "./tokenManager";
|
|
5
5
|
export * from "./session";
|
|
6
|
-
export { openCAMSPopUpLogin, validateConfig } from "./auth";
|
|
7
|
-
export { CAMSSession, CAMSEvents } from "./session";
|
|
8
|
-
export { TokenManager } from "./tokenManager";
|
package/dist/index.esm.js
CHANGED
|
@@ -39,18 +39,23 @@ const ProfileSchema = z.object({
|
|
|
39
39
|
family_name: z.string().optional(),
|
|
40
40
|
roles: z.array(z.string()).optional(),
|
|
41
41
|
});
|
|
42
|
-
//
|
|
43
|
-
const
|
|
42
|
+
// Matches IPv4 addresses like 192.168.x.x, 10.x.x.x, 172.16–31.x.x
|
|
43
|
+
const internalIpRegex = /^(http:\/\/|https:\/\/)((10\.\d{1,3}\.\d{1,3}\.\d{1,3})|(192\.168\.\d{1,3}\.\d{1,3})|(172\.(1[6-9]|2\d|3[0-1])\.\d{1,3}\.\d{1,3}))(:\d+)?$/;
|
|
44
|
+
const URLSchema = z.url().refine((url) => url.startsWith("https://") || // normal HTTPS
|
|
45
|
+
/^http:\/\/localhost(:\d+)?$/i.test(url) || // localhost
|
|
46
|
+
internalIpRegex.test(url), // internal LAN IPs
|
|
47
|
+
{
|
|
48
|
+
message: "Only HTTPS, http://localhost, or internal IPs (192.168.x.x, 10.x.x.x, 172.16–31.x.x) are allowed",
|
|
49
|
+
});
|
|
44
50
|
|
|
45
51
|
function validateConfig(config) {
|
|
46
|
-
var _a;
|
|
47
52
|
// Validate URL format
|
|
48
53
|
const urlValidation = URLSchema.safeParse(config.camsUrl);
|
|
49
54
|
if (!urlValidation.success) {
|
|
50
55
|
throw new CAMSError(CAMSErrorType.INVALID_URL, 'Invalid CAMS URL format');
|
|
51
56
|
}
|
|
52
57
|
// Domain validation is mandatory for security
|
|
53
|
-
if (!
|
|
58
|
+
if (!config.allowedDomains?.length) {
|
|
54
59
|
throw new CAMSError(CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');
|
|
55
60
|
}
|
|
56
61
|
const url = new URL(config.camsUrl); // URLSchema already validated this
|
|
@@ -145,10 +150,10 @@ function openCAMSPopUpLogin(config) {
|
|
|
145
150
|
}
|
|
146
151
|
|
|
147
152
|
class TokenManager {
|
|
148
|
-
constructor(storage = sessionStorage, storageKey
|
|
153
|
+
constructor(storage = sessionStorage, storageKey) {
|
|
149
154
|
this.storage = storage;
|
|
150
155
|
this.token = null;
|
|
151
|
-
this.storageKey = storageKey;
|
|
156
|
+
this.storageKey = storageKey || "cams_token";
|
|
152
157
|
}
|
|
153
158
|
setToken(token) {
|
|
154
159
|
const parsed = TokenSchema.parse(token);
|
|
@@ -184,9 +189,8 @@ class TokenManager {
|
|
|
184
189
|
this.storage.removeItem(this.storageKey);
|
|
185
190
|
}
|
|
186
191
|
getAccessToken() {
|
|
187
|
-
var _a;
|
|
188
192
|
const token = this.loadToken();
|
|
189
|
-
return
|
|
193
|
+
return token ? token.access_token : null;
|
|
190
194
|
}
|
|
191
195
|
isExpired() {
|
|
192
196
|
const token = this.loadToken();
|
|
@@ -199,6 +203,8 @@ class TokenManager {
|
|
|
199
203
|
if (parts.length < 3)
|
|
200
204
|
return true; // Invalid JWT format
|
|
201
205
|
const payload = JSON.parse(atob(parts[1]));
|
|
206
|
+
if (typeof payload.exp !== 'number')
|
|
207
|
+
return true;
|
|
202
208
|
const exp = payload.exp * 1000;
|
|
203
209
|
return Date.now() > exp;
|
|
204
210
|
}
|
|
@@ -218,15 +224,14 @@ class CAMSSession {
|
|
|
218
224
|
this.events = events;
|
|
219
225
|
}
|
|
220
226
|
async login(config) {
|
|
221
|
-
var _a, _b, _c, _d, _e, _f, _g;
|
|
222
227
|
try {
|
|
223
|
-
|
|
228
|
+
this.events.onAuthStart && this.events.onAuthStart();
|
|
224
229
|
let attempts = 0;
|
|
225
|
-
const maxAttempts = (
|
|
230
|
+
const maxAttempts = (config.retryAttempts ?? 0) + 1;
|
|
226
231
|
while (attempts < maxAttempts) {
|
|
227
232
|
try {
|
|
228
233
|
const response = await openCAMSPopUpLogin(config);
|
|
229
|
-
|
|
234
|
+
this.events.onAuthSuccess && this.events.onAuthSuccess(response);
|
|
230
235
|
return response;
|
|
231
236
|
}
|
|
232
237
|
catch (error) {
|
|
@@ -245,7 +250,7 @@ class CAMSSession {
|
|
|
245
250
|
catch (error) {
|
|
246
251
|
const camsError = error instanceof CAMSError ? error :
|
|
247
252
|
new CAMSError(CAMSErrorType.USER_CANCELLED, error instanceof Error ? error.message : 'Unknown error');
|
|
248
|
-
|
|
253
|
+
this.events.onAuthError && this.events.onAuthError(camsError);
|
|
249
254
|
throw camsError;
|
|
250
255
|
}
|
|
251
256
|
}
|
|
@@ -253,23 +258,21 @@ class CAMSSession {
|
|
|
253
258
|
this.tokenManager.clearToken();
|
|
254
259
|
}
|
|
255
260
|
isAuthenticated() {
|
|
256
|
-
var _a, _b;
|
|
257
261
|
const token = this.tokenManager.loadToken();
|
|
258
262
|
if (!token)
|
|
259
263
|
return false;
|
|
260
264
|
if (this.tokenManager.isExpired()) {
|
|
261
|
-
|
|
265
|
+
this.events.onTokenExpired?.();
|
|
262
266
|
return false;
|
|
263
267
|
}
|
|
264
268
|
return true;
|
|
265
269
|
}
|
|
266
270
|
getAccessToken() {
|
|
267
|
-
var _a, _b;
|
|
268
271
|
const token = this.tokenManager.loadToken();
|
|
269
272
|
if (!token)
|
|
270
273
|
return null;
|
|
271
274
|
if (this.tokenManager.isExpired()) {
|
|
272
|
-
|
|
275
|
+
this.events.onTokenExpired?.();
|
|
273
276
|
return null;
|
|
274
277
|
}
|
|
275
278
|
return token.access_token;
|
|
@@ -285,7 +288,7 @@ class CAMSSession {
|
|
|
285
288
|
}
|
|
286
289
|
async getProfile() {
|
|
287
290
|
const storedToken = this.tokenManager.loadToken();
|
|
288
|
-
if (!
|
|
291
|
+
if (!storedToken || !storedToken.id_token)
|
|
289
292
|
return null;
|
|
290
293
|
try {
|
|
291
294
|
const parts = storedToken.id_token.split('.');
|
package/dist/index.esm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.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":[],"mappings":";;IAWY;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,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AE;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;AACpB,oBAAA,OAAO,CAAC,IAAI,CAAC,+BAA+B,EAAE,WAAW,YAAY,KAAK,GAAG,WAAW,CAAC,OAAO,GAAG,eAAe,CAAC;gBACrH;YACF;QACF;QAAE,OAAO,KAAK,EAAE;AACd,YAAA,OAAO,CAAC,IAAI,CAAC,uCAAuC,EAAE,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,eAAe,CAAC;QACjH;AAEA,QAAA,OAAO,IAAI;IACb;AACD;;;;"}
|
|
1
|
+
{"version":3,"file":"index.esm.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// Matches IPv4 addresses like 192.168.x.x, 10.x.x.x, 172.16–31.x.x\nconst internalIpRegex =\n /^(http:\\/\\/|https:\\/\\/)((10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})|(192\\.168\\.\\d{1,3}\\.\\d{1,3})|(172\\.(1[6-9]|2\\d|3[0-1])\\.\\d{1,3}\\.\\d{1,3}))(:\\d+)?$/;\n\nexport const URLSchema = z.url().refine(\n (url) =>\n url.startsWith(\"https://\") || // normal HTTPS\n /^http:\\/\\/localhost(:\\d+)?$/i.test(url) || // localhost\n internalIpRegex.test(url), // internal LAN IPs\n {\n message:\n \"Only HTTPS, http://localhost, or internal IPs (192.168.x.x, 10.x.x.x, 172.16–31.x.x) are allowed\",\n }\n);","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\n ) {\n this.storageKey = storageKey || \"cams_token\";\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 ? 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 if (typeof payload.exp !== 'number') return true;\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 && 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 && 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 && 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 || !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":[],"mappings":";;IAWY;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;A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AAC,OAAO,GAAG,eAAe,CAAC;gBACrH;YACF;QACF;QAAE,OAAO,KAAK,EAAE;AACd,YAAA,OAAO,CAAC,IAAI,CAAC,uCAAuC,EAAE,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,eAAe,CAAC;QACjH;AAEA,QAAA,OAAO,IAAI;IACb;AACD;;;;"}
|
package/dist/index.umd.js
CHANGED
|
@@ -43,18 +43,23 @@
|
|
|
43
43
|
family_name: zod.z.string().optional(),
|
|
44
44
|
roles: zod.z.array(zod.z.string()).optional(),
|
|
45
45
|
});
|
|
46
|
-
//
|
|
47
|
-
const
|
|
46
|
+
// Matches IPv4 addresses like 192.168.x.x, 10.x.x.x, 172.16–31.x.x
|
|
47
|
+
const internalIpRegex = /^(http:\/\/|https:\/\/)((10\.\d{1,3}\.\d{1,3}\.\d{1,3})|(192\.168\.\d{1,3}\.\d{1,3})|(172\.(1[6-9]|2\d|3[0-1])\.\d{1,3}\.\d{1,3}))(:\d+)?$/;
|
|
48
|
+
const URLSchema = zod.z.url().refine((url) => url.startsWith("https://") || // normal HTTPS
|
|
49
|
+
/^http:\/\/localhost(:\d+)?$/i.test(url) || // localhost
|
|
50
|
+
internalIpRegex.test(url), // internal LAN IPs
|
|
51
|
+
{
|
|
52
|
+
message: "Only HTTPS, http://localhost, or internal IPs (192.168.x.x, 10.x.x.x, 172.16–31.x.x) are allowed",
|
|
53
|
+
});
|
|
48
54
|
|
|
49
55
|
function validateConfig(config) {
|
|
50
|
-
var _a;
|
|
51
56
|
// Validate URL format
|
|
52
57
|
const urlValidation = URLSchema.safeParse(config.camsUrl);
|
|
53
58
|
if (!urlValidation.success) {
|
|
54
59
|
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'Invalid CAMS URL format');
|
|
55
60
|
}
|
|
56
61
|
// Domain validation is mandatory for security
|
|
57
|
-
if (!
|
|
62
|
+
if (!config.allowedDomains?.length) {
|
|
58
63
|
throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');
|
|
59
64
|
}
|
|
60
65
|
const url = new URL(config.camsUrl); // URLSchema already validated this
|
|
@@ -149,10 +154,10 @@
|
|
|
149
154
|
}
|
|
150
155
|
|
|
151
156
|
class TokenManager {
|
|
152
|
-
constructor(storage = sessionStorage, storageKey
|
|
157
|
+
constructor(storage = sessionStorage, storageKey) {
|
|
153
158
|
this.storage = storage;
|
|
154
159
|
this.token = null;
|
|
155
|
-
this.storageKey = storageKey;
|
|
160
|
+
this.storageKey = storageKey || "cams_token";
|
|
156
161
|
}
|
|
157
162
|
setToken(token) {
|
|
158
163
|
const parsed = TokenSchema.parse(token);
|
|
@@ -188,9 +193,8 @@
|
|
|
188
193
|
this.storage.removeItem(this.storageKey);
|
|
189
194
|
}
|
|
190
195
|
getAccessToken() {
|
|
191
|
-
var _a;
|
|
192
196
|
const token = this.loadToken();
|
|
193
|
-
return
|
|
197
|
+
return token ? token.access_token : null;
|
|
194
198
|
}
|
|
195
199
|
isExpired() {
|
|
196
200
|
const token = this.loadToken();
|
|
@@ -203,6 +207,8 @@
|
|
|
203
207
|
if (parts.length < 3)
|
|
204
208
|
return true; // Invalid JWT format
|
|
205
209
|
const payload = JSON.parse(atob(parts[1]));
|
|
210
|
+
if (typeof payload.exp !== 'number')
|
|
211
|
+
return true;
|
|
206
212
|
const exp = payload.exp * 1000;
|
|
207
213
|
return Date.now() > exp;
|
|
208
214
|
}
|
|
@@ -222,15 +228,14 @@
|
|
|
222
228
|
this.events = events;
|
|
223
229
|
}
|
|
224
230
|
async login(config) {
|
|
225
|
-
var _a, _b, _c, _d, _e, _f, _g;
|
|
226
231
|
try {
|
|
227
|
-
|
|
232
|
+
this.events.onAuthStart && this.events.onAuthStart();
|
|
228
233
|
let attempts = 0;
|
|
229
|
-
const maxAttempts = (
|
|
234
|
+
const maxAttempts = (config.retryAttempts ?? 0) + 1;
|
|
230
235
|
while (attempts < maxAttempts) {
|
|
231
236
|
try {
|
|
232
237
|
const response = await openCAMSPopUpLogin(config);
|
|
233
|
-
|
|
238
|
+
this.events.onAuthSuccess && this.events.onAuthSuccess(response);
|
|
234
239
|
return response;
|
|
235
240
|
}
|
|
236
241
|
catch (error) {
|
|
@@ -249,7 +254,7 @@
|
|
|
249
254
|
catch (error) {
|
|
250
255
|
const camsError = error instanceof CAMSError ? error :
|
|
251
256
|
new CAMSError(exports.CAMSErrorType.USER_CANCELLED, error instanceof Error ? error.message : 'Unknown error');
|
|
252
|
-
|
|
257
|
+
this.events.onAuthError && this.events.onAuthError(camsError);
|
|
253
258
|
throw camsError;
|
|
254
259
|
}
|
|
255
260
|
}
|
|
@@ -257,23 +262,21 @@
|
|
|
257
262
|
this.tokenManager.clearToken();
|
|
258
263
|
}
|
|
259
264
|
isAuthenticated() {
|
|
260
|
-
var _a, _b;
|
|
261
265
|
const token = this.tokenManager.loadToken();
|
|
262
266
|
if (!token)
|
|
263
267
|
return false;
|
|
264
268
|
if (this.tokenManager.isExpired()) {
|
|
265
|
-
|
|
269
|
+
this.events.onTokenExpired?.();
|
|
266
270
|
return false;
|
|
267
271
|
}
|
|
268
272
|
return true;
|
|
269
273
|
}
|
|
270
274
|
getAccessToken() {
|
|
271
|
-
var _a, _b;
|
|
272
275
|
const token = this.tokenManager.loadToken();
|
|
273
276
|
if (!token)
|
|
274
277
|
return null;
|
|
275
278
|
if (this.tokenManager.isExpired()) {
|
|
276
|
-
|
|
279
|
+
this.events.onTokenExpired?.();
|
|
277
280
|
return null;
|
|
278
281
|
}
|
|
279
282
|
return token.access_token;
|
|
@@ -289,7 +292,7 @@
|
|
|
289
292
|
}
|
|
290
293
|
async getProfile() {
|
|
291
294
|
const storedToken = this.tokenManager.loadToken();
|
|
292
|
-
if (!
|
|
295
|
+
if (!storedToken || !storedToken.id_token)
|
|
293
296
|
return null;
|
|
294
297
|
try {
|
|
295
298
|
const parts = storedToken.id_token.split('.');
|
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":["CA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AI,CAAC,GAAG,CAAC;QAClB;IAEA,IAAA,MAAM,UAAU,GAAA;YACd,MAAM,WAAW,GAAG,IAAI,CAAC,YAAY,CAAC,SAAS,EAAE;YACjD,IAAI,EAAC,WAAW,KAAA,IAAA,IAAX,WAAW,KAAA,MAAA,GAAA,MAAA,GAAX,WAAW,CAAE,QAAQ,CAAA;IAAE,YAAA,OAAO,IAAI;IAEvC,QAAA,IAAI;gBACF,MAAM,KAAK,GAAG,WAAW,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC;gBAC7C,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;IACpB,oBAAA,OAAO,CAAC,IAAI,CAAC,+BAA+B,EAAE,WAAW,YAAY,KAAK,GAAG,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/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// Matches IPv4 addresses like 192.168.x.x, 10.x.x.x, 172.16–31.x.x\nconst internalIpRegex =\n /^(http:\\/\\/|https:\\/\\/)((10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})|(192\\.168\\.\\d{1,3}\\.\\d{1,3})|(172\\.(1[6-9]|2\\d|3[0-1])\\.\\d{1,3}\\.\\d{1,3}))(:\\d+)?$/;\n\nexport const URLSchema = z.url().refine(\n (url) =>\n url.startsWith(\"https://\") || // normal HTTPS\n /^http:\\/\\/localhost(:\\d+)?$/i.test(url) || // localhost\n internalIpRegex.test(url), // internal LAN IPs\n {\n message:\n \"Only HTTPS, http://localhost, or internal IPs (192.168.x.x, 10.x.x.x, 172.16–31.x.x) are allowed\",\n }\n);","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\n ) {\n this.storageKey = storageKey || \"cams_token\";\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 ? 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 if (typeof payload.exp !== 'number') return true;\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 && 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 && 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 && 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 || !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,MAAM,CAAC;QACzC,YAAY,EAAEA,KAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,4BAA4B,EAAE,iCAAiC,CAAC;IAChG,CAAA;AAIM,UAAM,kBAAkB,GAAGA,KAAC,CAAC,MAAM,CAAC;IACzC,IAAA,KAAK,EAAEA,KAAC,CAAC,MAAM,EAAE;IAClB,CAAA;AAEM,UAAM,WAAW,GAAGA,KAAC,CAAC,MAAM,CAAC;IAClC,IAAA,YAAY,EAAEA,KAAC,CAAC,MAAM,EAAE;IACxB,IAAA,aAAa,EAAEA,KAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC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AW,IAAI,CAAC,WAAW,CAAC,QAAQ;IAAE,YAAA,OAAO,IAAI;IAEtD,QAAA,IAAI;gBACF,MAAM,KAAK,GAAG,WAAW,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC;gBAC7C,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;IACpB,oBAAA,OAAO,CAAC,IAAI,CAAC,+BAA+B,EAAE,WAAW,YAAY,KAAK,GAAG,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;;;;;;;;;;;;;;;;;"}
|
package/dist/validators.d.ts
CHANGED
|
@@ -23,4 +23,4 @@ export declare const ProfileSchema: z.ZodObject<{
|
|
|
23
23
|
roles: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
24
24
|
}, z.core.$strip>;
|
|
25
25
|
export type Profile = z.infer<typeof ProfileSchema>;
|
|
26
|
-
export declare const URLSchema: z.
|
|
26
|
+
export declare const URLSchema: z.ZodURL;
|
package/package.json
CHANGED
|
@@ -1,11 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nibssplc/cams-sdk",
|
|
3
|
-
"version": "0.0.1-beta.
|
|
3
|
+
"version": "0.0.1-beta.9",
|
|
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",
|
|
7
7
|
"unpkg": "dist/index.umd.js",
|
|
8
|
-
"types": "dist/
|
|
8
|
+
"types": "dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.esm.js",
|
|
13
|
+
"require": "./dist/index.cjs.js",
|
|
14
|
+
"default": "./dist/index.esm.js"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
9
17
|
"scripts": {
|
|
10
18
|
"clean": "rm -rf dist",
|
|
11
19
|
"build": "npx rollup -c",
|