Introduction
This Cyphlens SDK is a lightweight JavaScript library designed to simplify Cyphlens 2FA authentication with Server-Sent Events (SSE) integration. This SDK enables Cyphlens swipe functionality and mobile browser verification for an even more seamless user experience.
We provide language bindings in HTML/Javascript and show code examples throughout this document.
We have both a Sandbox environment and a Production environment; we suggest to start with Sandbox for development and testing purposes.
API base URL (sandbox): https://api.sandbox.cyphme.com/b2b/v1
API base URL (production): https://api.prod.cyphme.com/b2b/v1
Installation
Using NPM
To install the Cyphlens SSE SDK using NPM, run the following command:
npm install @cyphlens/2fa-sse-sdk
Using Yarn
To install the Cyphlens SSE SDK using Yarn, run the following command:
yarn add @cyphlens/2fa-sse-sdk
Using a CDN (Browser)
To install the Cyphlens SSE SDK using a CDN, include this code in the <head> section of your
webpage:
<head>
...
<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/@cyphlens/2fa-sse-sdk/dist/bundle.min.js">
</script>
...
</head>
Importing the SDK
Depending on the approach followed for installation, the SDK can be imported in a few different ways.
ES Modules (ESM) - Modern JavaScript
import { Cyphlens, EventType } from "@cyphlens/2fa-sse-sdk";
CommonJS (CJS) - Node.js
const { Cyphlens, EventType } = require("@cyphlens/2fa-sse-sdk");
Browser (IIFE)
Once the Cyphlens SDK script has been included, the SDK is available as a global Cyphlens object
and can be used within the JavaScript code of your webpage.
Listening For 2FA Events
Initialize The Cyphlens SDK
Before being able to listen for events, we need to initialize the Cyphlens object with the correct environment.
In
the example below we use the sandbox environment.
const baseUrl = "https://api.sandbox.cyphme.com/b2b/v1";
const cyphlens = new Cyphlens(baseUrl);
Start Listening For Events
// Session ID from '/auth/login' endpoint
const sessionId = "current-session-id";
// Data callback - process events
const onData = (eventType, data) => {
if (eventType === EventType.MFASwipe) {
const twoFactorEvent = data;
console.log("2FA Status:", twoFactorEvent.status);
// Handle status change (e.g., update UI or trigger logic)
}
};
// Error callback - process errors
const onError = (error) => {
console.error("SSE Error:", error);
// Handle the error (e.g., retry connection, notify user)
};
// Start listening to events and register callbacks
cyphlens.listen(sessionId, onData, onError);
After the SDK has been initialized, we can check for MFASwipe events returning the status of a
Cyphlens
verification process. This is a process initiated by the end-user by using the swipe functionality within the
Cyphlens app.
Stop Listening For Events
When no longer needed, the SDK event listener should be stopped and the connection to the Cyphlens backend closed.
// Stop listening for events and close the connection if open
cyphlens.stop();
API Reference
Methods
new Cyphlens(baseUrl)
Creates a new instance of the Cyphlens client.
Example
const cyphlens = new Cyphlens("https://api.sandbox.cyphme.com/b2b/v1");
Parameters
| Parameter | Type | Description |
|---|---|---|
| baseUrl | string | The base URL of your Cyphlens API (e.g., "https://api.sandbox.cyphme.com/b2b/v1") |
Returns: Cyphlens instance
listen(sessionId, callback, errorCallback)
Starts listening for Server-Sent Events tied to the specified session.
Example
cyphlens.listen(
"ff36e371f11f4ec6870d5cd74c9fxxxx",
(eventType, data) => {
console.log("Event:", eventType, data);
// data: event data object or string message
},
(error) => {
console.error("Error:", error);
}
);
Parameters
| Parameter | Type | Description |
|---|---|---|
| sessionId | string | The session ID to listen for events |
| callback | (eventType: string, data: any) => void |
Callback function to handle incoming events |
| errorCallback | (error: Event) => void |
Callback function to handle errors (optional) |
Returns: void
stop()
Stops the event listener and closes the connection. Always call this method when the component unmounts or the page unloads to clean up resources.
Parameters: None
Returns: void
Example
cyphlens.stop();
Events
Event Types
Currently, the SDK supports the following event type:
| Event Type | Description |
|---|---|
MFA.SWIPE |
Triggered when a 2FA swipe event occurs |
DISCONNECT |
Triggered when the server disconnects |
MFA.SWIPE Event
Data Structure
{
sessionId: string, // The session ID associated with this event
status: string, // "SUCCESS", "FAILURE", "PENDING", or "EXPIRED"
timestamp: number, // Event timestamp in milliseconds (UTC)
expiresAt: number // Expiration timestamp in milliseconds (UTC) - only present for PENDING status
}
Example - PENDING status
{
"sessionId": "ff36e371f1f4ec6870d5cd74c9fxxxx",
"expiresAt": 123234435546,
"status": "PENDING",
"timestamp": 1726502908001
}
Example - SUCCESS status
{
"sessionId": "ff36e371f1f4ec6870d5cd74c9fxxxx",
"status": "SUCCESS",
"timestamp": 1726502929233
}
Example - EXPIRED status
{
"sessionId": "b96a05e5b87e4b5f95dde4939087xxxx",
"status": "EXPIRED",
"timestamp": 1726498730995
}
Possible Status Values
| Status | Description |
|---|---|
SUCCESS |
The user has successfully verified the Cyphlens image |
FAILURE |
The verification failed due to invalid data or user error |
PENDING |
The user has not yet completed the verification |
EXPIRED |
The Cyphlens image has expired (after 60 seconds) |
DISCONNECT Event
Triggered when the server disconnects the connection.
Data Structure
"The server disconnected" // A string describing the disconnect reason
Error Handling
Errors may occur in the following scenarios:
| Scenario | Description |
|---|---|
| Network connection lost | The connection to the server was interrupted |
| Invalid session ID | The provided session ID does not exist or is malformed |
| Session expired | The session has timed out (after 60 seconds) |
| Server unavailable | The Cyphlens server is temporarily unavailable |
| Server disconnect | The server intentionally closed the connection (triggers DISCONNECT event) |
Example error handling:
cyphlens.listen(
sessionId,
(eventType, data) => {
if (eventType === "DISCONNECT") {
// Server disconnected - handle gracefully
console.log("Server disconnected:", data);
showErrorMessage("Connection closed. Please refresh to try again.");
}
// Handle other events...
},
(error) => {
// Network or connection errors
console.error("Connection error:", error);
showErrorMessage("Connection error. Please check your network and try again.");
}
);
Complete Example
Here is a full end-to-end example of using the Cyphlens SDK:
// 1. Create client instance
const cyphlens = new Cyphlens("https://api.sandbox.cyphme.com/b2b/v1");
// 2. Start listening after displaying Cyphlens image
cyphlens.listen(
sessionId,
(eventType, data) => {
switch (eventType) {
case "MFA.SWIPE":
// Received SWIPE event
switch (data.status) {
case "SUCCESS":
// User verified successfully - proceed with login
window.location.href = "/home";
break;
case "EXPIRED":
// Close SSE connection
cyphlens.stop();
// The Cyphlens image has expired - refresh
showAlertMessage("Cyphlens image expired. Please refresh and try again.");
break;
case "FAILURE":
// Close SSE connection
cyphlens.stop();
// Show error message
showErrorMessage("Verification failed. Please try again.");
break;
case "PENDING":
// Still waiting for user action
// You can use data.expiresAt to show a countdown timer
console.log("Waiting for verification, expires at:", data.expiresAt);
break;
}
break;
case "DISCONNECT":
// Server disconnected
console.log("Disconnected:", data);
showErrorMessage("Connection lost. Please refresh the page.");
break;
}
},
(error) => {
// Close SSE connection
cyphlens.stop();
// General error
console.error("Connection error:", error);
showErrorMessage("Connection error. Please refresh the page.");
}
);
// 3. Clean up when leaving page
window.addEventListener("beforeunload", () => {
cyphlens.stop();
});
Best Practices
- Always call
stop()when the component unmounts or page unloads to prevent memory leaks - Handle all status values in your callback to provide appropriate user feedback
- Handle the
DISCONNECTevent to gracefully inform users when the server closes the connection - Implement error handling to gracefully handle network issues
- Refresh expired images - Cyphlens images by default are valid for only 60 seconds (use
expiresAtto show countdown) - Provide visual feedback to users while waiting for verification (e.g., loading spinner)
Errors
The Cyphlens API uses the following error codes:
| Error Code | Meaning |
|---|---|
| 400 | Bad Request -- Your request has some invalid or missing data. |
| 401 | Unauthorized -- Either your API key is wrong, your access token is wrong or your IP address is invalid. |
| 404 | Not Found -- The specified end-user could not be found. |
| 405 | Method Not Allowed -- You tried to access the Cyphlens API with an invalid method. |
| 406 | Not Acceptable -- You requested a format that isn't json. |
| 429 | Too Many Requests -- You're sending too many requests! Slow down! |
| 500 | Internal Server Error -- We had a problem with our server. Try again later. |
| 503 | Service Unavailable -- We're temporarily offline for maintenance. Please try again later. |