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

saas-platform-auth-client

v1.5.1

Published

Authentication client for SaaS platform auth-service with password reset support

Readme

@saas-platform/auth-client

TypeScript/JavaScript client for SaaS platform authentication service.

Features

  • 🔐 Complete Auth Flow - Login, token refresh, validation, logout
  • 🔄 Password Recovery - Forgot password and reset with email verification
  • 🚀 Automatic Token Management - Built-in token storage and refresh
  • 📦 TypeScript Support - Full type safety with Zod validation
  • 🎯 SaaS Isolation - Automatic SaasId handling in JWT tokens
  • 👤 Admin Impersonation - Admin login as other users
  • 💾 Persistent Sessions - Token storage in localStorage
  • 📧 Email Integration - Secure password reset with 15-minute expiration

Installation

npm install @saas-platform/auth-client @saas-platform/core-client

Basic Usage

import { AuthClient } from '@saas-platform/auth-client';

const authClient = new AuthClient({
  saasId: 'your-saas-id',
  authServiceUrl: 'http://localhost:8000',
  timeout: 30000
});

// Login
const loginResponse = await authClient.login({
  email: '[email protected]',
  password: 'password123',
  saasId: 'your-saas-id'
});

if (loginResponse.success) {
  console.log('Logged in:', loginResponse.data?.user);
  
  // Tokens are automatically stored and managed
  console.log('Authenticated:', authClient.isAuthenticated());
}

Authentication Methods

Login

const response = await authClient.login({
  email: '[email protected]',
  password: 'password123',
  saasId: 'your-saas-id'
});

if (response.success) {
  const user = response.data?.user;
  const tokens = {
    accessToken: response.data?.accessToken,
    refreshToken: response.data?.refreshToken,
    expiresIn: response.data?.expiresIn
  };
}

Token Validation

// Check if current token is valid
const validation = await authClient.validateToken();

if (validation.success) {
  console.log('Token is valid:', validation.data?.isValid);
  console.log('User info:', validation.data?.user);
}

Logout

// Clear all stored tokens
authClient.logout();
console.log('Logged out:', !authClient.isAuthenticated());

Password Recovery

// Request password reset
const forgotResponse = await authClient.forgotPassword({
  email: '[email protected]',
  saasId: 'your-saas-id'
});

if (forgotResponse.success) {
  console.log('Reset email sent:', forgotResponse.data?.message);
  console.log('Code expires at:', forgotResponse.data?.expiresAt);
}

// Reset password with verification code
const resetResponse = await authClient.resetPassword({
  email: '[email protected]',
  resetCode: '123456', // 6-digit code from email
  newPassword: 'newSecurePassword123',
  saasId: 'your-saas-id'
});

if (resetResponse.success) {
  console.log('Password reset successful:', resetResponse.data?.message);
}

User Creation

Raw Password (Default)

const createUserResponse = await authClient.createUser({
  name: 'João Silva',
  email: '[email protected]',
  password: 'minhasenha123', // Raw password - will be hashed automatically
  isPasswordHashed: false, // Default, can be omitted
  role: 'User',
  phone: '11999999999',
  documentNumber: '12345678900',
  saasId: 'your-saas-id',
  isActive: true
});

if (createUserResponse.success) {
  console.log('User created:', createUserResponse.data?.userId);
}

Pre-hashed Password

const createUserResponse = await authClient.createUser({
  name: 'Maria Santos',
  email: '[email protected]',
  password: '$2a$11$...', // BCrypt hash already calculated
  isPasswordHashed: true, // Indicates password is already hashed
  role: 'Admin',
  saasId: 'your-saas-id'
});

if (createUserResponse.success) {
  console.log('User created with pre-hashed password:', createUserResponse.data?.userId);
}

⚠️ Important: When isPasswordHashed: true, ensure the password hash was generated using BCrypt with the same parameters as AuthService to guarantee compatibility during validation.

Admin Impersonation

// Login as another user (requires admin permissions)
const impersonation = await authClient.adminLogin({
  userId: 'user-guid-to-impersonate',
  saasId: 'target-saas-id'
});

if (impersonation.success) {
  console.log('Impersonating user:', impersonation.data?.user);
}

Token Management

The client automatically handles token lifecycle:

// Check authentication status
const isAuth = authClient.isAuthenticated();

// Get current user from token
const currentUser = authClient.getCurrentUser();
// Returns: { id, email, saasId, role }

// Get token information
const accessToken = authClient.getAccessToken();
const refreshToken = authClient.getRefreshToken();
const isExpired = authClient.isTokenExpired();

// Get user/saas info from token
const userId = authClient.getUserId();
const saasId = authClient.getSaasId();

Health Check

const health = await authClient.getHealth();

if (health.success) {
  console.log('Service status:', health.data?.status);
  console.log('Uptime:', health.data?.uptime);
}

Error Handling

All methods return a standardized response:

const response = await authClient.login(credentials);

if (!response.success) {
  console.error('Login failed:', response.error?.message);
  
  switch (response.error?.code) {
    case 'INVALID_CREDENTIALS':
      // Handle wrong email/password
      break;
    case 'SAAS_ID_REQUIRED':
      // Handle missing saasId
      break;
    case 'NETWORK_ERROR':
      // Handle connection issues
      break;
  }
}

Integration with React

// React hook example
import { useState, useEffect } from 'react';
import { AuthClient } from '@saas-platform/auth-client';

const useAuth = () => {
  const [authClient] = useState(() => new AuthClient(config));
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [user, setUser] = useState(null);

  useEffect(() => {
    setIsAuthenticated(authClient.isAuthenticated());
    setUser(authClient.getCurrentUser());
  }, [authClient]);

  const login = async (credentials) => {
    const response = await authClient.login(credentials);
    
    if (response.success) {
      setIsAuthenticated(true);
      setUser(authClient.getCurrentUser());
    }
    
    return response;
  };

  const logout = () => {
    authClient.logout();
    setIsAuthenticated(false);
    setUser(null);
  };

  return {
    authClient,
    isAuthenticated,
    user,
    login,
    logout
  };
};

TypeScript Types

The client includes complete TypeScript definitions:

interface LoginRequest {
  email: string;
  password: string;
  saasId: string;
}

interface LoginResponse {
  accessToken: string;
  refreshToken: string;
  expiresIn: number;
  tokenType: 'Bearer';
  user: {
    id: string;
    email: string;
    name: string;
    role: string;
    saasId: string;
    isActive: boolean;
  };
}

interface ForgotPasswordRequest {
  email: string;
  saasId: string;
}

interface ResetPasswordRequest {
  email: string;
  resetCode: string; // 6-digit numeric code
  newPassword: string;
  saasId: string;
}

interface PasswordResetResponse {
  success: boolean;
  message: string;
  expiresAt?: string; // ISO 8601 timestamp
}

Configuration

interface AuthClientConfig {
  saasId: string;           // Your SaaS identifier
  authServiceUrl: string;   // Auth service URL (e.g., 'http://localhost:8000')
  timeout?: number;         // Request timeout in milliseconds (default: 30000)
}

License

MIT