binoauth
v0.0.27
Published
Node.js SDK for BinoAuth authentication
Downloads
93
Maintainers
Readme
BinoAuth Core SDK
A comprehensive TypeScript SDK for BinoAuth authentication platform with support for multiple authentication flows, user management, and admin operations.
Features
- Multiple Authentication Methods: Password, Magic Link, OTP, OAuth 2.0, Social Login
- Multi-Factor Authentication: TOTP, SMS, Email verification
- Admin Operations: User management, tenant management, API key management
- Secure Token Storage: Encrypted token storage with multiple strategies
- Cross-Platform: Works in browsers, Node.js, React Native
- Type Safe: Full TypeScript support with comprehensive types
- OAuth 2.0 Complete: Authorization Code, Device Code, Client Credentials, and Refresh Token flows
Installation
npm install binoauth
# or
yarn add binoauth
# or
bun add binoauthQuick Start
Basic Authentication
import { BinoAuthClient } from 'binoauth';
const auth = new BinoAuthClient({
issuer: 'https://auth.binoauth.com',
clientId: 'your_client_id',
redirectUri: 'https://yourapp.com/callback'
});
// Password authentication
const result = await auth.loginWithPassword('[email protected]', 'password123');
if (result.success) {
console.log('Welcome,', result.user.name);
}
// Magic link authentication
await auth.magicLink.sendMagicLink({
email: '[email protected]',
returnTo: 'https://yourapp.com/dashboard'
});
// Check authentication status
const isLoggedIn = await auth.isAuthenticated();OAuth 2.0 Flow
// Authorization Code Flow
const authUrl = await auth.oauth.getAuthorizationUrl();
window.location.href = authUrl;
// Handle callback
const urlParams = new URLSearchParams(window.location.search);
await auth.oauth.handleCallback(
urlParams.get('code')!,
urlParams.get('state')!
);
// Device Code Flow (for devices without browsers)
const deviceAuth = await auth.oauth.requestDeviceCode();
console.log(`Visit: ${deviceAuth.verification_uri}`);
console.log(`Enter code: ${deviceAuth.user_code}`);
// Poll for authorization
await auth.oauth.pollForToken(deviceAuth.device_code);Authentication Flows
1. Password Authentication
import { PasswordFlow } from 'binoauth';
const passwordFlow = new PasswordFlow(config);
// Login
const result = await passwordFlow.login('[email protected]', 'password123');
// Register new user
await passwordFlow.register({
email: '[email protected]',
password: 'securepassword',
name: 'John Doe',
acceptTerms: true
});
// Login with credentials object
await passwordFlow.loginWithCredentials({
email: '[email protected]',
password: 'password123',
rememberMe: true
});2. Magic Link Authentication
import { MagicLinkFlow } from 'binoauth';
const magicLinkFlow = new MagicLinkFlow(config);
// Send magic link
await magicLinkFlow.sendMagicLink({
email: '[email protected]',
returnTo: 'https://yourapp.com/dashboard'
});
// Verify magic link token
const result = await magicLinkFlow.verifyMagicLink(token);
// Verify magic link code
const result = await magicLinkFlow.verifyMagicLinkCode(code);3. OTP Authentication
import { OTPFlow } from 'binoauth';
const otpFlow = new OTPFlow(config);
// Send phone OTP
await otpFlow.sendPhoneOTP({
phoneNumber: '+1234567890'
});
// Verify phone OTP
const result = await otpFlow.verifyPhoneOTP({
phoneNumber: '+1234567890',
code: '123456'
});4. Multi-Factor Authentication
import { MFAFlow } from 'binoauth';
const mfaFlow = new MFAFlow(config);
// Send MFA challenge
await mfaFlow.sendMFAChallenge({
challengeId: 'challenge_123',
method: 'sms'
});
// Verify MFA challenge
const result = await mfaFlow.verifyMFAChallenge({
challengeId: 'challenge_123',
code: '123456',
method: 'sms'
});5. Social Authentication
import { SocialFlow } from 'binoauth';
const socialFlow = new SocialFlow(config);
// Get authentication URL for provider
const googleUrl = await socialFlow.getAuthUrl('google');
window.location.href = googleUrl;
// Handle callback
const result = await socialFlow.handleCallback('google', code, state);
// Get available providers
const providers = await socialFlow.getAvailableProviders();OAuth 2.0 Flows
Authorization Code Flow
import { BinoAuthOAuth } from 'binoauth';
const oauth = new BinoAuthOAuth(config, storageConfig);
// Get authorization URL
const authUrl = await oauth.getAuthorizationUrl();
// Handle callback
const result = await oauth.handleCallback(code, state);Device Code Flow
// Request device code
const deviceAuth = await oauth.requestDeviceCode();
// Poll for token
await oauth.pollForToken(deviceAuth.device_code);Client Credentials Flow
// Get client credentials token
const tokenSet = await oauth.getClientCredentialsToken();Refresh Token Flow
// Refresh access token
const newTokenSet = await oauth.refreshAccessToken();Admin Operations
import { AdminClient } from 'binoauth';
const adminClient = new AdminClient({
baseUrl: 'https://auth.binoauth.com',
apiKey: 'admin_api_key',
tenantId: 'your_tenant_id'
});
// User management
const users = await adminClient.getUsers();
const user = await adminClient.getUser('user_id');
// Tenant management
const tenants = await adminClient.listTenants();
const tenant = await adminClient.getTenant('tenant_id');
await adminClient.createTenant(tenantData);
await adminClient.updateTenant('tenant_id', updateData);
// API key management
const apiKeys = await adminClient.listApiKeys();
const apiKey = await adminClient.createApiKey(apiKeyData);
await adminClient.revokeApiKey('key_id');
// OAuth client management
const clients = await adminClient.listClients();
const client = await adminClient.createClient(clientData);
const clientInfo = await adminClient.getClient('client_id');
// Provider management
const providers = await adminClient.listProviders();
const provider = await adminClient.createProvider(providerData);
// Statistics and health
const stats = await adminClient.getStats();
const health = await adminClient.healthCheck();
// Admin authentication
const adminAuth = await adminClient.adminLogin('[email protected]', 'password');
const currentAdmin = await adminClient.getCurrentAdmin();
await adminClient.adminLogout();Configuration
Basic Configuration
const config = {
issuer: 'https://auth.binoauth.com',
clientId: 'your_client_id',
redirectUri: 'https://yourapp.com/callback'
};Advanced Configuration
const config = {
issuer: 'https://auth.binoauth.com',
clientId: 'your_client_id',
clientSecret: 'your_client_secret', // For server-side apps
redirectUri: 'https://yourapp.com/callback',
scope: 'openid profile email',
// OAuth endpoints (auto-discovered by default)
authorizeEndpoint: 'https://auth.binoauth.com/oauth/authorize',
tokenEndpoint: 'https://auth.binoauth.com/oauth/token',
userinfoEndpoint: 'https://auth.binoauth.com/oauth/userinfo',
// Additional config
tenant: 'your_tenant_id',
apiKey: 'your_api_key'
};Token Storage Configuration
import { LocalStorageTokenStorage, SessionStorageTokenStorage, InMemoryTokenStorage } from 'binoauth';
// Use localStorage (default for browsers)
const storage = new LocalStorageTokenStorage({
clientId: 'your_client_id',
encryptionKey: 'your-encryption-key'
});
// Use sessionStorage (cleared when browser closes)
const sessionStorage = new SessionStorageTokenStorage({
clientId: 'your_client_id',
encryptionKey: 'your-encryption-key'
});
// Use in-memory storage (for server-side or testing)
const memoryStorage = new InMemoryTokenStorage({
clientId: 'your_client_id',
encryptionKey: 'your-encryption-key'
});Error Handling
import { AuthError, AuthErrorCode } from 'binoauth';
try {
await auth.loginWithPassword('[email protected]', 'wrong_password');
} catch (error) {
if (error instanceof AuthError) {
switch (error.code) {
case AuthErrorCode.INVALID_CREDENTIALS:
console.log('Invalid email or password');
break;
case AuthErrorCode.MFA_REQUIRED:
console.log('MFA required:', error.details);
break;
case AuthErrorCode.ACCOUNT_LOCKED:
console.log('Account is locked');
break;
case AuthErrorCode.ACCOUNT_NOT_FOUND:
console.log('Account not found');
break;
case AuthErrorCode.NETWORK_ERROR:
console.log('Network connection error');
break;
default:
console.log('Auth error:', error.message);
}
}
}TypeScript Support
The SDK is built with TypeScript and provides comprehensive type definitions:
import type {
AuthConfig,
AuthResult,
User,
LoginRequest,
SignupRequest,
TokenSet,
MFAChallenge,
AdminConfig
} from 'binoauth';
// All methods are fully typed
const result: AuthResult = await auth.loginWithPassword(email, password);
const user: User = result.user;Available Error Codes
INVALID_CREDENTIALS- Invalid email or passwordINVALID_EMAIL- Invalid email formatINVALID_PASSWORD- Invalid passwordINVALID_OTP- Invalid OTP codeEXPIRED_OTP- OTP code has expiredINVALID_TOKEN- Invalid or expired tokenACCOUNT_NOT_FOUND- User account not foundACCOUNT_LOCKED- Account is lockedACCOUNT_DISABLED- Account is disabledEMAIL_NOT_VERIFIED- Email verification requiredMFA_REQUIRED- Multi-factor authentication requiredTOO_MANY_ATTEMPTS- Too many failed attemptsRATE_LIMITED- Rate limit exceededEMAIL_ALREADY_EXISTS- Email already registeredWEAK_PASSWORD- Password is too weakNETWORK_ERROR- Network connection errorSERVER_ERROR- Server errorINVALID_CONFIG- Invalid configurationOAUTH_ERROR- OAuth-specific error
Examples
React Integration
import { BinoAuthClient } from 'binoauth';
import { useEffect, useState } from 'react';
function App() {
const [auth] = useState(() => new BinoAuthClient(config));
const [user, setUser] = useState(null);
useEffect(() => {
auth.isAuthenticated().then(isAuth => {
if (isAuth) {
auth.getUser().then(setUser);
}
});
}, []);
const handleLogin = async (email, password) => {
try {
const result = await auth.loginWithPassword(email, password);
if (result.success) {
setUser(result.user);
}
} catch (error) {
console.error('Login failed:', error.message);
}
};
return (
<div>
{user ? (
<div>Welcome, {user.name}!</div>
) : (
<LoginForm onLogin={handleLogin} />
)}
</div>
);
}Node.js Server
import { BinoAuthClient } from 'binoauth';
import express from 'express';
const app = express();
const auth = new BinoAuthClient({
issuer: 'https://auth.binoauth.com',
clientId: process.env.BINOAUTH_CLIENT_ID,
clientSecret: process.env.BINOAUTH_CLIENT_SECRET,
redirectUri: 'https://yourapp.com/callback'
});
app.get('/auth/callback', async (req, res) => {
try {
const result = await auth.oauth.handleCallback(
req.query.code,
req.query.state
);
// Store tokens and redirect
req.session.tokens = result.tokens;
res.redirect('/dashboard');
} catch (error) {
res.status(401).send('Authentication failed');
}
});License
MIT License - see LICENSE file for details.
Support
- Documentation: https://docs.binoauth.com
- Issues: GitHub Issues
- Email: [email protected]
