npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

binoauth

v0.0.27

Published

Node.js SDK for BinoAuth authentication

Downloads

93

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 binoauth

Quick 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 password
  • INVALID_EMAIL - Invalid email format
  • INVALID_PASSWORD - Invalid password
  • INVALID_OTP - Invalid OTP code
  • EXPIRED_OTP - OTP code has expired
  • INVALID_TOKEN - Invalid or expired token
  • ACCOUNT_NOT_FOUND - User account not found
  • ACCOUNT_LOCKED - Account is locked
  • ACCOUNT_DISABLED - Account is disabled
  • EMAIL_NOT_VERIFIED - Email verification required
  • MFA_REQUIRED - Multi-factor authentication required
  • TOO_MANY_ATTEMPTS - Too many failed attempts
  • RATE_LIMITED - Rate limit exceeded
  • EMAIL_ALREADY_EXISTS - Email already registered
  • WEAK_PASSWORD - Password is too weak
  • NETWORK_ERROR - Network connection error
  • SERVER_ERROR - Server error
  • INVALID_CONFIG - Invalid configuration
  • OAUTH_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