@nibssplc/cams-sdk 0.0.1-beta.1

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.
@@ -0,0 +1,324 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('zod')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'zod'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.CAMS = {}, global.zod));
5
+ })(this, (function (exports, zod) { 'use strict';
6
+
7
+ exports.CAMSErrorType = void 0;
8
+ (function (CAMSErrorType) {
9
+ CAMSErrorType["POPUP_BLOCKED"] = "POPUP_BLOCKED";
10
+ CAMSErrorType["TIMEOUT"] = "TIMEOUT";
11
+ CAMSErrorType["INVALID_ORIGIN"] = "INVALID_ORIGIN";
12
+ CAMSErrorType["USER_CANCELLED"] = "USER_CANCELLED";
13
+ CAMSErrorType["INVALID_URL"] = "INVALID_URL";
14
+ CAMSErrorType["MAX_RETRIES_EXCEEDED"] = "MAX_RETRIES_EXCEEDED";
15
+ })(exports.CAMSErrorType || (exports.CAMSErrorType = {}));
16
+ class CAMSError extends Error {
17
+ constructor(type, message) {
18
+ super(message);
19
+ this.type = type;
20
+ this.name = 'CAMSError';
21
+ }
22
+ }
23
+
24
+ // Validate the returned token - Base64 format with minimum 20 chars
25
+ const TokenMessageSchema = zod.z.object({
26
+ access_token: zod.z.string().regex(/^[A-Za-z0-9+/]{20,}={0,2}$/, "Invalid NIBSS CAMS token format"),
27
+ });
28
+ const ErrorMessageSchema = zod.z.object({
29
+ error: zod.z.string(),
30
+ });
31
+ const TokenSchema = zod.z.object({
32
+ access_token: zod.z.string(),
33
+ refresh_token: zod.z.string().optional(),
34
+ expires_in: zod.z.number(), // in seconds
35
+ token_type: zod.z.string().default("Bearer"),
36
+ id_token: zod.z.string().optional(),
37
+ });
38
+ const ProfileSchema = zod.z.object({
39
+ sub: zod.z.string(), // user ID
40
+ name: zod.z.string().optional(),
41
+ email: zod.z.email({ message: "Invalid email address" }).optional(),
42
+ given_name: zod.z.string().optional(),
43
+ family_name: zod.z.string().optional(),
44
+ roles: zod.z.array(zod.z.string()).optional(),
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" });
48
+
49
+ function validateConfig(config) {
50
+ var _a;
51
+ // Validate URL format
52
+ const urlValidation = URLSchema.safeParse(config.camsUrl);
53
+ if (!urlValidation.success) {
54
+ throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'Invalid CAMS URL format');
55
+ }
56
+ // Domain validation is mandatory for security
57
+ if (!((_a = config.allowedDomains) === null || _a === void 0 ? void 0 : _a.length)) {
58
+ throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');
59
+ }
60
+ const url = new URL(config.camsUrl); // URLSchema already validated this
61
+ const isAllowed = config.allowedDomains.some(domain => url.hostname === domain || url.hostname.endsWith('.' + domain));
62
+ if (!isAllowed) {
63
+ throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'URL not in allowed domains list');
64
+ }
65
+ }
66
+ function openCAMSPopUpLogin(config) {
67
+ return new Promise((resolve, reject) => {
68
+ try {
69
+ validateConfig(config);
70
+ }
71
+ catch (error) {
72
+ reject(error);
73
+ return;
74
+ }
75
+ const { camsUrl, allowedOrigin, windowHeight, windowWidth, timeout = 300000 } = config;
76
+ let authWindow;
77
+ let timeoutId = null;
78
+ let checkClosedInterval = null;
79
+ try {
80
+ authWindow = window.open(camsUrl, "NIBSS CAMS Login", `width=${windowWidth},height=${windowHeight}`);
81
+ }
82
+ catch (error) {
83
+ reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window: " + (error instanceof Error ? error.message : "Unknown error")));
84
+ return;
85
+ }
86
+ if (!authWindow) {
87
+ reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window. Please allow popups."));
88
+ return;
89
+ }
90
+ const cleanup = () => {
91
+ window.removeEventListener("message", listener);
92
+ if (timeoutId)
93
+ clearTimeout(timeoutId);
94
+ if (checkClosedInterval)
95
+ clearInterval(checkClosedInterval);
96
+ };
97
+ const cleanupAndClose = (error) => {
98
+ cleanup();
99
+ try {
100
+ if (authWindow && !authWindow.closed) {
101
+ authWindow.close();
102
+ }
103
+ }
104
+ catch {
105
+ // Ignore close errors
106
+ }
107
+ if (error)
108
+ reject(error);
109
+ };
110
+ const listener = (event) => {
111
+ 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);
115
+ return;
116
+ }
117
+ // ✅ Validate payload
118
+ const tokenMsg = TokenMessageSchema.safeParse(event.data);
119
+ if (tokenMsg.success) {
120
+ cleanupAndClose();
121
+ resolve({ token: tokenMsg.data.access_token });
122
+ return;
123
+ }
124
+ const errorMsg = ErrorMessageSchema.safeParse(event.data);
125
+ if (errorMsg.success) {
126
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication failed: " + errorMsg.data.error));
127
+ return;
128
+ }
129
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
130
+ };
131
+ // Timeout handler
132
+ timeoutId = setTimeout(() => {
133
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));
134
+ }, timeout);
135
+ checkClosedInterval = setInterval(() => {
136
+ if (authWindow && authWindow.closed) {
137
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
138
+ }
139
+ }, 2000); // Reduced polling frequency
140
+ try {
141
+ window.addEventListener("message", listener);
142
+ }
143
+ catch (error) {
144
+ cleanup();
145
+ reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " + (error instanceof Error ? error.message : "Unknown error")));
146
+ return;
147
+ }
148
+ });
149
+ }
150
+
151
+ class TokenManager {
152
+ constructor(storage = sessionStorage, storageKey = "cams_token") {
153
+ this.storage = storage;
154
+ this.token = null;
155
+ this.storageKey = storageKey;
156
+ }
157
+ setToken(token) {
158
+ const parsed = TokenSchema.parse(token);
159
+ this.token = parsed;
160
+ this.storage.setItem(this.storageKey, JSON.stringify(parsed));
161
+ }
162
+ loadToken() {
163
+ if (this.token)
164
+ return this.token;
165
+ const raw = this.storage.getItem(this.storageKey);
166
+ if (!raw)
167
+ return null;
168
+ try {
169
+ const parsed = JSON.parse(raw);
170
+ try {
171
+ this.token = TokenSchema.parse(parsed);
172
+ return this.token;
173
+ }
174
+ catch (validationError) {
175
+ console.warn('Token validation failed:', validationError instanceof Error ? validationError.message : 'Unknown error');
176
+ this.storage.removeItem(this.storageKey);
177
+ return null;
178
+ }
179
+ }
180
+ catch (parseError) {
181
+ console.warn('Failed to parse stored token JSON:', parseError instanceof Error ? parseError.message : 'Unknown error');
182
+ this.storage.removeItem(this.storageKey);
183
+ return null;
184
+ }
185
+ }
186
+ clearToken() {
187
+ this.token = null;
188
+ this.storage.removeItem(this.storageKey);
189
+ }
190
+ getAccessToken() {
191
+ var _a;
192
+ const token = this.loadToken();
193
+ return (_a = token === null || token === void 0 ? void 0 : token.access_token) !== null && _a !== void 0 ? _a : null;
194
+ }
195
+ isExpired() {
196
+ const token = this.loadToken();
197
+ if (!token)
198
+ return true;
199
+ // JWT expiration check if available
200
+ if (token.id_token) {
201
+ try {
202
+ const parts = token.id_token.split(".");
203
+ if (parts.length < 3)
204
+ return true; // Invalid JWT format
205
+ const payload = JSON.parse(atob(parts[1]));
206
+ const exp = payload.exp * 1000;
207
+ return Date.now() > exp;
208
+ }
209
+ catch (error) {
210
+ console.warn('Failed to parse JWT token:', error instanceof Error ? error.message : 'Unknown error');
211
+ return true;
212
+ }
213
+ }
214
+ // Fallback: return true for safety when expiration cannot be determined
215
+ return true;
216
+ }
217
+ }
218
+
219
+ class CAMSSession {
220
+ constructor(storage = sessionStorage, storageKey, events = {}) {
221
+ this.tokenManager = new TokenManager(storage, storageKey);
222
+ this.events = events;
223
+ }
224
+ async login(config) {
225
+ var _a, _b, _c, _d, _e, _f, _g;
226
+ try {
227
+ (_b = (_a = this.events).onAuthStart) === null || _b === void 0 ? void 0 : _b.call(_a);
228
+ let attempts = 0;
229
+ const maxAttempts = ((_c = config.retryAttempts) !== null && _c !== void 0 ? _c : 0) + 1;
230
+ while (attempts < maxAttempts) {
231
+ try {
232
+ const response = await openCAMSPopUpLogin(config);
233
+ (_e = (_d = this.events).onAuthSuccess) === null || _e === void 0 ? void 0 : _e.call(_d, response);
234
+ return response;
235
+ }
236
+ catch (error) {
237
+ attempts++;
238
+ if (attempts >= maxAttempts || !(error instanceof CAMSError)) {
239
+ throw error;
240
+ }
241
+ // Only retry on specific error types
242
+ if (![exports.CAMSErrorType.TIMEOUT, exports.CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {
243
+ throw error;
244
+ }
245
+ }
246
+ }
247
+ throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED, 'Max retry attempts exceeded');
248
+ }
249
+ catch (error) {
250
+ const camsError = error instanceof CAMSError ? error :
251
+ 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);
253
+ throw camsError;
254
+ }
255
+ }
256
+ async logout() {
257
+ this.tokenManager.clearToken();
258
+ }
259
+ isAuthenticated() {
260
+ var _a, _b;
261
+ const token = this.tokenManager.loadToken();
262
+ if (!token)
263
+ return false;
264
+ if (this.tokenManager.isExpired()) {
265
+ (_b = (_a = this.events).onTokenExpired) === null || _b === void 0 ? void 0 : _b.call(_a);
266
+ return false;
267
+ }
268
+ return true;
269
+ }
270
+ getAccessToken() {
271
+ var _a, _b;
272
+ const token = this.tokenManager.loadToken();
273
+ if (!token)
274
+ return null;
275
+ if (this.tokenManager.isExpired()) {
276
+ (_b = (_a = this.events).onTokenExpired) === null || _b === void 0 ? void 0 : _b.call(_a);
277
+ return null;
278
+ }
279
+ return token.access_token;
280
+ }
281
+ decodeBase64Url(str) {
282
+ // Convert base64url to base64
283
+ str = str.replace(/-/g, '+').replace(/_/g, '/');
284
+ // Add padding if needed
285
+ while (str.length % 4) {
286
+ str += '=';
287
+ }
288
+ return atob(str);
289
+ }
290
+ async getProfile() {
291
+ const storedToken = this.tokenManager.loadToken();
292
+ if (!(storedToken === null || storedToken === void 0 ? void 0 : storedToken.id_token))
293
+ return null;
294
+ try {
295
+ const parts = storedToken.id_token.split('.');
296
+ if (parts.length >= 3) { // JWT has header.payload.signature format
297
+ try {
298
+ const payload = JSON.parse(this.decodeBase64Url(parts[1]));
299
+ return ProfileSchema.parse(payload);
300
+ }
301
+ catch (decodeError) {
302
+ console.warn('Failed to decode JWT payload:', decodeError instanceof Error ? decodeError.message : 'Unknown error');
303
+ }
304
+ }
305
+ }
306
+ catch (error) {
307
+ console.warn('Failed to extract profile from token:', error instanceof Error ? error.message : 'Unknown error');
308
+ }
309
+ return null;
310
+ }
311
+ }
312
+
313
+ exports.CAMSError = CAMSError;
314
+ exports.CAMSSession = CAMSSession;
315
+ exports.ErrorMessageSchema = ErrorMessageSchema;
316
+ exports.ProfileSchema = ProfileSchema;
317
+ exports.TokenManager = TokenManager;
318
+ exports.TokenMessageSchema = TokenMessageSchema;
319
+ exports.TokenSchema = TokenSchema;
320
+ exports.URLSchema = URLSchema;
321
+ exports.openCAMSPopUpLogin = openCAMSPopUpLogin;
322
+
323
+ }));
324
+ //# sourceMappingURL=index.umd.js.map
@@ -0,0 +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,IA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AAI,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;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,19 @@
1
+ import { CAMSConfig, CAMSTokenResponse, CAMSError } from "./types";
2
+ import { Profile } from "./validators";
3
+ export interface CAMSEvents {
4
+ onAuthStart?: () => void;
5
+ onAuthSuccess?: (token: CAMSTokenResponse) => void;
6
+ onAuthError?: (error: CAMSError) => void;
7
+ onTokenExpired?: () => void;
8
+ }
9
+ export declare class CAMSSession {
10
+ private readonly tokenManager;
11
+ private readonly events;
12
+ constructor(storage?: Storage, storageKey?: string, events?: CAMSEvents);
13
+ login(config: CAMSConfig): Promise<CAMSTokenResponse>;
14
+ logout(): Promise<void>;
15
+ isAuthenticated(): boolean;
16
+ getAccessToken(): string | null;
17
+ private decodeBase64Url;
18
+ getProfile(): Promise<Profile | null>;
19
+ }
@@ -0,0 +1,12 @@
1
+ import { Token } from "./validators";
2
+ export declare class TokenManager {
3
+ private readonly storage;
4
+ private token;
5
+ private readonly storageKey;
6
+ constructor(storage?: Storage, storageKey?: string);
7
+ setToken(token: Token): void;
8
+ loadToken(): Token | null;
9
+ clearToken(): void;
10
+ getAccessToken(): string | null;
11
+ isExpired(): boolean;
12
+ }
@@ -0,0 +1,28 @@
1
+ export interface CAMSConfig {
2
+ camsUrl: string;
3
+ allowedOrigin: string;
4
+ windowWidth: number;
5
+ windowHeight: number;
6
+ timeout?: number;
7
+ allowedDomains?: string[];
8
+ storageKey?: string;
9
+ retryAttempts?: number;
10
+ }
11
+ export declare enum CAMSErrorType {
12
+ POPUP_BLOCKED = "POPUP_BLOCKED",
13
+ TIMEOUT = "TIMEOUT",
14
+ INVALID_ORIGIN = "INVALID_ORIGIN",
15
+ USER_CANCELLED = "USER_CANCELLED",
16
+ INVALID_URL = "INVALID_URL",
17
+ MAX_RETRIES_EXCEEDED = "MAX_RETRIES_EXCEEDED"
18
+ }
19
+ export declare class CAMSError extends Error {
20
+ type: CAMSErrorType;
21
+ constructor(type: CAMSErrorType, message: string);
22
+ }
23
+ export interface CAMSTokenResponse {
24
+ token: string;
25
+ }
26
+ export interface CAMSErrorResponse {
27
+ error: string;
28
+ }
@@ -0,0 +1,26 @@
1
+ import { z } from "zod";
2
+ export declare const TokenMessageSchema: z.ZodObject<{
3
+ access_token: z.ZodString;
4
+ }, z.core.$strip>;
5
+ export type TokenMessage = z.infer<typeof TokenMessageSchema>;
6
+ export declare const ErrorMessageSchema: z.ZodObject<{
7
+ error: z.ZodString;
8
+ }, z.core.$strip>;
9
+ export declare const TokenSchema: z.ZodObject<{
10
+ access_token: z.ZodString;
11
+ refresh_token: z.ZodOptional<z.ZodString>;
12
+ expires_in: z.ZodNumber;
13
+ token_type: z.ZodDefault<z.ZodString>;
14
+ id_token: z.ZodOptional<z.ZodString>;
15
+ }, z.core.$strip>;
16
+ export type Token = z.infer<typeof TokenSchema>;
17
+ export declare const ProfileSchema: z.ZodObject<{
18
+ sub: z.ZodString;
19
+ name: z.ZodOptional<z.ZodString>;
20
+ email: z.ZodOptional<z.ZodEmail>;
21
+ given_name: z.ZodOptional<z.ZodString>;
22
+ family_name: z.ZodOptional<z.ZodString>;
23
+ roles: z.ZodOptional<z.ZodArray<z.ZodString>>;
24
+ }, z.core.$strip>;
25
+ export type Profile = z.infer<typeof ProfileSchema>;
26
+ export declare const URLSchema: z.ZodString;
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@nibssplc/cams-sdk",
3
+ "version": "0.0.1-beta.1",
4
+ "description": "Central Authentication Management Service (CAMS) SDK for popup-based authentication with Azure AD + custom 2FA",
5
+ "main": "dist/index.cjs.js",
6
+ "module": "dist/index.esm.js",
7
+ "unpkg": "dist/index.umd.js",
8
+ "types": "dist/types.d.ts",
9
+ "scripts": {
10
+ "build": "rollup -c",
11
+ "clean": "rm -rf dist",
12
+ "prepare": "npm run clean && npm run build",
13
+ "lint": "eslint src --ext .ts",
14
+ "test": "npx jest"
15
+ },
16
+ "keywords": [
17
+ "cams",
18
+ "authentication",
19
+ "azure-ad",
20
+ "2fa",
21
+ "sdk",
22
+ "popup-login"
23
+ ],
24
+ "author": "NIBSS PLC, Caleb Boluwade",
25
+ "license": "MIT",
26
+ "dependencies": {
27
+ "tslib": "^2.6.0",
28
+ "zod": "^4.0.17"
29
+ },
30
+ "peerDependencies": {
31
+ "tslib": "^2.6.0"
32
+ },
33
+ "devDependencies": {
34
+ "@rollup/plugin-commonjs": "^25.0.7",
35
+ "@rollup/plugin-node-resolve": "^15.2.3",
36
+ "@rollup/plugin-typescript": "^11.1.6",
37
+ "@types/jest": "^29.5.14",
38
+ "@types/node": "^20.11.24",
39
+ "babel-jest": "^30.0.5",
40
+ "jest": "^29.7.0",
41
+ "jest-environment-jsdom": "^29.7.0",
42
+ "rollup": "^4.21.1",
43
+ "ts-jest": "^29.4.1",
44
+ "typescript": "^5.4.5"
45
+ },
46
+ "files": [
47
+ "dist"
48
+ ],
49
+ "publishConfig": {
50
+ "access": "public"
51
+ }
52
+ }