rauth-client
Version:
A lightweight, framework-agnostic JavaScript/TypeScript library for adding reverse authentication via WhatsApp on the client side.
63 lines (62 loc) • 2.04 kB
JavaScript
// Main entry for rauth-client
import { getDeviceInfo } from './utils/device';
const API_URL = 'https://api.rauth.io/session/init';
// Replace getIP to fetch IP and location from freeipapi
async function getIPAndLocation() {
try {
const res = await fetch('https://free.freeipapi.com/api/json');
const data = await res.json();
return {
ip: data.ipAddress || '',
city: data.cityName || '',
country: data.countryName || '',
location: (data.cityName && data.countryName) ? `${data.cityName}, ${data.countryName}` : '',
};
}
catch {
return { ip: '', city: '', country: '', location: '' };
}
}
export const rauth = {
/**
* Initialize a Rauth session
* @param params {RauthInitParams}
* @returns {Promise<RauthSessionResponse>}
*/
async init({ appId, phone }) {
if (!appId || !phone)
throw new Error('appId and phone are required');
const device = await getDeviceInfo();
const { ip, location } = await getIPAndLocation();
const body = {
phone,
ip,
location,
browser: device.browser,
platform: device.platform,
session_source: device.session_source
};
// Only send device_name if available
if (typeof navigator !== 'undefined' && navigator.platform && navigator.platform !== '') {
body.device_name = navigator.platform;
}
const res = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-app-id': appId
},
body: JSON.stringify(body)
});
if (!res.ok) {
const err = await res.text();
throw new Error('Rauth API error: ' + err);
}
return res.json();
}
};
// Attach to window for <script> usage
if (typeof window !== 'undefined') {
window.rauth = rauth;
}
export default rauth;