@cyphlens/2fa-sse-sdk 1.0.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.
package/README.md ADDED
@@ -0,0 +1,142 @@
1
+ # Cyphlens SSE Client SDK 🚀
2
+ A lightweight JavaScript library designed to simplify 2FA authentication with Cyphlens' Server-Sent Events (SSE) integration.
3
+
4
+ This SDK is bundled using **Rollup** and supports **ES Modules (ESM)**, **CommonJS (CJS)**, and **UMD (Universal Module Definition)** formats for maximum compatibility across environments.
5
+
6
+ ---
7
+
8
+ ## Features ✨
9
+ - Easy integration with Cyphlens 2FA authentication
10
+ - Real-time event listening via Server-Sent Events (SSE)
11
+ - Lightweight and dependency-free
12
+ - Cross-environment support (Node.js, browsers, and modern frameworks)
13
+
14
+ ---
15
+
16
+ ## Installation 📦
17
+
18
+ ### Using NPM
19
+ Install the SDK via npm:
20
+ ```sh
21
+ npm install @cyphlens/2fa-sse-sdk
22
+ ```
23
+
24
+ ### Using Yarn
25
+ Install the SDK via Yarn:
26
+ ```sh
27
+ yarn add @cyphlens/2fa-sse-sdk
28
+ ```
29
+
30
+ ### Using CDN (Browser)
31
+ Include the SDK directly in your HTML:
32
+ ```html
33
+ <script src="https://cdn.jsdelivr.net/npm/@cyphlens/2fa-sse-sdk/dist/bundle.umd.min.js"/>
34
+ ```
35
+
36
+ ---
37
+
38
+ ## Usage 🔧
39
+
40
+ ### Importing the SDK
41
+
42
+ #### 1. ES Modules (ESM) - Modern JavaScript
43
+ ```javascript
44
+ import Cyphlens from "@cyphlens/2fa-sse-sdk";
45
+ ```
46
+
47
+ #### 2. CommonJS (CJS) - Node.js
48
+ ```javascript
49
+ const Cyphlens = require("@cyphlens/2fa-sse-sdk");
50
+ ```
51
+
52
+ #### 3. Browser (UMD)
53
+ After including the CDN script, the SDK is available as a global `Cyphlens` object:
54
+ ```javascript
55
+ const cyphlensClient = new Cyphlens("https://your-api-base-url/b2b/v1");
56
+ ```
57
+
58
+ ---
59
+
60
+ ### Example: Listening to 2FA Events
61
+
62
+ #### 1. Initialize the Client
63
+ ```javascript
64
+ const baseUrl = "https://your-api-base-url"; // Replace with your API base URL
65
+ const sessionId = "your-session-id"; // Replace with your session ID
66
+ // Initialize the Cyphlens client
67
+ const cyphlensClient = new Cyphlens(`${baseUrl}/b2b/v1`);
68
+ ```
69
+
70
+ #### 2. Listen for Events
71
+ ```javascript
72
+ // Define the callback for handling events```
73
+ const onData = (eventType, data) => {
74
+ if (eventType === "MFASwipe") {
75
+ const twoFactorEvent = data;
76
+ console.log("2FA Status:", twoFactorEvent.status);
77
+ // Handle status change (e.g., update UI or trigger logic)
78
+ }
79
+ };
80
+ const onError = (error) => {
81
+ console.error("SSE Error:", error);
82
+ // Handle the error (e.g., retry connection, notify user)
83
+ };
84
+ // Start listening to events
85
+ cyphlensClient.listen(sessionId, onData, onError);
86
+ ```
87
+
88
+ #### 3. Stop Listening
89
+ ```javascript
90
+ // Stop the event listener when no longer needed```
91
+ cyphlensClient.stop();
92
+ ```
93
+
94
+ ---
95
+
96
+ ## API Reference 📚
97
+
98
+ ### ```new Cyphlens(baseUrl)```
99
+ - **baseUrl**: `string` - The base URL of your Cyphlens API (e.g., `"https://api.cyphlens.com/b2b/v1"`)
100
+ Creates a new instance of the Cyphlens client.
101
+
102
+ ### ```listen(sessionId, callback, errorCallback)```
103
+ - **sessionId**: `string` - The session ID to listen for events
104
+ - **callback**: `(eventType: string, data: any) => void` - Callback function to handle incoming events
105
+ - **errorCallback**: `(error: Event) => void` - Callback function to handle errors (optional)
106
+ Starts listening for Server-Sent Events tied to the specified session.
107
+
108
+ ### ```stop()```
109
+ Stops the event listener and closes the connection.
110
+
111
+ ---
112
+
113
+ ## Event Types
114
+ - **`MFASwipe`**: Triggered when a 2FA swipe event occurs.
115
+ - **data**: `{ status: string, ... }` - Contains the event details, including the 2FA status.
116
+
117
+ ---
118
+
119
+ ## Types
120
+ - `CyphlensErrorCallback`: `(error: Event) => void` - Type definition for the error callback function.
121
+
122
+ ## Requirements ⚙️
123
+ - **Node.js**: v14.x or higher (for CommonJS/ESM usage)
124
+ - **Browsers**: Modern browsers with support for Server-Sent Events (SSE)
125
+
126
+ ---
127
+
128
+ ## Contributing 🤝
129
+ We welcome contributions! Please follow these steps:
130
+ 1. Fork the repository
131
+ 2. Create a feature branch (```git checkout -b feature/YourFeature```)
132
+ 3. Commit your changes (```git commit -m "Add your feature"```)
133
+ 4. Push to the branch (```git push origin feature/YourFeature```)
134
+ 5. Open a Pull Request
135
+
136
+ ---
137
+
138
+ ## License 📄
139
+ This project is licensed under the Cyphlens License. See the [LICENSE](https://cyphlens.com/legal/terms-and-conditions.html) file for details.
140
+
141
+
142
+
@@ -0,0 +1,115 @@
1
+ var EventType;
2
+ (function (EventType) {
3
+ EventType["MFASwipe"] = "MFA.SWIPE";
4
+ EventType["Disconnect"] = "DISCONNECT";
5
+ })(EventType || (EventType = {}));
6
+ var StatusType;
7
+ (function (StatusType) {
8
+ StatusType["Pending"] = "PENDING";
9
+ StatusType["Success"] = "SUCCESS";
10
+ StatusType["Expired"] = "EXPIRED";
11
+ })(StatusType || (StatusType = {}));
12
+
13
+ class Cyphlens {
14
+ /**
15
+ * Initializes the Cyphlens service with a base URL.
16
+ * @param baseUrl The base API URL for connecting to the Cyphlens service.
17
+ */
18
+ constructor(baseUrl = "https://api.cyphme.com/b2c/v1") {
19
+ this.eventSource = null;
20
+ this.timeoutId = null;
21
+ /**
22
+ * Handles browser visibility changes to restart the SSE connection when the page becomes visible.
23
+ * This is primarily to prevent connection loss in Safari when the tab goes to the background.
24
+ */
25
+ this.onVisibilityChange = () => {
26
+ if (document.visibilityState === "visible" && this.sessionID) {
27
+ this.start();
28
+ }
29
+ };
30
+ this.baseUrl = baseUrl;
31
+ }
32
+ /**
33
+ * Updates the base API URL.
34
+ * @param baseUrl The new base URL.
35
+ */
36
+ setBaseUrl(baseUrl) {
37
+ this.baseUrl = baseUrl;
38
+ }
39
+ /**
40
+ * Starts the Server-Sent Events (SSE) connection to listen for authentication events.
41
+ * @returns The EventSource instance if successful, otherwise null.
42
+ */
43
+ start() {
44
+ if (!this.sessionID)
45
+ return null;
46
+ this.stop(); // Ensure any existing connections are closed before starting a new one.
47
+ this.eventSource = new EventSource(`${this.baseUrl}/cyphlens/status-events?sid=${this.sessionID}`);
48
+ // Listen for MFA swipe events
49
+ this.eventSource.addEventListener(EventType.MFASwipe, (event) => {
50
+ var _a, _b;
51
+ try {
52
+ const data = JSON.parse(event.data);
53
+ this.setupTimeout(data.expiresAt);
54
+ (_a = this.onSuccess) === null || _a === void 0 ? void 0 : _a.call(this, EventType.MFASwipe, data);
55
+ }
56
+ catch (error) {
57
+ console.error("Error parsing event data:", error);
58
+ const errorEvent = new Event('Something went wrong');
59
+ (_b = this.onError) === null || _b === void 0 ? void 0 : _b.call(this, errorEvent);
60
+ }
61
+ });
62
+ // Handle SSE errors
63
+ this.eventSource.addEventListener("error", (event) => {
64
+ var _a;
65
+ (_a = this.onError) === null || _a === void 0 ? void 0 : _a.call(this, event);
66
+ this.stop();
67
+ });
68
+ return this.eventSource;
69
+ }
70
+ /**
71
+ * Sets up a timeout to automatically stop the SSE connection when the event expires.
72
+ * @param expiresAt The expiration timestamp (milliseconds).
73
+ */
74
+ setupTimeout(expiresAt) {
75
+ if (this.timeoutId) {
76
+ clearTimeout(this.timeoutId);
77
+ }
78
+ // Calculate timeout duration and add a buffer (5000ms) before stopping the connection.
79
+ const timeoutDuration = expiresAt - Date.now() + 5000;
80
+ this.timeoutId = setTimeout(() => this.stop(), timeoutDuration);
81
+ }
82
+ /**
83
+ * Starts listening for authentication events.
84
+ * @param sessionId The session ID used for authentication.
85
+ * @param onData Callback function for handling successful authentication events.
86
+ * @param onError Callback function for handling errors.
87
+ * @returns The EventSource instance if successfully started, otherwise null.
88
+ */
89
+ listen(sessionId, onData, onError) {
90
+ this.sessionID = sessionId;
91
+ this.onSuccess = onData;
92
+ this.onError = onError;
93
+ // Attach visibility change listener to handle browser background issues (especially for iOS Safari).
94
+ if (typeof document !== "undefined") {
95
+ document.addEventListener("visibilitychange", this.onVisibilityChange);
96
+ }
97
+ return this.start();
98
+ }
99
+ /**
100
+ * Stops the SSE connection and clears any active timeouts.
101
+ */
102
+ stop() {
103
+ if (this.eventSource) {
104
+ this.eventSource.close();
105
+ this.eventSource = null;
106
+ }
107
+ if (this.timeoutId) {
108
+ clearTimeout(this.timeoutId);
109
+ this.timeoutId = null;
110
+ }
111
+ }
112
+ }
113
+
114
+ export { Cyphlens, EventType, StatusType, Cyphlens as default };
115
+ //# sourceMappingURL=index.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.esm.js","sources":["../src/types.ts","../src/index.ts"],"sourcesContent":["export enum EventType {\n MFASwipe = \"MFA.SWIPE\",\n Disconnect = \"DISCONNECT\",\n}\n\nexport enum StatusType {\n Pending = \"PENDING\",\n Success = \"SUCCESS\",\n Expired = \"EXPIRED\",\n}\n\nexport interface CyphlensEvent {}\n\nexport interface TwoFactorEvent extends CyphlensEvent { \n sessionId: string;\n status: StatusType;\n timestamp: number;\n expiresAt: number;\n}\n\nexport interface DisconnectEvent extends CyphlensEvent {\n message: string;\n}\n\nexport type EventCallback = (eventType: EventType, data: CyphlensEvent) => void;\nexport type CyphlensErrorCallback = (error: Event) => void;\n","import { EventCallback, TwoFactorEvent, EventType, CyphlensErrorCallback, StatusType, DisconnectEvent, CyphlensEvent } from './types';\nexport { EventCallback, TwoFactorEvent, EventType, CyphlensErrorCallback, StatusType, DisconnectEvent, CyphlensEvent }\nexport class Cyphlens {\n private baseUrl: string;\n private eventSource: EventSource | null = null;\n private sessionID?: string;\n private onSuccess?: EventCallback;\n private onError?: CyphlensErrorCallback;\n private timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * Initializes the Cyphlens service with a base URL.\n * @param baseUrl The base API URL for connecting to the Cyphlens service.\n */\n constructor(baseUrl: string = \"https://api.cyphme.com/b2c/v1\") {\n this.baseUrl = baseUrl;\n }\n\n /**\n * Updates the base API URL.\n * @param baseUrl The new base URL.\n */\n setBaseUrl(baseUrl: string): void {\n this.baseUrl = baseUrl;\n }\n\n /**\n * Starts the Server-Sent Events (SSE) connection to listen for authentication events.\n * @returns The EventSource instance if successful, otherwise null.\n */\n private start(): EventSource | null {\n if (!this.sessionID) return null;\n\n this.stop(); // Ensure any existing connections are closed before starting a new one.\n\n this.eventSource = new EventSource(`${this.baseUrl}/cyphlens/status-events?sid=${this.sessionID}`);\n\n // Listen for MFA swipe events\n this.eventSource.addEventListener(EventType.MFASwipe, (event: MessageEvent) => {\n try {\n const data: TwoFactorEvent = JSON.parse(event.data);\n this.setupTimeout(data.expiresAt);\n this.onSuccess?.(EventType.MFASwipe, data);\n } catch (error) {\n console.error(\"Error parsing event data:\", error);\n const errorEvent = new Event('Something went wrong');\n this.onError?.(errorEvent);\n }\n });\n\n // Handle SSE errors\n this.eventSource.addEventListener(\"error\", (event: Event) => {\n this.onError?.(event);\n this.stop();\n });\n\n return this.eventSource;\n }\n\n /**\n * Sets up a timeout to automatically stop the SSE connection when the event expires.\n * @param expiresAt The expiration timestamp (milliseconds).\n */\n private setupTimeout(expiresAt: number): void {\n if (this.timeoutId) {\n clearTimeout(this.timeoutId);\n }\n\n // Calculate timeout duration and add a buffer (5000ms) before stopping the connection.\n const timeoutDuration = expiresAt - Date.now() + 5000;\n this.timeoutId = setTimeout(() => this.stop(), timeoutDuration);\n }\n\n /**\n * Starts listening for authentication events.\n * @param sessionId The session ID used for authentication.\n * @param onData Callback function for handling successful authentication events.\n * @param onError Callback function for handling errors.\n * @returns The EventSource instance if successfully started, otherwise null.\n */\n listen(sessionId: string, onData?: EventCallback, onError?: CyphlensErrorCallback): EventSource | null {\n this.sessionID = sessionId;\n this.onSuccess = onData;\n this.onError = onError;\n\n // Attach visibility change listener to handle browser background issues (especially for iOS Safari).\n if (typeof document !== \"undefined\") {\n document.addEventListener(\"visibilitychange\", this.onVisibilityChange);\n }\n\n return this.start();\n }\n\n /**\n * Stops the SSE connection and clears any active timeouts.\n */\n stop(): void {\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n if (this.timeoutId) {\n clearTimeout(this.timeoutId);\n this.timeoutId = null;\n }\n }\n\n /**\n * Handles browser visibility changes to restart the SSE connection when the page becomes visible.\n * This is primarily to prevent connection loss in Safari when the tab goes to the background.\n */\n private readonly onVisibilityChange = (): void => {\n if (document.visibilityState === \"visible\" && this.sessionID) {\n this.start();\n }\n };\n}\n\nexport type CyphlensExports = {\n Cyphlens: typeof Cyphlens;\n EventType: typeof EventType;\n StatusType: typeof StatusType;\n TwoFactorEvent: TwoFactorEvent;\n CyphlensEvent: CyphlensEvent;\n DisconnectEvent: DisconnectEvent;\n EventCallback: EventCallback;\n CyphlensErrorCallback: CyphlensErrorCallback;\n};\n\nexport default Cyphlens;\n"],"names":[],"mappings":"IAAY;AAAZ,CAAA,UAAY,SAAS,EAAA;AACnB,IAAA,SAAA,CAAA,UAAA,CAAA,GAAA,WAAsB;AACtB,IAAA,SAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AAC3B,CAAC,EAHW,SAAS,KAAT,SAAS,GAGpB,EAAA,CAAA,CAAA;IAEW;AAAZ,CAAA,UAAY,UAAU,EAAA;AACpB,IAAA,UAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,UAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,UAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACrB,CAAC,EAJW,UAAU,KAAV,UAAU,GAIrB,EAAA,CAAA,CAAA;;MCPY,QAAQ,CAAA;AAQnB;;;AAGG;AACH,IAAA,WAAA,CAAY,UAAkB,+BAA+B,EAAA;QAVrD,IAAW,CAAA,WAAA,GAAuB,IAAI;QAItC,IAAS,CAAA,SAAA,GAAyC,IAAI;AAmG9D;;;AAGG;QACc,IAAkB,CAAA,kBAAA,GAAG,MAAW;YAC/C,IAAI,QAAQ,CAAC,eAAe,KA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B,YAAA,YAAY,CAAC,IAAI,CAAC,SAAS,CAAC;AAC5B,YAAA,IAAI,CAAC,SAAS,GAAG,IAAI;;;AAa1B;;;;"}
package/dist/index.js ADDED
@@ -0,0 +1,120 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ exports.EventType = void 0;
6
+ (function (EventType) {
7
+ EventType["MFASwipe"] = "MFA.SWIPE";
8
+ EventType["Disconnect"] = "DISCONNECT";
9
+ })(exports.EventType || (exports.EventType = {}));
10
+ exports.StatusType = void 0;
11
+ (function (StatusType) {
12
+ StatusType["Pending"] = "PENDING";
13
+ StatusType["Success"] = "SUCCESS";
14
+ StatusType["Expired"] = "EXPIRED";
15
+ })(exports.StatusType || (exports.StatusType = {}));
16
+
17
+ class Cyphlens {
18
+ /**
19
+ * Initializes the Cyphlens service with a base URL.
20
+ * @param baseUrl The base API URL for connecting to the Cyphlens service.
21
+ */
22
+ constructor(baseUrl = "https://api.cyphme.com/b2c/v1") {
23
+ this.eventSource = null;
24
+ this.timeoutId = null;
25
+ /**
26
+ * Handles browser visibility changes to restart the SSE connection when the page becomes visible.
27
+ * This is primarily to prevent connection loss in Safari when the tab goes to the background.
28
+ */
29
+ this.onVisibilityChange = () => {
30
+ if (document.visibilityState === "visible" && this.sessionID) {
31
+ this.start();
32
+ }
33
+ };
34
+ this.baseUrl = baseUrl;
35
+ }
36
+ /**
37
+ * Updates the base API URL.
38
+ * @param baseUrl The new base URL.
39
+ */
40
+ setBaseUrl(baseUrl) {
41
+ this.baseUrl = baseUrl;
42
+ }
43
+ /**
44
+ * Starts the Server-Sent Events (SSE) connection to listen for authentication events.
45
+ * @returns The EventSource instance if successful, otherwise null.
46
+ */
47
+ start() {
48
+ if (!this.sessionID)
49
+ return null;
50
+ this.stop(); // Ensure any existing connections are closed before starting a new one.
51
+ this.eventSource = new EventSource(`${this.baseUrl}/cyphlens/status-events?sid=${this.sessionID}`);
52
+ // Listen for MFA swipe events
53
+ this.eventSource.addEventListener(exports.EventType.MFASwipe, (event) => {
54
+ var _a, _b;
55
+ try {
56
+ const data = JSON.parse(event.data);
57
+ this.setupTimeout(data.expiresAt);
58
+ (_a = this.onSuccess) === null || _a === void 0 ? void 0 : _a.call(this, exports.EventType.MFASwipe, data);
59
+ }
60
+ catch (error) {
61
+ console.error("Error parsing event data:", error);
62
+ const errorEvent = new Event('Something went wrong');
63
+ (_b = this.onError) === null || _b === void 0 ? void 0 : _b.call(this, errorEvent);
64
+ }
65
+ });
66
+ // Handle SSE errors
67
+ this.eventSource.addEventListener("error", (event) => {
68
+ var _a;
69
+ (_a = this.onError) === null || _a === void 0 ? void 0 : _a.call(this, event);
70
+ this.stop();
71
+ });
72
+ return this.eventSource;
73
+ }
74
+ /**
75
+ * Sets up a timeout to automatically stop the SSE connection when the event expires.
76
+ * @param expiresAt The expiration timestamp (milliseconds).
77
+ */
78
+ setupTimeout(expiresAt) {
79
+ if (this.timeoutId) {
80
+ clearTimeout(this.timeoutId);
81
+ }
82
+ // Calculate timeout duration and add a buffer (5000ms) before stopping the connection.
83
+ const timeoutDuration = expiresAt - Date.now() + 5000;
84
+ this.timeoutId = setTimeout(() => this.stop(), timeoutDuration);
85
+ }
86
+ /**
87
+ * Starts listening for authentication events.
88
+ * @param sessionId The session ID used for authentication.
89
+ * @param onData Callback function for handling successful authentication events.
90
+ * @param onError Callback function for handling errors.
91
+ * @returns The EventSource instance if successfully started, otherwise null.
92
+ */
93
+ listen(sessionId, onData, onError) {
94
+ this.sessionID = sessionId;
95
+ this.onSuccess = onData;
96
+ this.onError = onError;
97
+ // Attach visibility change listener to handle browser background issues (especially for iOS Safari).
98
+ if (typeof document !== "undefined") {
99
+ document.addEventListener("visibilitychange", this.onVisibilityChange);
100
+ }
101
+ return this.start();
102
+ }
103
+ /**
104
+ * Stops the SSE connection and clears any active timeouts.
105
+ */
106
+ stop() {
107
+ if (this.eventSource) {
108
+ this.eventSource.close();
109
+ this.eventSource = null;
110
+ }
111
+ if (this.timeoutId) {
112
+ clearTimeout(this.timeoutId);
113
+ this.timeoutId = null;
114
+ }
115
+ }
116
+ }
117
+
118
+ exports.Cyphlens = Cyphlens;
119
+ exports.default = Cyphlens;
120
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../src/types.ts","../src/index.ts"],"sourcesContent":["export enum EventType {\n MFASwipe = \"MFA.SWIPE\",\n Disconnect = \"DISCONNECT\",\n}\n\nexport enum StatusType {\n Pending = \"PENDING\",\n Success = \"SUCCESS\",\n Expired = \"EXPIRED\",\n}\n\nexport interface CyphlensEvent {}\n\nexport interface TwoFactorEvent extends CyphlensEvent { \n sessionId: string;\n status: StatusType;\n timestamp: number;\n expiresAt: number;\n}\n\nexport interface DisconnectEvent extends CyphlensEvent {\n message: string;\n}\n\nexport type EventCallback = (eventType: EventType, data: CyphlensEvent) => void;\nexport type CyphlensErrorCallback = (error: Event) => void;\n","import { EventCallback, TwoFactorEvent, EventType, CyphlensErrorCallback, StatusType, DisconnectEvent, CyphlensEvent } from './types';\nexport { EventCallback, TwoFactorEvent, EventType, CyphlensErrorCallback, StatusType, DisconnectEvent, CyphlensEvent }\nexport class Cyphlens {\n private baseUrl: string;\n private eventSource: EventSource | null = null;\n private sessionID?: string;\n private onSuccess?: EventCallback;\n private onError?: CyphlensErrorCallback;\n private timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * Initializes the Cyphlens service with a base URL.\n * @param baseUrl The base API URL for connecting to the Cyphlens service.\n */\n constructor(baseUrl: string = \"https://api.cyphme.com/b2c/v1\") {\n this.baseUrl = baseUrl;\n }\n\n /**\n * Updates the base API URL.\n * @param baseUrl The new base URL.\n */\n setBaseUrl(baseUrl: string): void {\n this.baseUrl = baseUrl;\n }\n\n /**\n * Starts the Server-Sent Events (SSE) connection to listen for authentication events.\n * @returns The EventSource instance if successful, otherwise null.\n */\n private start(): EventSource | null {\n if (!this.sessionID) return null;\n\n this.stop(); // Ensure any existing connections are closed before starting a new one.\n\n this.eventSource = new EventSource(`${this.baseUrl}/cyphlens/status-events?sid=${this.sessionID}`);\n\n // Listen for MFA swipe events\n this.eventSource.addEventListener(EventType.MFASwipe, (event: MessageEvent) => {\n try {\n const data: TwoFactorEvent = JSON.parse(event.data);\n this.setupTimeout(data.expiresAt);\n this.onSuccess?.(EventType.MFASwipe, data);\n } catch (error) {\n console.error(\"Error parsing event data:\", error);\n const errorEvent = new Event('Something went wrong');\n this.onError?.(errorEvent);\n }\n });\n\n // Handle SSE errors\n this.eventSource.addEventListener(\"error\", (event: Event) => {\n this.onError?.(event);\n this.stop();\n });\n\n return this.eventSource;\n }\n\n /**\n * Sets up a timeout to automatically stop the SSE connection when the event expires.\n * @param expiresAt The expiration timestamp (milliseconds).\n */\n private setupTimeout(expiresAt: number): void {\n if (this.timeoutId) {\n clearTimeout(this.timeoutId);\n }\n\n // Calculate timeout duration and add a buffer (5000ms) before stopping the connection.\n const timeoutDuration = expiresAt - Date.now() + 5000;\n this.timeoutId = setTimeout(() => this.stop(), timeoutDuration);\n }\n\n /**\n * Starts listening for authentication events.\n * @param sessionId The session ID used for authentication.\n * @param onData Callback function for handling successful authentication events.\n * @param onError Callback function for handling errors.\n * @returns The EventSource instance if successfully started, otherwise null.\n */\n listen(sessionId: string, onData?: EventCallback, onError?: CyphlensErrorCallback): EventSource | null {\n this.sessionID = sessionId;\n this.onSuccess = onData;\n this.onError = onError;\n\n // Attach visibility change listener to handle browser background issues (especially for iOS Safari).\n if (typeof document !== \"undefined\") {\n document.addEventListener(\"visibilitychange\", this.onVisibilityChange);\n }\n\n return this.start();\n }\n\n /**\n * Stops the SSE connection and clears any active timeouts.\n */\n stop(): void {\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n if (this.timeoutId) {\n clearTimeout(this.timeoutId);\n this.timeoutId = null;\n }\n }\n\n /**\n * Handles browser visibility changes to restart the SSE connection when the page becomes visible.\n * This is primarily to prevent connection loss in Safari when the tab goes to the background.\n */\n private readonly onVisibilityChange = (): void => {\n if (document.visibilityState === \"visible\" && this.sessionID) {\n this.start();\n }\n };\n}\n\nexport type CyphlensExports = {\n Cyphlens: typeof Cyphlens;\n EventType: typeof EventType;\n StatusType: typeof StatusType;\n TwoFactorEvent: TwoFactorEvent;\n CyphlensEvent: CyphlensEvent;\n DisconnectEvent: DisconnectEvent;\n EventCallback: EventCallback;\n CyphlensErrorCallback: CyphlensErrorCallback;\n};\n\nexport default Cyphlens;\n"],"names":["EventType","StatusType"],"mappings":";;;;AAAYA;AAAZ,CAAA,UAAY,SAAS,EAAA;AACnB,IAAA,SAAA,CAAA,UAAA,CAAA,GAAA,WAAsB;AACtB,IAAA,SAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AAC3B,CAAC,EAHWA,iBAAS,KAATA,iBAAS,GAGpB,EAAA,CAAA,CAAA;AAEWC;AAAZ,CAAA,UAAY,UAAU,EAAA;AACpB,IAAA,UAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,UAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,UAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACrB,CAAC,EAJWA,kBAAU,KAAVA,kBAAU,GAIrB,EAAA,CAAA,CAAA;;MCPY,QAAQ,CAAA;AAQnB;;;AAGG;AACH,IAAA,WAAA,CAAY,UAAkB,+BAA+B,EAAA;QAVrD,IAAW,CAAA,WAAA,GAAuB,IAAI;QAItC,IAAS,CAAA,SAAA,GAAyC,IAAI;AAmG9D;;;AAGG;QACc,IAAkB,CAAA,kBAAA,GAAG,MAAW;YAC/C,IAAI,QAAQ,CAAC,eAAe,KAAK,SAAS,IAAI,IAAI,CAAC,SAAS,EAAE;gBAC5D,IAAI,CAAC,KAAK,EAAE;;AAEhB,SAAC;AApGC,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO;;AAGxB;;;AAGG;AACH,IAAA,UAAU,CAAC,OAAe,EAAA;AACxB,QAAA,IAAI,C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=== 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.CyphlensSSE = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ exports.EventType = void 0;
8
+ (function (EventType) {
9
+ EventType["MFASwipe"] = "MFA.SWIPE";
10
+ EventType["Disconnect"] = "DISCONNECT";
11
+ })(exports.EventType || (exports.EventType = {}));
12
+ exports.StatusType = void 0;
13
+ (function (StatusType) {
14
+ StatusType["Pending"] = "PENDING";
15
+ StatusType["Success"] = "SUCCESS";
16
+ StatusType["Expired"] = "EXPIRED";
17
+ })(exports.StatusType || (exports.StatusType = {}));
18
+
19
+ class Cyphlens {
20
+ /**
21
+ * Initializes the Cyphlens service with a base URL.
22
+ * @param baseUrl The base API URL for connecting to the Cyphlens service.
23
+ */
24
+ constructor(baseUrl = "https://api.cyphme.com/b2c/v1") {
25
+ this.eventSource = null;
26
+ this.timeoutId = null;
27
+ /**
28
+ * Handles browser visibility changes to restart the SSE connection when the page becomes visible.
29
+ * This is primarily to prevent connection loss in Safari when the tab goes to the background.
30
+ */
31
+ this.onVisibilityChange = () => {
32
+ if (document.visibilityState === "visible" && this.sessionID) {
33
+ this.start();
34
+ }
35
+ };
36
+ this.baseUrl = baseUrl;
37
+ }
38
+ /**
39
+ * Updates the base API URL.
40
+ * @param baseUrl The new base URL.
41
+ */
42
+ setBaseUrl(baseUrl) {
43
+ this.baseUrl = baseUrl;
44
+ }
45
+ /**
46
+ * Starts the Server-Sent Events (SSE) connection to listen for authentication events.
47
+ * @returns The EventSource instance if successful, otherwise null.
48
+ */
49
+ start() {
50
+ if (!this.sessionID)
51
+ return null;
52
+ this.stop(); // Ensure any existing connections are closed before starting a new one.
53
+ this.eventSource = new EventSource(`${this.baseUrl}/cyphlens/status-events?sid=${this.sessionID}`);
54
+ // Listen for MFA swipe events
55
+ this.eventSource.addEventListener(exports.EventType.MFASwipe, (event) => {
56
+ var _a, _b;
57
+ try {
58
+ const data = JSON.parse(event.data);
59
+ this.setupTimeout(data.expiresAt);
60
+ (_a = this.onSuccess) === null || _a === void 0 ? void 0 : _a.call(this, exports.EventType.MFASwipe, data);
61
+ }
62
+ catch (error) {
63
+ console.error("Error parsing event data:", error);
64
+ const errorEvent = new Event('Something went wrong');
65
+ (_b = this.onError) === null || _b === void 0 ? void 0 : _b.call(this, errorEvent);
66
+ }
67
+ });
68
+ // Handle SSE errors
69
+ this.eventSource.addEventListener("error", (event) => {
70
+ var _a;
71
+ (_a = this.onError) === null || _a === void 0 ? void 0 : _a.call(this, event);
72
+ this.stop();
73
+ });
74
+ return this.eventSource;
75
+ }
76
+ /**
77
+ * Sets up a timeout to automatically stop the SSE connection when the event expires.
78
+ * @param expiresAt The expiration timestamp (milliseconds).
79
+ */
80
+ setupTimeout(expiresAt) {
81
+ if (this.timeoutId) {
82
+ clearTimeout(this.timeoutId);
83
+ }
84
+ // Calculate timeout duration and add a buffer (5000ms) before stopping the connection.
85
+ const timeoutDuration = expiresAt - Date.now() + 5000;
86
+ this.timeoutId = setTimeout(() => this.stop(), timeoutDuration);
87
+ }
88
+ /**
89
+ * Starts listening for authentication events.
90
+ * @param sessionId The session ID used for authentication.
91
+ * @param onData Callback function for handling successful authentication events.
92
+ * @param onError Callback function for handling errors.
93
+ * @returns The EventSource instance if successfully started, otherwise null.
94
+ */
95
+ listen(sessionId, onData, onError) {
96
+ this.sessionID = sessionId;
97
+ this.onSuccess = onData;
98
+ this.onError = onError;
99
+ // Attach visibility change listener to handle browser background issues (especially for iOS Safari).
100
+ if (typeof document !== "undefined") {
101
+ document.addEventListener("visibilitychange", this.onVisibilityChange);
102
+ }
103
+ return this.start();
104
+ }
105
+ /**
106
+ * Stops the SSE connection and clears any active timeouts.
107
+ */
108
+ stop() {
109
+ if (this.eventSource) {
110
+ this.eventSource.close();
111
+ this.eventSource = null;
112
+ }
113
+ if (this.timeoutId) {
114
+ clearTimeout(this.timeoutId);
115
+ this.timeoutId = null;
116
+ }
117
+ }
118
+ }
119
+
120
+ exports.Cyphlens = Cyphlens;
121
+ exports.default = Cyphlens;
122
+
123
+ Object.defineProperty(exports, '__esModule', { value: true });
124
+
125
+ }));
126
+ //# sourceMappingURL=index.umd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.umd.js","sources":["../src/types.ts","../src/index.ts"],"sourcesContent":["export enum EventType {\n MFASwipe = \"MFA.SWIPE\",\n Disconnect = \"DISCONNECT\",\n}\n\nexport enum StatusType {\n Pending = \"PENDING\",\n Success = \"SUCCESS\",\n Expired = \"EXPIRED\",\n}\n\nexport interface CyphlensEvent {}\n\nexport interface TwoFactorEvent extends CyphlensEvent { \n sessionId: string;\n status: StatusType;\n timestamp: number;\n expiresAt: number;\n}\n\nexport interface DisconnectEvent extends CyphlensEvent {\n message: string;\n}\n\nexport type EventCallback = (eventType: EventType, data: CyphlensEvent) => void;\nexport type CyphlensErrorCallback = (error: Event) => void;\n","import { EventCallback, TwoFactorEvent, EventType, CyphlensErrorCallback, StatusType, DisconnectEvent, CyphlensEvent } from './types';\nexport { EventCallback, TwoFactorEvent, EventType, CyphlensErrorCallback, StatusType, DisconnectEvent, CyphlensEvent }\nexport class Cyphlens {\n private baseUrl: string;\n private eventSource: EventSource | null = null;\n private sessionID?: string;\n private onSuccess?: EventCallback;\n private onError?: CyphlensErrorCallback;\n private timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * Initializes the Cyphlens service with a base URL.\n * @param baseUrl The base API URL for connecting to the Cyphlens service.\n */\n constructor(baseUrl: string = \"https://api.cyphme.com/b2c/v1\") {\n this.baseUrl = baseUrl;\n }\n\n /**\n * Updates the base API URL.\n * @param baseUrl The new base URL.\n */\n setBaseUrl(baseUrl: string): void {\n this.baseUrl = baseUrl;\n }\n\n /**\n * Starts the Server-Sent Events (SSE) connection to listen for authentication events.\n * @returns The EventSource instance if successful, otherwise null.\n */\n private start(): EventSource | null {\n if (!this.sessionID) return null;\n\n this.stop(); // Ensure any existing connections are closed before starting a new one.\n\n this.eventSource = new EventSource(`${this.baseUrl}/cyphlens/status-events?sid=${this.sessionID}`);\n\n // Listen for MFA swipe events\n this.eventSource.addEventListener(EventType.MFASwipe, (event: MessageEvent) => {\n try {\n const data: TwoFactorEvent = JSON.parse(event.data);\n this.setupTimeout(data.expiresAt);\n this.onSuccess?.(EventType.MFASwipe, data);\n } catch (error) {\n console.error(\"Error parsing event data:\", error);\n const errorEvent = new Event('Something went wrong');\n this.onError?.(errorEvent);\n }\n });\n\n // Handle SSE errors\n this.eventSource.addEventListener(\"error\", (event: Event) => {\n this.onError?.(event);\n this.stop();\n });\n\n return this.eventSource;\n }\n\n /**\n * Sets up a timeout to automatically stop the SSE connection when the event expires.\n * @param expiresAt The expiration timestamp (milliseconds).\n */\n private setupTimeout(expiresAt: number): void {\n if (this.timeoutId) {\n clearTimeout(this.timeoutId);\n }\n\n // Calculate timeout duration and add a buffer (5000ms) before stopping the connection.\n const timeoutDuration = expiresAt - Date.now() + 5000;\n this.timeoutId = setTimeout(() => this.stop(), timeoutDuration);\n }\n\n /**\n * Starts listening for authentication events.\n * @param sessionId The session ID used for authentication.\n * @param onData Callback function for handling successful authentication events.\n * @param onError Callback function for handling errors.\n * @returns The EventSource instance if successfully started, otherwise null.\n */\n listen(sessionId: string, onData?: EventCallback, onError?: CyphlensErrorCallback): EventSource | null {\n this.sessionID = sessionId;\n this.onSuccess = onData;\n this.onError = onError;\n\n // Attach visibility change listener to handle browser background issues (especially for iOS Safari).\n if (typeof document !== \"undefined\") {\n document.addEventListener(\"visibilitychange\", this.onVisibilityChange);\n }\n\n return this.start();\n }\n\n /**\n * Stops the SSE connection and clears any active timeouts.\n */\n stop(): void {\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n if (this.timeoutId) {\n clearTimeout(this.timeoutId);\n this.timeoutId = null;\n }\n }\n\n /**\n * Handles browser visibility changes to restart the SSE connection when the page becomes visible.\n * This is primarily to prevent connection loss in Safari when the tab goes to the background.\n */\n private readonly onVisibilityChange = (): void => {\n if (document.visibilityState === \"visible\" && this.sessionID) {\n this.start();\n }\n };\n}\n\nexport type CyphlensExports = {\n Cyphlens: typeof Cyphlens;\n EventType: typeof EventType;\n StatusType: typeof StatusType;\n TwoFactorEvent: TwoFactorEvent;\n CyphlensEvent: CyphlensEvent;\n DisconnectEvent: DisconnectEvent;\n EventCallback: EventCallback;\n CyphlensErrorCallback: CyphlensErrorCallback;\n};\n\nexport default Cyphlens;\n"],"names":["EventType","StatusType"],"mappings":";;;;;;AAAYA;EAAZ,CAAA,UAAY,SAAS,EAAA;EACnB,IAAA,SAAA,CAAA,UAAA,CAAA,GAAA,WAAsB;EACtB,IAAA,SAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;EAC3B,CAAC,EAHWA,iBAAS,KAATA,iBAAS,GAGpB,EAAA,CAAA,CAAA;AAEWC;EAAZ,CAAA,UAAY,UAAU,EAAA;EACpB,IAAA,UAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;EACnB,IAAA,UAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;EACnB,IAAA,UAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;EACrB,CAAC,EAJWA,kBAAU,KAAVA,kBAAU,GAIrB,EAAA,CAAA,CAAA;;QCPY,QAAQ,CAAA;EAQnB;;;EAGG;EACH,IAAA,WAAA,CAAY,UAAkB,+BAA+B,EAAA;UAVrD,IAAW,CAAA,WAAA,GAAuB,IAAI;UAItC,IAAS,CAAA,SAAA,GAAyC,IAAI;EAmG9D;;;EAGG;UACc,IAAkB,CAAA,kBAAA,GAAG,MAAW;cAC/C,IAAI,QAAQ,CAAC,eAAe,KAAK,SAAS,IAAI,IAAI,CAAC,SAAS,EAAE;kBAC5D,IAAI,CAAC,KAAK,EAAE;;EAEhB,SAAC;EApGC,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO;;EAGxB;;;EAGG;EACH,IAAA,UAAU,CAAC,OAAe,EAAA;EACxB,QAAA,IAAI,CAAC,OAAO,GA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';
2
+ export { EventCallback, TwoFactorEvent, EventType, CyphlensErrorCallback, StatusType, DisconnectEvent, CyphlensEvent };
3
+ export declare class Cyphlens {
4
+ private baseUrl;
5
+ private eventSource;
6
+ private sessionID?;
7
+ private onSuccess?;
8
+ private onError?;
9
+ private timeoutId;
10
+ /**
11
+ * Initializes the Cyphlens service with a base URL.
12
+ * @param baseUrl The base API URL for connecting to the Cyphlens service.
13
+ */
14
+ constructor(baseUrl?: string);
15
+ /**
16
+ * Updates the base API URL.
17
+ * @param baseUrl The new base URL.
18
+ */
19
+ setBaseUrl(baseUrl: string): void;
20
+ /**
21
+ * Starts the Server-Sent Events (SSE) connection to listen for authentication events.
22
+ * @returns The EventSource instance if successful, otherwise null.
23
+ */
24
+ private start;
25
+ /**
26
+ * Sets up a timeout to automatically stop the SSE connection when the event expires.
27
+ * @param expiresAt The expiration timestamp (milliseconds).
28
+ */
29
+ private setupTimeout;
30
+ /**
31
+ * Starts listening for authentication events.
32
+ * @param sessionId The session ID used for authentication.
33
+ * @param onData Callback function for handling successful authentication events.
34
+ * @param onError Callback function for handling errors.
35
+ * @returns The EventSource instance if successfully started, otherwise null.
36
+ */
37
+ listen(sessionId: string, onData?: EventCallback, onError?: CyphlensErrorCallback): EventSource | null;
38
+ /**
39
+ * Stops the SSE connection and clears any active timeouts.
40
+ */
41
+ stop(): void;
42
+ /**
43
+ * Handles browser visibility changes to restart the SSE connection when the page becomes visible.
44
+ * This is primarily to prevent connection loss in Safari when the tab goes to the background.
45
+ */
46
+ private readonly onVisibilityChange;
47
+ }
48
+ export type CyphlensExports = {
49
+ Cyphlens: typeof Cyphlens;
50
+ EventType: typeof EventType;
51
+ StatusType: typeof StatusType;
52
+ TwoFactorEvent: TwoFactorEvent;
53
+ CyphlensEvent: CyphlensEvent;
54
+ DisconnectEvent: DisconnectEvent;
55
+ EventCallback: EventCallback;
56
+ CyphlensErrorCallback: CyphlensErrorCallback;
57
+ };
58
+ export default Cyphlens;
59
+ //# sourceMappingURL=index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aAAa,CAAC;IAC7B,qBAAqB,EAAE,qBAAqB,CAAC;CAC9C,CAAC;AAEF,eAAe,QAAQ,CAAC"}
@@ -0,0 +1,23 @@
1
+ export declare enum EventType {
2
+ MFASwipe = "MFA.SWIPE",
3
+ Disconnect = "DISCONNECT"
4
+ }
5
+ export declare enum StatusType {
6
+ Pending = "PENDING",
7
+ Success = "SUCCESS",
8
+ Expired = "EXPIRED"
9
+ }
10
+ export interface CyphlensEvent {
11
+ }
12
+ export interface TwoFactorEvent extends CyphlensEvent {
13
+ sessionId: string;
14
+ status: StatusType;
15
+ timestamp: number;
16
+ expiresAt: number;
17
+ }
18
+ export interface DisconnectEvent extends CyphlensEvent {
19
+ message: string;
20
+ }
21
+ export type EventCallback = (eventType: EventType, data: CyphlensEvent) => void;
22
+ export type CyphlensErrorCallback = (error: Event) => void;
23
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,oBAAY,SAAS;IACnB,QAAQ,cAAc;IACtB,UAAU,eAAe;CAC1B;AAED,oBAAY,UAAU;IACpB,OAAO,YAAY;IACnB,OAAO,YAAY;IACnB,OAAO,YAAY;CACpB;AAED,MAAM,WAAW,aAAa;CAAG;AAEjC,MAAM,WAAW,cAAe,SAAQ,aAAa;IACnD,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,UAAU,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,eAAgB,SAAQ,aAAa;IACpD,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,MAAM,aAAa,GAAG,CAAC,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,aAAa,KAAK,IAAI,CAAC;AAChF,MAAM,MAAM,qBAAqB,GAAG,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC"}
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@cyphlens/2fa-sse-sdk",
3
+ "version": "1.0.1",
4
+ "private": false,
5
+ "description": "Cyphlens SDK for 2FA SSE",
6
+ "main": "dist/index.js",
7
+ "module": "dist/index.esm.js",
8
+ "browser": "dist/index.umd.js",
9
+ "types": "dist/types/index.d.ts",
10
+ "publishConfig": {
11
+ "access": "restricted"
12
+ },
13
+ "files": [
14
+ "dist/"
15
+ ],
16
+ "scripts": {
17
+ "build": "rollup -c",
18
+ "test": "jest --coverage"
19
+ },
20
+ "devDependencies": {
21
+ "@rollup/plugin-commonjs": "^28.0.3",
22
+ "@rollup/plugin-node-resolve": "^16.0.1",
23
+ "@types/jest": "^29.5.14",
24
+ "jest": "^29.7.0",
25
+ "jest-environment-jsdom": "^29.7.0",
26
+ "jsdom": "^25.0.1",
27
+ "rollup": "^4.24.0",
28
+ "rollup-plugin-typescript2": "^0.36.0",
29
+ "ts-jest": "^29.2.5",
30
+ "tsx": "^4.19.2",
31
+ "typescript": "^5.6.3"
32
+ },
33
+ "keywords": [
34
+ "2fa",
35
+ "sse",
36
+ "cyphlens",
37
+ "sdk"
38
+ ],
39
+ "author": "Cyphlens",
40
+ "license": "ISC",
41
+ "dependencies": {
42
+ "eventsource": "^2.0.2"
43
+ }
44
+ }