@nibssplc/cams-sdk 0.0.1-beta.1 → 0.0.1-beta.10

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.umd.js CHANGED
@@ -43,18 +43,59 @@
43
43
  family_name: zod.z.string().optional(),
44
44
  roles: zod.z.array(zod.z.string()).optional(),
45
45
  });
46
- // URL validation schema - only HTTPS for production security
47
- const URLSchema = zod.z.string().url().refine((url) => url.startsWith('https://'), { message: "Only HTTPS URLs are allowed" });
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
+ });
54
+
55
+ exports.LogLevel = void 0;
56
+ (function (LogLevel) {
57
+ LogLevel[LogLevel["ERROR"] = 0] = "ERROR";
58
+ LogLevel[LogLevel["WARN"] = 1] = "WARN";
59
+ LogLevel[LogLevel["INFO"] = 2] = "INFO";
60
+ LogLevel[LogLevel["DEBUG"] = 3] = "DEBUG";
61
+ })(exports.LogLevel || (exports.LogLevel = {}));
62
+ class Logger {
63
+ static setLevel(level) {
64
+ Logger.level = level;
65
+ }
66
+ static error(message, context) {
67
+ if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.ERROR) {
68
+ console.error(`${Logger.prefix} ERROR:`, message, context || '');
69
+ }
70
+ }
71
+ static warn(message, context) {
72
+ if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.WARN) {
73
+ console.warn(`${Logger.prefix} WARN:`, message, context || '');
74
+ }
75
+ }
76
+ static info(message, context) {
77
+ if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.INFO) {
78
+ console.info(`${Logger.prefix} INFO:`, message, context || '');
79
+ }
80
+ }
81
+ static debug(message, context) {
82
+ if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.DEBUG) {
83
+ console.debug(`${Logger.prefix} DEBUG:`, message, context || '');
84
+ }
85
+ }
86
+ }
87
+ Logger.level = exports.LogLevel.WARN;
88
+ Logger.prefix = '[CAMS-SDK]';
89
+ Logger.isTestEnv = typeof process !== 'undefined' && process.env?.NODE_ENV === 'test';
48
90
 
49
91
  function validateConfig(config) {
50
- var _a;
51
92
  // Validate URL format
52
93
  const urlValidation = URLSchema.safeParse(config.camsUrl);
53
94
  if (!urlValidation.success) {
54
95
  throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'Invalid CAMS URL format');
55
96
  }
56
97
  // Domain validation is mandatory for security
57
- if (!((_a = config.allowedDomains) === null || _a === void 0 ? void 0 : _a.length)) {
98
+ if (!config.allowedDomains?.length) {
58
99
  throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');
59
100
  }
60
101
  const url = new URL(config.camsUrl); // URLSchema already validated this
@@ -65,10 +106,15 @@
65
106
  }
66
107
  function openCAMSPopUpLogin(config) {
67
108
  return new Promise((resolve, reject) => {
109
+ if (config.debug)
110
+ Logger.setLevel(exports.LogLevel.DEBUG);
111
+ Logger.info('Starting CAMS authentication', { url: config.camsUrl });
68
112
  try {
69
113
  validateConfig(config);
114
+ Logger.debug('Config validation passed');
70
115
  }
71
116
  catch (error) {
117
+ Logger.error('Config validation failed', { error: error instanceof Error ? error.message : 'Unknown error' });
72
118
  reject(error);
73
119
  return;
74
120
  }
@@ -77,16 +123,20 @@
77
123
  let timeoutId = null;
78
124
  let checkClosedInterval = null;
79
125
  try {
126
+ Logger.debug('Opening popup window', { width: windowWidth, height: windowHeight });
80
127
  authWindow = window.open(camsUrl, "NIBSS CAMS Login", `width=${windowWidth},height=${windowHeight}`);
81
128
  }
82
129
  catch (error) {
130
+ Logger.error('Failed to open popup window', { error: error instanceof Error ? error.message : 'Unknown error' });
83
131
  reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window: " + (error instanceof Error ? error.message : "Unknown error")));
84
132
  return;
85
133
  }
86
134
  if (!authWindow) {
135
+ Logger.error('Popup window blocked');
87
136
  reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window. Please allow popups."));
88
137
  return;
89
138
  }
139
+ Logger.debug('Popup window opened successfully');
90
140
  const cleanup = () => {
91
141
  window.removeEventListener("message", listener);
92
142
  if (timeoutId)
@@ -108,32 +158,37 @@
108
158
  reject(error);
109
159
  };
110
160
  const listener = (event) => {
161
+ Logger.debug('Received message', { origin: event.origin, expectedOrigin: allowedOrigin });
111
162
  if (event.origin !== allowedOrigin) {
112
- // Sanitize origin for logging to prevent log injection
113
- const sanitizedOrigin = event.origin.replace(/[\r\n]/g, '');
114
- console.warn("Blocked message from origin:", sanitizedOrigin);
163
+ Logger.warn('Blocked message from unauthorized origin', { origin: event.origin, expected: allowedOrigin });
115
164
  return;
116
165
  }
117
166
  // ✅ Validate payload
118
167
  const tokenMsg = TokenMessageSchema.safeParse(event.data);
119
168
  if (tokenMsg.success) {
169
+ Logger.info('Authentication successful');
120
170
  cleanupAndClose();
121
171
  resolve({ token: tokenMsg.data.access_token });
122
172
  return;
123
173
  }
124
174
  const errorMsg = ErrorMessageSchema.safeParse(event.data);
125
175
  if (errorMsg.success) {
176
+ Logger.warn('Authentication error received', { error: errorMsg.data.error });
126
177
  cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication failed: " + errorMsg.data.error));
127
178
  return;
128
179
  }
180
+ Logger.error('Invalid message format received');
129
181
  cleanupAndClose(new CAMSError(exports.CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
130
182
  };
131
183
  // Timeout handler
184
+ Logger.debug('Setting timeout', { timeout });
132
185
  timeoutId = setTimeout(() => {
186
+ Logger.warn('Authentication timeout', { timeout });
133
187
  cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));
134
188
  }, timeout);
135
189
  checkClosedInterval = setInterval(() => {
136
190
  if (authWindow && authWindow.closed) {
191
+ Logger.info('Authentication window closed by user');
137
192
  cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
138
193
  }
139
194
  }, 2000); // Reduced polling frequency
@@ -149,15 +204,16 @@
149
204
  }
150
205
 
151
206
  class TokenManager {
152
- constructor(storage = sessionStorage, storageKey = "cams_token") {
207
+ constructor(storage = sessionStorage, storageKey) {
153
208
  this.storage = storage;
154
209
  this.token = null;
155
- this.storageKey = storageKey;
210
+ this.storageKey = storageKey || "cams_token";
156
211
  }
157
212
  setToken(token) {
158
213
  const parsed = TokenSchema.parse(token);
159
214
  this.token = parsed;
160
215
  this.storage.setItem(this.storageKey, JSON.stringify(parsed));
216
+ Logger.debug('Token stored', { storageKey: this.storageKey });
161
217
  }
162
218
  loadToken() {
163
219
  if (this.token)
@@ -169,16 +225,17 @@
169
225
  const parsed = JSON.parse(raw);
170
226
  try {
171
227
  this.token = TokenSchema.parse(parsed);
228
+ Logger.debug('Token loaded from storage');
172
229
  return this.token;
173
230
  }
174
231
  catch (validationError) {
175
- console.warn('Token validation failed:', validationError instanceof Error ? validationError.message : 'Unknown error');
232
+ Logger.warn('Token validation failed', { error: validationError instanceof Error ? validationError.message : 'Unknown error' });
176
233
  this.storage.removeItem(this.storageKey);
177
234
  return null;
178
235
  }
179
236
  }
180
237
  catch (parseError) {
181
- console.warn('Failed to parse stored token JSON:', parseError instanceof Error ? parseError.message : 'Unknown error');
238
+ Logger.warn('Failed to parse stored token JSON', { error: parseError instanceof Error ? parseError.message : 'Unknown error' });
182
239
  this.storage.removeItem(this.storageKey);
183
240
  return null;
184
241
  }
@@ -186,11 +243,11 @@
186
243
  clearToken() {
187
244
  this.token = null;
188
245
  this.storage.removeItem(this.storageKey);
246
+ Logger.debug('Token cleared');
189
247
  }
190
248
  getAccessToken() {
191
- var _a;
192
249
  const token = this.loadToken();
193
- return (_a = token === null || token === void 0 ? void 0 : token.access_token) !== null && _a !== void 0 ? _a : null;
250
+ return token ? token.access_token : null;
194
251
  }
195
252
  isExpired() {
196
253
  const token = this.loadToken();
@@ -203,11 +260,13 @@
203
260
  if (parts.length < 3)
204
261
  return true; // Invalid JWT format
205
262
  const payload = JSON.parse(atob(parts[1]));
263
+ if (typeof payload.exp !== 'number')
264
+ return true;
206
265
  const exp = payload.exp * 1000;
207
266
  return Date.now() > exp;
208
267
  }
209
268
  catch (error) {
210
- console.warn('Failed to parse JWT token:', error instanceof Error ? error.message : 'Unknown error');
269
+ Logger.warn('Failed to parse JWT token', { error: error instanceof Error ? error.message : 'Unknown error' });
211
270
  return true;
212
271
  }
213
272
  }
@@ -222,19 +281,23 @@
222
281
  this.events = events;
223
282
  }
224
283
  async login(config) {
225
- var _a, _b, _c, _d, _e, _f, _g;
226
284
  try {
227
- (_b = (_a = this.events).onAuthStart) === null || _b === void 0 ? void 0 : _b.call(_a);
285
+ Logger.info('Session login started');
286
+ this.events.onAuthStart && this.events.onAuthStart();
228
287
  let attempts = 0;
229
- const maxAttempts = ((_c = config.retryAttempts) !== null && _c !== void 0 ? _c : 0) + 1;
288
+ const maxAttempts = (config.retryAttempts ?? 0) + 1;
289
+ Logger.debug('Login retry configuration', { maxAttempts });
230
290
  while (attempts < maxAttempts) {
231
291
  try {
292
+ attempts++;
293
+ Logger.debug('Login attempt', { attempt: attempts, maxAttempts });
232
294
  const response = await openCAMSPopUpLogin(config);
233
- (_e = (_d = this.events).onAuthSuccess) === null || _e === void 0 ? void 0 : _e.call(_d, response);
295
+ Logger.info('Session login successful');
296
+ this.events.onAuthSuccess && this.events.onAuthSuccess(response);
234
297
  return response;
235
298
  }
236
299
  catch (error) {
237
- attempts++;
300
+ Logger.warn('Login attempt failed', { attempt: attempts, error: error instanceof Error ? error.message : 'Unknown error' });
238
301
  if (attempts >= maxAttempts || !(error instanceof CAMSError)) {
239
302
  throw error;
240
303
  }
@@ -242,6 +305,7 @@
242
305
  if (![exports.CAMSErrorType.TIMEOUT, exports.CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {
243
306
  throw error;
244
307
  }
308
+ Logger.info('Retrying login', { nextAttempt: attempts + 1 });
245
309
  }
246
310
  }
247
311
  throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED, 'Max retry attempts exceeded');
@@ -249,31 +313,35 @@
249
313
  catch (error) {
250
314
  const camsError = error instanceof CAMSError ? error :
251
315
  new CAMSError(exports.CAMSErrorType.USER_CANCELLED, error instanceof Error ? error.message : 'Unknown error');
252
- (_g = (_f = this.events).onAuthError) === null || _g === void 0 ? void 0 : _g.call(_f, camsError);
316
+ Logger.error('Session login failed', { error: camsError.message, type: camsError.type });
317
+ this.events.onAuthError && this.events.onAuthError(camsError);
253
318
  throw camsError;
254
319
  }
255
320
  }
256
321
  async logout() {
322
+ Logger.info('Session logout');
257
323
  this.tokenManager.clearToken();
258
324
  }
259
325
  isAuthenticated() {
260
- var _a, _b;
261
326
  const token = this.tokenManager.loadToken();
262
- if (!token)
327
+ if (!token) {
328
+ Logger.debug('No token found');
263
329
  return false;
330
+ }
264
331
  if (this.tokenManager.isExpired()) {
265
- (_b = (_a = this.events).onTokenExpired) === null || _b === void 0 ? void 0 : _b.call(_a);
332
+ Logger.info('Token expired');
333
+ this.events.onTokenExpired?.();
266
334
  return false;
267
335
  }
336
+ Logger.debug('Token is valid');
268
337
  return true;
269
338
  }
270
339
  getAccessToken() {
271
- var _a, _b;
272
340
  const token = this.tokenManager.loadToken();
273
341
  if (!token)
274
342
  return null;
275
343
  if (this.tokenManager.isExpired()) {
276
- (_b = (_a = this.events).onTokenExpired) === null || _b === void 0 ? void 0 : _b.call(_a);
344
+ this.events.onTokenExpired?.();
277
345
  return null;
278
346
  }
279
347
  return token.access_token;
@@ -289,7 +357,7 @@
289
357
  }
290
358
  async getProfile() {
291
359
  const storedToken = this.tokenManager.loadToken();
292
- if (!(storedToken === null || storedToken === void 0 ? void 0 : storedToken.id_token))
360
+ if (!storedToken || !storedToken.id_token)
293
361
  return null;
294
362
  try {
295
363
  const parts = storedToken.id_token.split('.');
@@ -299,12 +367,12 @@
299
367
  return ProfileSchema.parse(payload);
300
368
  }
301
369
  catch (decodeError) {
302
- console.warn('Failed to decode JWT payload:', decodeError instanceof Error ? decodeError.message : 'Unknown error');
370
+ Logger.warn('Failed to decode JWT payload', { error: decodeError instanceof Error ? decodeError.message : 'Unknown error' });
303
371
  }
304
372
  }
305
373
  }
306
374
  catch (error) {
307
- console.warn('Failed to extract profile from token:', error instanceof Error ? error.message : 'Unknown error');
375
+ Logger.warn('Failed to extract profile from token', { error: error instanceof Error ? error.message : 'Unknown error' });
308
376
  }
309
377
  return null;
310
378
  }
@@ -313,12 +381,14 @@
313
381
  exports.CAMSError = CAMSError;
314
382
  exports.CAMSSession = CAMSSession;
315
383
  exports.ErrorMessageSchema = ErrorMessageSchema;
384
+ exports.Logger = Logger;
316
385
  exports.ProfileSchema = ProfileSchema;
317
386
  exports.TokenManager = TokenManager;
318
387
  exports.TokenMessageSchema = TokenMessageSchema;
319
388
  exports.TokenSchema = TokenSchema;
320
389
  exports.URLSchema = URLSchema;
321
390
  exports.openCAMSPopUpLogin = openCAMSPopUpLogin;
391
+ exports.validateConfig = validateConfig;
322
392
 
323
393
  }));
324
394
  //# sourceMappingURL=index.umd.js.map
@@ -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\nfunction validateConfig(config: CAMSConfig): void {\n // Validate URL format\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'Invalid CAMS URL format');\n }\n\n // Domain validation is mandatory for security\n if (!config.allowedDomains?.length) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');\n }\n\n const url = new URL(config.camsUrl); // URLSchema already validated this\n const isAllowed = config.allowedDomains.some(domain => \n url.hostname === domain || url.hostname.endsWith('.' + domain)\n );\n if (!isAllowed) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'URL not in allowed domains list');\n }\n}\n\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<CAMSTokenResponse> {\n return new Promise((resolve, reject) => {\n try {\n validateConfig(config);\n } catch (error) {\n reject(error);\n return;\n }\n\n const { camsUrl, allowedOrigin, windowHeight, windowWidth, timeout = 300000 } = config;\n let authWindow: Window | null;\n let timeoutId: NodeJS.Timeout | null = null;\n let checkClosedInterval: NodeJS.Timeout | null = null;\n \n try {\n authWindow = window.open(\n camsUrl,\n \"NIBSS CAMS Login\",\n `width=${windowWidth},height=${windowHeight}`\n );\n } catch (error) {\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to open authentication window: \" + (error instanceof Error ? error.message : \"Unknown error\")));\n return;\n }\n\n if (!authWindow) {\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to open authentication window. Please allow popups.\"));\n return;\n }\n\n const cleanup = () => {\n window.removeEventListener(\"message\", listener);\n if (timeoutId) clearTimeout(timeoutId);\n if (checkClosedInterval) clearInterval(checkClosedInterval);\n };\n \n const cleanupAndClose = (error?: CAMSError) => {\n cleanup();\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.close();\n }\n } catch {\n // Ignore close errors\n }\n if (error) reject(error);\n };\n\n const listener = (event: MessageEvent) => {\n if (event.origin !== allowedOrigin) {\n // Sanitize origin for logging to prevent log injection\n const sanitizedOrigin = event.origin.replace(/[\\r\\n]/g, '');\n console.warn(\"Blocked message from origin:\", sanitizedOrigin);\n return;\n }\n\n // ✅ Validate payload\n const tokenMsg = TokenMessageSchema.safeParse(event.data);\n if (tokenMsg.success) {\n cleanupAndClose();\n resolve({ token: tokenMsg.data.access_token });\n return;\n }\n\n const errorMsg = ErrorMessageSchema.safeParse(event.data);\n if (errorMsg.success) {\n cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, \"Authentication failed: \" + errorMsg.data.error));\n return;\n }\n\n cleanupAndClose(new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\"));\n };\n\n // Timeout handler\n timeoutId = setTimeout(() => {\n cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));\n }, timeout);\n\n checkClosedInterval = setInterval(() => {\n if (authWindow && authWindow.closed) {\n cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, \"Authentication window was closed\"));\n }\n }, 2000); // Reduced polling frequency\n\n try {\n window.addEventListener(\"message\", listener);\n } catch (error) {\n cleanup();\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to set up message listener: \" + (error instanceof Error ? error.message : \"Unknown error\")));\n return;\n }\n });\n}\n","import { Token, TokenSchema } from \"./validators\";\n\nexport class TokenManager {\n private token: Token | null = null;\n private readonly storageKey: string;\n\n constructor(\n private readonly storage: Storage = sessionStorage,\n storageKey: string = \"cams_token\"\n ) {\n this.storageKey = storageKey;\n }\n\n setToken(token: Token) {\n const parsed = TokenSchema.parse(token);\n this.token = parsed;\n this.storage.setItem(this.storageKey, JSON.stringify(parsed));\n }\n\n loadToken(): Token | null {\n if (this.token) return this.token;\n const raw = this.storage.getItem(this.storageKey);\n if (!raw) return null;\n \n try {\n const parsed = JSON.parse(raw);\n try {\n this.token = TokenSchema.parse(parsed);\n return this.token;\n } catch (validationError) {\n console.warn('Token validation failed:', validationError instanceof Error ? validationError.message : 'Unknown error');\n this.storage.removeItem(this.storageKey);\n return null;\n }\n } catch (parseError) {\n console.warn('Failed to parse stored token JSON:', parseError instanceof Error ? parseError.message : 'Unknown error');\n this.storage.removeItem(this.storageKey);\n return null;\n }\n }\n\n clearToken() {\n this.token = null;\n this.storage.removeItem(this.storageKey);\n }\n\n getAccessToken(): string | null {\n const token = this.loadToken();\n return token?.access_token ?? null;\n }\n\n isExpired(): boolean {\n const token = this.loadToken();\n if (!token) return true;\n\n // JWT expiration check if available\n if (token.id_token) {\n try {\n const parts = token.id_token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const payload = JSON.parse(atob(parts[1]));\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n console.warn('Failed to parse JWT token:', error instanceof Error ? error.message : 'Unknown error');\n return true;\n }\n }\n\n // Fallback: return true for safety when expiration cannot be determined\n return true;\n }\n}\n","import { CAMSConfig, CAMSTokenResponse, CAMSError, CAMSErrorType } from \"./types\";\nimport { TokenManager } from \"./tokenManager\";\nimport { openCAMSPopUpLogin } from \"./auth\";\nimport { Profile, ProfileSchema } from \"./validators\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (token: CAMSTokenResponse) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSession {\n private readonly tokenManager: TokenManager;\n private readonly events: CAMSEvents;\n\n constructor(\n storage: Storage = sessionStorage,\n storageKey?: string,\n events: CAMSEvents = {}\n ) {\n this.tokenManager = new TokenManager(storage, storageKey);\n this.events = events;\n }\n\n async login(config: CAMSConfig): Promise<CAMSTokenResponse> {\n try {\n this.events.onAuthStart?.();\n \n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n \n while (attempts < maxAttempts) {\n try {\n const response = await openCAMSPopUpLogin(config);\n this.events.onAuthSuccess?.(response);\n return response;\n } catch (error) {\n attempts++;\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {\n throw error;\n }\n }\n }\n \n throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, 'Max retry attempts exceeded');\n } catch (error) {\n const camsError = error instanceof CAMSError ? error : \n new CAMSError(CAMSErrorType.USER_CANCELLED, error instanceof Error ? error.message : 'Unknown error');\n this.events.onAuthError?.(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n this.tokenManager.clearToken();\n }\n\n isAuthenticated(): boolean {\n const token = this.tokenManager.loadToken();\n if (!token) return false;\n \n if (this.tokenManager.isExpired()) {\n this.events.onTokenExpired?.();\n return false;\n }\n \n return true;\n }\n\n getAccessToken(): string | null {\n const token = this.tokenManager.loadToken();\n if (!token) return null;\n \n if (this.tokenManager.isExpired()) {\n this.events.onTokenExpired?.();\n return null;\n }\n \n return token.access_token;\n }\n\n private decodeBase64Url(str: string): string {\n // Convert base64url to base64\n str = str.replace(/-/g, '+').replace(/_/g, '/');\n // Add padding if needed\n while (str.length % 4) {\n str += '=';\n }\n return atob(str);\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.tokenManager.loadToken();\n if (!storedToken?.id_token) return null;\n\n try {\n const parts = storedToken.id_token.split('.');\n if (parts.length >= 3) { // JWT has header.payload.signature format\n try {\n const payload = JSON.parse(this.decodeBase64Url(parts[1]));\n return ProfileSchema.parse(payload);\n } catch (decodeError) {\n console.warn('Failed to decode JWT payload:', decodeError instanceof Error ? decodeError.message : 'Unknown error');\n }\n }\n } catch (error) {\n console.warn('Failed to extract profile from token:', error instanceof Error ? error.message : 'Unknown error');\n }\n\n return null;\n }\n}"],"names":["CAMSErrorType","z"],"mappings":";;;;;;AAWYA;IAAZ,CAAA,UAAY,aAAa,EAAA;IACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;IAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;IACnB,IAAA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,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/logger.ts","../src/auth.ts","../src/tokenManager.ts","../src/session.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n allowedOrigin: string;\n windowWidth: number;\n windowHeight: number;\n timeout?: number; // Auth timeout in ms (default: 300000)\n allowedDomains?: string[]; // URL allowlist for security\n storageKey?: string; // Custom storage key\n retryAttempts?: number; // Auto-retry on failure (default: 0)\n debug?: boolean; // Enable debug logging (default: false)\n}\n\nexport enum CAMSErrorType {\n POPUP_BLOCKED = 'POPUP_BLOCKED',\n TIMEOUT = 'TIMEOUT',\n INVALID_ORIGIN = 'INVALID_ORIGIN',\n USER_CANCELLED = 'USER_CANCELLED',\n INVALID_URL = 'INVALID_URL',\n MAX_RETRIES_EXCEEDED = 'MAX_RETRIES_EXCEEDED'\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = 'CAMSError';\n }\n}\n\nexport interface CAMSTokenResponse {\n token: string;\n}\n\nexport interface CAMSErrorResponse {\n error: string;\n}\n","import { z } from \"zod\";\n\n// Validate the returned token - Base64 format with minimum 20 chars\nexport const TokenMessageSchema = z.object({\n access_token: z.string().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);","export enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3\n}\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nexport class Logger {\n private static level: LogLevel = LogLevel.WARN;\n private static prefix = '[CAMS-SDK]';\n private static isTestEnv = typeof process !== 'undefined' && process.env?.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, message, context || '');\n }\n }\n\n static warn(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {\n console.warn(`${Logger.prefix} WARN:`, message, context || '');\n }\n }\n\n static info(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {\n console.info(`${Logger.prefix} INFO:`, message, context || '');\n }\n }\n\n static debug(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {\n console.debug(`${Logger.prefix} DEBUG:`, message, context || '');\n }\n }\n}","import { CAMSConfig, CAMSTokenResponse, CAMSError, CAMSErrorType } from \"./types\";\nimport { TokenMessageSchema, ErrorMessageSchema, URLSchema } from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\nexport function validateConfig(config: CAMSConfig): void {\n // Validate URL format\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'Invalid CAMS URL format');\n }\n\n // Domain validation is mandatory for security\n if (!config.allowedDomains?.length) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');\n }\n\n const url = new URL(config.camsUrl); // URLSchema already validated this\n const isAllowed = config.allowedDomains.some(domain => \n url.hostname === domain || url.hostname.endsWith('.' + domain)\n );\n if (!isAllowed) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, 'URL not in allowed domains list');\n }\n}\n\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<CAMSTokenResponse> {\n return new Promise((resolve, reject) => {\n if (config.debug) Logger.setLevel(LogLevel.DEBUG);\n \n Logger.info('Starting CAMS authentication', { url: config.camsUrl });\n \n try {\n validateConfig(config);\n Logger.debug('Config validation passed');\n } catch (error) {\n Logger.error('Config validation failed', { error: error instanceof Error ? error.message : 'Unknown error' });\n reject(error);\n return;\n }\n\n const { camsUrl, allowedOrigin, windowHeight, windowWidth, timeout = 300000 } = config;\n let authWindow: Window | null;\n let timeoutId: NodeJS.Timeout | null = null;\n let checkClosedInterval: NodeJS.Timeout | null = null;\n \n try {\n Logger.debug('Opening popup window', { width: windowWidth, height: windowHeight });\n authWindow = window.open(\n camsUrl,\n \"NIBSS CAMS Login\",\n `width=${windowWidth},height=${windowHeight}`\n );\n } catch (error) {\n Logger.error('Failed to open popup window', { error: error instanceof Error ? error.message : 'Unknown error' });\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to open authentication window: \" + (error instanceof Error ? error.message : \"Unknown error\")));\n return;\n }\n\n if (!authWindow) {\n Logger.error('Popup window blocked');\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to open authentication window. Please allow popups.\"));\n return;\n }\n \n Logger.debug('Popup window opened successfully');\n\n const cleanup = () => {\n window.removeEventListener(\"message\", listener);\n if (timeoutId) clearTimeout(timeoutId);\n if (checkClosedInterval) clearInterval(checkClosedInterval);\n };\n \n const cleanupAndClose = (error?: CAMSError) => {\n cleanup();\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.close();\n }\n } catch {\n // Ignore close errors\n }\n if (error) reject(error);\n };\n\n const listener = (event: MessageEvent) => {\n Logger.debug('Received message', { origin: event.origin, expectedOrigin: allowedOrigin });\n \n if (event.origin !== allowedOrigin) {\n Logger.warn('Blocked message from unauthorized origin', { origin: event.origin, expected: allowedOrigin });\n return;\n }\n\n // ✅ Validate payload\n const tokenMsg = TokenMessageSchema.safeParse(event.data);\n if (tokenMsg.success) {\n Logger.info('Authentication successful');\n cleanupAndClose();\n resolve({ token: tokenMsg.data.access_token });\n return;\n }\n\n const errorMsg = ErrorMessageSchema.safeParse(event.data);\n if (errorMsg.success) {\n Logger.warn('Authentication error received', { error: errorMsg.data.error });\n cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, \"Authentication failed: \" + errorMsg.data.error));\n return;\n }\n\n Logger.error('Invalid message format received');\n cleanupAndClose(new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\"));\n };\n\n // Timeout handler\n Logger.debug('Setting timeout', { timeout });\n timeoutId = setTimeout(() => {\n Logger.warn('Authentication timeout', { timeout });\n cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));\n }, timeout);\n\n checkClosedInterval = setInterval(() => {\n if (authWindow && authWindow.closed) {\n Logger.info('Authentication window closed by user');\n cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, \"Authentication window was closed\"));\n }\n }, 2000); // Reduced polling frequency\n\n try {\n window.addEventListener(\"message\", listener);\n } catch (error) {\n cleanup();\n reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, \"Failed to set up message listener: \" + (error instanceof Error ? error.message : \"Unknown error\")));\n return;\n }\n });\n}\n","import { Token, TokenSchema } from \"./validators\";\nimport { Logger } from \"./logger\";\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 Logger.debug('Token stored', { storageKey: this.storageKey });\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 Logger.debug('Token loaded from storage');\n return this.token;\n } catch (validationError) {\n Logger.warn('Token validation failed', { error: validationError instanceof Error ? validationError.message : 'Unknown error' });\n this.storage.removeItem(this.storageKey);\n return null;\n }\n } catch (parseError) {\n Logger.warn('Failed to parse stored token JSON', { error: 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 Logger.debug('Token cleared');\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 Logger.warn('Failed to parse JWT token', { error: 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\";\nimport { Logger } from \"./logger\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (token: CAMSTokenResponse) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSession {\n private readonly tokenManager: TokenManager;\n private readonly events: CAMSEvents;\n\n constructor(\n storage: Storage = sessionStorage,\n storageKey?: string,\n events: CAMSEvents = {}\n ) {\n this.tokenManager = new TokenManager(storage, storageKey);\n this.events = events;\n }\n\n async login(config: CAMSConfig): Promise<CAMSTokenResponse> {\n try {\n Logger.info('Session login started');\n this.events.onAuthStart && this.events.onAuthStart();\n \n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n Logger.debug('Login retry configuration', { maxAttempts });\n \n while (attempts < maxAttempts) {\n try {\n attempts++;\n Logger.debug('Login attempt', { attempt: attempts, maxAttempts });\n const response = await openCAMSPopUpLogin(config);\n Logger.info('Session login successful');\n this.events.onAuthSuccess && this.events.onAuthSuccess(response);\n return response;\n } catch (error) {\n Logger.warn('Login attempt failed', { attempt: attempts, error: error instanceof Error ? error.message : 'Unknown error' });\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {\n throw error;\n }\n Logger.info('Retrying login', { nextAttempt: attempts + 1 });\n }\n }\n \n throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, 'Max retry attempts exceeded');\n } catch (error) {\n const camsError = error instanceof CAMSError ? error : \n new CAMSError(CAMSErrorType.USER_CANCELLED, error instanceof Error ? error.message : 'Unknown error');\n Logger.error('Session login failed', { error: camsError.message, type: camsError.type });\n this.events.onAuthError && this.events.onAuthError(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n Logger.info('Session logout');\n this.tokenManager.clearToken();\n }\n\n isAuthenticated(): boolean {\n const token = this.tokenManager.loadToken();\n if (!token) {\n Logger.debug('No token found');\n return false;\n }\n \n if (this.tokenManager.isExpired()) {\n Logger.info('Token expired');\n this.events.onTokenExpired?.();\n return false;\n }\n \n Logger.debug('Token is valid');\n return true;\n }\n\n getAccessToken(): string | null {\n const token = this.tokenManager.loadToken();\n if (!token) return null;\n \n if (this.tokenManager.isExpired()) {\n this.events.onTokenExpired?.();\n return null;\n }\n \n return token.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 Logger.warn('Failed to decode JWT payload', { error: decodeError instanceof Error ? decodeError.message : 'Unknown error' });\n }\n }\n } catch (error) {\n Logger.warn('Failed to extract profile from token', { error: error instanceof Error ? error.message : 'Unknown error' });\n }\n\n return null;\n }\n}"],"names":["CAMSErrorType","z","LogLevel"],"mappings":";;;;;;AAYYA;IAAZ,CAAA,UAAY,aAAa,EAAA;IACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;IAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;IACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;IACjC,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;IACjC,IAAA,aAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;IAC3B,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;IAC/C,CAAC,EAPWA,qBAAa,KAAbA,qBAAa,GAAA,EAAA,CAAA,CAAA;IASnB,MAAO,SAAU,SAAQ,KAAK,CAAA;QAClC,WAAA,CAAmB,IAAmB,EAAE,OAAe,EAAA;YACrD,KAAK,CAAC,OAAO,CAAC;YADG,IAAA,CAAA,IAAI,GAAJ,IAAI;IAErB,QAAA,IAAI,CAAC,IAAI,GAAG,WAAW;QACzB;IACD;;ICxBD;AACO,UAAM,kBAAkB,GAAGC,KAAC,CAAC,MAAM,CAAC;QACzC,YAAY,EAAEA,KAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,4BAA4B,EAAE,iCAAiC,CAAC;IAChG,CAAA;AAIM,UAAM,kBAAkB,GAAGA,KAAC,CAAC,MAAM,CAAC;IACzC,IAAA,K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E,EAAE,KAAK,EAAE,WAAW,YAAY,KAAK,GAAG,WAAW,CAAC,OAAO,GAAG,eAAe,EAAE,CAAC;oBAC9H;gBACF;YACF;YAAE,OAAO,KAAK,EAAE;gBACd,MAAM,CAAC,IAAI,CAAC,sCAAsC,EAAE,EAAE,KAAK,EAAE,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,eAAe,EAAE,CAAC;YAC1H;IAEA,QAAA,OAAO,IAAI;QACb;IACD;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,19 @@
1
+ export declare enum LogLevel {
2
+ ERROR = 0,
3
+ WARN = 1,
4
+ INFO = 2,
5
+ DEBUG = 3
6
+ }
7
+ export interface LogContext {
8
+ [key: string]: any;
9
+ }
10
+ export declare class Logger {
11
+ private static level;
12
+ private static prefix;
13
+ private static isTestEnv;
14
+ static setLevel(level: LogLevel): void;
15
+ static error(message: string, context?: LogContext): void;
16
+ static warn(message: string, context?: LogContext): void;
17
+ static info(message: string, context?: LogContext): void;
18
+ static debug(message: string, context?: LogContext): void;
19
+ }
package/dist/types.d.ts CHANGED
@@ -7,6 +7,7 @@ export interface CAMSConfig {
7
7
  allowedDomains?: string[];
8
8
  storageKey?: string;
9
9
  retryAttempts?: number;
10
+ debug?: boolean;
10
11
  }
11
12
  export declare enum CAMSErrorType {
12
13
  POPUP_BLOCKED = "POPUP_BLOCKED",
@@ -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.ZodString;
26
+ export declare const URLSchema: z.ZodURL;
package/package.json CHANGED
@@ -1,17 +1,26 @@
1
1
  {
2
2
  "name": "@nibssplc/cams-sdk",
3
- "version": "0.0.1-beta.1",
3
+ "version": "0.0.1-beta.10",
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/types.d.ts",
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
- "build": "rollup -c",
11
18
  "clean": "rm -rf dist",
19
+ "build": "npx rollup -c",
12
20
  "prepare": "npm run clean && npm run build",
13
21
  "lint": "eslint src --ext .ts",
14
- "test": "npx jest"
22
+ "test": "npx jest",
23
+ "postpublish": "echo '✅ Published $(npm pkg get name)@$(npm pkg get version)'"
15
24
  },
16
25
  "keywords": [
17
26
  "cams",