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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@zytehub/auth-client

v1.3.0

Published

JavaScript API client for ZyteHub Authentication Service

Readme

@zytehub/auth-client

JavaScript API client for ZyteHub Authentication Service - a backend-as-a-service authentication solution.

Installation

npm install @zytehub/auth-client

Quick Start

const AuthClient = require('@zytehub/auth-client');

// Initialize the client
const client = new AuthClient({
  apiUrl: 'https://api.example.com',  // Your backend API URL
  platformId: 'your-platform-id',     // Your platform identifier (required for tracking)
  timeout: 30000                      // Request timeout in ms (default: 30000)
});

// Login
try {
  const result = await client.login({
    username: '[email protected]',
    password: 'password123',
    remember_device: true,           // Optional: remember device for 30 days
    device_fingerprint: '...',       // Optional: device fingerprint
    device_name: 'Chrome on Windows' // Optional: device name
  });
  
  // Tokens are automatically stored
  console.log('Login successful!');
  
  // Check if 2FA is required
  if (result.requires_2fa) {
    // Handle 2FA verification
  }
} catch (error) {
  console.error('Login failed:', error.message);
}

Configuration

Constructor Options

| Option | Type | Required | Default | Description | |--------|------|----------|---------|-------------| | apiUrl | string | Yes | - | Base URL of your authentication API (e.g., https://api.example.com) | | platformId | string | No | - | Platform identifier for usage tracking. Required for proper analytics. | | timeout | number | No | 30000 | Request timeout in milliseconds |

Platform ID

The platformId is crucial for:

  • Usage Analytics: Track which platform users are logging in from
  • Component Statistics: View platform-specific metrics in admin dashboard
  • Security Auditing: Associate login events with specific platforms

Important: Always set platformId when initializing the client. This ensures your platform's usage is properly tracked.

Authentication Methods

Login

const result = await client.login({
  username: '[email protected]',  // Email or username
  password: 'password123',
  remember_device: true,           // Optional: trust device for 30 days
  device_fingerprint: '...',       // Optional: device fingerprint
  device_name: 'Chrome on Windows' // Optional: device name
});

// Response:
// {
//   access: "jwt_access_token",
//   refresh: "jwt_refresh_token",
//   requires_2fa: false,  // true if 2FA is enabled
//   user: { ... }
// }

Logout

// Clear tokens locally
client.logout();

// Logout all sessions (requires authentication)
await client.logoutAllSessions();
client.logout(); // Clear local tokens

Token Management

// Get stored tokens
const tokens = client.getTokens();
// { access: "token", refresh: "refresh_token" }

// Set tokens manually (useful for SSR or custom flows)
client.setTokens(accessToken, refreshToken);

// Clear tokens
client.clearTokens();

// Refresh access token (automatically called on 401 errors)
await client.refreshAccessToken();

Automatic Token Refresh: The client automatically refreshes expired access tokens when a 401 error occurs. Tokens are stored in localStorage (browser) or memory (Node.js).

Two-Factor Authentication (2FA)

Verify 2FA Code

const result = await client.verify2FA({
  username: '[email protected]',
  otp_token: '123456',              // 6-digit code from authenticator app
  remember_device: true,            // Optional: trust device for 30 days
  device_fingerprint: '...',
  device_name: 'Chrome on Windows'
});

// Returns same structure as login() with access/refresh tokens

Setup 2FA

// Get QR code and secret
const setup = await client.setup2FA();
// {
//   qr_code: "data:image/png;base64,...",
//   secret: "JBSWY3DPEHPK3PXP",
//   provisioning_uri: "otpauth://totp/..."
// }

// Enable 2FA (after user scans QR code)
await client.enable2FA('123456'); // OTP code from authenticator app

Manage 2FA

// Disable 2FA (requires password)
await client.disable2FA('user_password');

// Generate backup codes
const codes = await client.generateBackupCodes();
// { backup_codes: ["code1", "code2", ...] }

// Login with backup code
const result = await client.verifyBackupCode({
  username: '[email protected]',
  backup_code: 'backup-code-here'
});

Password Management

Request Password Reset

await client.requestPasswordReset('[email protected]');
// Sends reset email to user

Confirm Password Reset

await client.confirmPasswordReset({
  token: 'reset-token-from-email',
  new_password: 'newSecurePassword123'
});

Change Password (Authenticated)

await client.changePassword({
  old_password: 'currentPassword',
  new_password: 'newSecurePassword123'
});

Email Verification

// Send verification email
await client.sendEmailVerification();

// Confirm email with token from email
await client.confirmEmailVerification('verification-token');

User Management

Get Current User

const user = await client.getCurrentUser();
// {
//   id: 1,
//   username: "johndoe",
//   email: "[email protected]",
//   first_name: "John",
//   last_name: "Doe",
//   is_email_verified: true,
//   has_2fa: false,
//   ...
// }

Update Profile

const updated = await client.updateProfile({
  email: '[email protected]',
  first_name: 'Jane',
  last_name: 'Smith'
});

Session Management

List Active Sessions

const sessions = await client.listSessions();
// [
//   {
//     id: "session-id",
//     device_name: "Chrome on Windows",
//     ip_address: "192.168.1.1",
//     last_activity: "2024-01-15T10:30:00Z",
//     is_current: true
//   },
//   ...
// ]

Trusted Devices

// Get trusted devices
const devices = await client.getTrustedDevices();

// Remove trusted device
await client.removeTrustedDevice('device-id');

Security & Compliance

Audit Logs

// Get user's security audit logs
const logs = await client.getAuditLogs({
  limit: 50,
  offset: 0,
  event_type: 'login_success' // Optional filter
});

// [
//   {
//     id: 1,
//     event_type: "login_success",
//     timestamp: "2024-01-15T10:30:00Z",
//     ip_address: "192.168.1.1",
//     user_agent: "Mozilla/5.0...",
//     metadata: { ... }
//   },
//   ...
// ]

Account Deletion (GDPR)

await client.requestAccountDeletion('user_password');
// Initiates account deletion process

Error Handling

The client throws errors for failed requests. Always wrap API calls in try/catch:

try {
  await client.login({ username, password });
} catch (error) {
  if (error.message.includes('Invalid credentials')) {
    // Handle invalid credentials
  } else if (error.message.includes('Account locked')) {
    // Handle locked account
  } else if (error.code === 'TIMEOUT') {
    // Handle timeout
  } else {
    // Handle other errors
    console.error('Unexpected error:', error);
  }
}

Common Error Messages

  • "Invalid credentials" - Wrong username/password
  • "Account locked" - Too many failed login attempts
  • "2FA required" - User has 2FA enabled, need to verify
  • "Request timeout after 30000ms" - Request took too long
  • "No refresh token available" - Cannot refresh expired token

Advanced Usage

Custom Request Headers

The client automatically adds:

  • Authorization: Bearer <token> (if authenticated)
  • X-Platform-ID: <platformId> (if provided)
  • Content-Type: application/json

Request Timeout

const client = new AuthClient({
  apiUrl: 'https://api.example.com',
  timeout: 10000 // 10 seconds
});

Server-Side Rendering (SSR)

For SSR, you may want to override token storage:

const client = new AuthClient({
  apiUrl: 'https://api.example.com',
  platformId: 'my-platform'
});

// Override setTokens to use cookies instead of localStorage
client.setTokens = function(access, refresh) {
  this.token = access;
  this.refreshToken = refresh;
  // Set HTTP-only cookies via your server
};

Platform Tracking

Critical: Always set platformId to ensure proper usage tracking:

// ✅ Correct - platform tracking enabled
const client = new AuthClient({
  apiUrl: window.location.origin,
  platformId: 'fireglue' // Your platform identifier
});

// ❌ Incorrect - no platform tracking
const client = new AuthClient({
  apiUrl: window.location.origin
  // Missing platformId!
});

API Reference

Authentication

  • login(credentials) - Login with username/password
  • logout() - Clear local tokens
  • logoutAllSessions() - Logout all sessions
  • refreshAccessToken() - Manually refresh access token

2FA

  • verify2FA(data) - Verify OTP code
  • setup2FA() - Get QR code for 2FA setup
  • enable2FA(otpToken) - Enable 2FA
  • disable2FA(password) - Disable 2FA
  • generateBackupCodes() - Generate backup codes
  • verifyBackupCode(data) - Login with backup code

Password

  • requestPasswordReset(email) - Request password reset email
  • confirmPasswordReset(data) - Confirm password reset
  • changePassword(data) - Change password (authenticated)

Email

  • sendEmailVerification() - Send verification email
  • confirmEmailVerification(token) - Confirm email

User

  • getCurrentUser() - Get current user profile
  • updateProfile(data) - Update user profile

Sessions

  • listSessions() - List active sessions
  • getTrustedDevices() - Get trusted devices
  • removeTrustedDevice(deviceId) - Remove trusted device

Security

  • getAuditLogs(filters) - Get security audit logs
  • requestAccountDeletion(password) - Request account deletion

Browser Support

  • Chrome (latest)
  • Firefox (latest)
  • Safari (latest)
  • Edge (latest)

Node.js Support

Works in Node.js 14+ with node-fetch or similar fetch polyfill.

License

MIT

Support

For issues and questions:

  • GitHub: https://github.com/zytehub/auth-client
  • Documentation: https://docs.zytehub.com/auth