rauth-provider
Version:
A lightweight, plug-and-play Node.js library for phone number authentication using the Rauth.io reverse verification flow via WhatsApp or SMS.
120 lines (107 loc) • 3.4 kB
JavaScript
// Fetch polyfill for Node.js < 18
import nodeFetch from 'node-fetch';
const fetch = globalThis.fetch || nodeFetch;
/**
* API Client for rauth.io integration
*/
class RauthApiClient {
constructor(config) {
this.config = config;
this.baseUrl = 'https://api.rauth.io/session';
}
/**
* Get session details from rauth.io API
* @param {string} sessionToken - Session token to query
* @returns {Promise<Object|null>} Session details or null if not found
*/
async getSessionDetails(sessionToken) {
try {
const response = await fetch(`${this.baseUrl}/status`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.config.rauth_api_key}`,
'X-App-ID': this.config.app_id,
},
body: JSON.stringify({
session_token: sessionToken,
}),
});
if (response.status === 404) {
return null; // Session not found
}
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(`Rauth API Error (${response.status}): ${errorData.message || response.statusText}`);
}
const data = await response.json();
return data;
} catch (error) {
if (error.name === 'TypeError' && error.message.includes('fetch')) {
throw new Error('Failed to connect to Rauth API. Please check your internet connection.');
}
throw error;
}
}
/**
* Verify session status with rauth.io API
* @param {string} sessionToken - Session token to verify
* @returns {Promise<Object|null>} Verification status or null if not found
*/
async verifySession(sessionToken) {
try {
const sessionDetails = await this.getSessionDetails(sessionToken);
if (!sessionDetails) {
return null;
}
// Check if session is verified
if (sessionDetails.status === 'verified') {
return {
verified: true,
phone: sessionDetails.phone,
timestamp: sessionDetails.timestamp,
ttl: sessionDetails.ttl || 900, // Default 15 minutes
};
}
// Check if session is revoked
if (sessionDetails.status === 'revoked') {
return {
verified: false,
revoked: true,
reason: sessionDetails.reason || 'revoked',
timestamp: sessionDetails.timestamp,
ttl: sessionDetails.ttl || 3600, // Default 1 hour
};
}
// Session exists but not verified yet
return {
verified: false,
revoked: false,
status: sessionDetails.status,
phone: sessionDetails.phone,
timestamp: sessionDetails.timestamp,
};
} catch (error) {
throw error;
}
}
/**
* Check if API is reachable
* @returns {Promise<boolean>} True if API is reachable
*/
async healthCheck() {
try {
const response = await fetch(`${this.baseUrl}/health`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${this.config.rauth_api_key}`,
'X-App-ID': this.config.app_id,
},
});
return response.ok;
} catch (error) {
return false;
}
}
}
export { RauthApiClient };