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

@mirats/mirats-auth

v2.0.6

Published

Mamauth SDK for authentication and user management

Readme

Mamauth SDK

A TypeScript SDK for integrating Mamauth authentication and user management into your applications.

Package: @mirats/mirats-auth
Version: 2.0.7

Installation

npm install @mirats/[email protected]
# or
yarn add @mirats/[email protected]
# or
pnpm add @mirats/[email protected]

Dependencies

The SDK requires the following peer dependencies:

  • crypto-js - For URL encryption/decryption
  • jwt-decode - For JWT token decoding

Configuration

The SDK automatically detects the Mamauth origin URL. You can override it by:

  1. Environment Variable (Client-side):

    process.env.NEXT_PUBLIC_MAMAUTH_ORIGIN = 'https://your-custom-domain.com'
  2. Global Variable (Client-side):

    window.__MAMAUTH_ORIGIN__ = 'https://your-custom-domain.com'
  3. Environment Variable (Server-side):

    process.env.MAMAUTH_ORIGIN = 'https://your-custom-domain.com'

Default: https://accounts.miratsgroup.com

Usage

Import the SDK

import {
  signIn,
  signUp,
  getAuth,
  isLoggedIn,
  logOut,
  getCookie,
  setCookie,
  deleteCookie,
  // ... other functions
} from '@mirats/mirats-auth';

Authentication Functions

Sign In

Redirects user to the login page with optional redirect URL:

// Sign in with default redirect
await signIn();

// Sign in with custom redirect URL
await signIn('https://myservice.example.com');

Sign In With Service

Sign in and automatically check service access:

await signInWithService('https://myservice.example.com');

Sign Up

Redirects user to the registration page:

await signUp();

Forgot Password

Redirects user to the forgot password page:

await forgotPassword();

Get Authentication Status

Get the current user's authentication status and user data with service access:

const auth = await getAuth();
if (auth) {
  console.log('User is authenticated:', auth.currentUser);
  console.log('Token:', auth.token);
  console.log('Session ID:', auth.sessionId);
  console.log('Service Access:', auth.currentUser.access);
  
  // Access user personal information (available in v2.0.7+)
  console.log('Date of Birth:', auth.currentUser.DOB);
  console.log('Gender:', auth.currentUser.gender);
  console.log('Phone:', auth.currentUser.phone_country_code, auth.currentUser.phone);
  console.log('Country:', auth.currentUser.country);
  console.log('Default Language:', auth.currentUser.defaultLanguage);
} else {
  console.log('User is not authenticated');
}

Response Type:

interface AuthResponse {
  token: string;
  sessionId: string;
  session?: SessionInfo;
  currentUser: {
    _id: string;
    email: string;
    firstName: string;
    lastName: string;
    fullName: string;
    accountStatus: string;
    avatar?: string;
    access?: ServiceAccess[]; // Service access data
    
    // Personal Information
    DOB?: string | Date;
    gender?: string;
    pronouns?: string;
    phone?: string;
    phone_country_code?: string;
    secondaryEmail?: string;
    
    // Location Information
    country?: string;
    country_code?: string;
    countryMetadata?: any;
    
    // Preferences
    defaultLanguage?: string;
    
    // Additional Information
    addresses?: {
      workAddress?: string;
      homeAddress?: string;
    };
    about?: {
      introduction?: string;
      sports?: string;
      music?: string;
      books?: string;
    };
    workAndEducationDetails?: {
      work?: {
        companyName?: string;
        designation?: string;
        startDate?: Date | string;
        endDate?: Date | string;
        currentlyWorking?: boolean;
        description?: string;
      };
      education?: {
        collegeName?: string;
        degree?: string;
        startDate?: Date | string;
        endDate?: Date | string;
        currentlyStudying?: boolean;
        description?: string;
      };
    };
  };
}

Check if Logged In

Quick check if user has a valid token:

const { user, loading } = isLoggedIn();
if (user) {
  console.log('User is logged in');
}

Log Out

Log out the current user and clear cookies:

await logOut();

Cookie Management

The SDK now uses token and GAS-SE cookies (primary) with frontendCookie as fallback for backward compatibility.

Get Cookie

const token = getCookie('token');

Get Token (Helper)

const token = getToken(); // Gets token from 'token' cookie or 'frontendCookie' fallback

Get Session ID (Helper)

const sessionId = getSessionId(); // Gets session ID from 'GAS-SE' cookie

Set Cookie

setCookie('token', 'your-token-value'); // 5 days expiration (default)

Delete Cookie

deleteCookie('token');

Clear All Auth Cookies (Helper)

clearAllAuthCookies(); // Clears token, GAS-SE, and frontendCookie

User Management

Get GAS ID

Get a user's GAS ID by email:

const result = await getGasId('[email protected]');
if (result) {
  console.log('GAS ID:', result.gasId);
}

Get Multiple GAS IDs

Get GAS IDs for multiple users (max 10):

const results = await getGasIds([
  '[email protected]',
  '[email protected]',
]);
// Returns: [{ email: '[email protected]', gasId: '...' }, ...]

Invitations

Generate Invite Link

const link = inviteLink(
  '[email protected]',
  'user-id',
  'John', // firstName (optional)
  'Doe',  // lastName (optional)
  30      // days until expiration (default: 30)
);

Send User Invite

const result = await sendUserInvite({
  name: 'John Doe',
  email: '[email protected]',
  id: 'user-id',
  organizationName: 'My Organization',
  invitedBy: 'inviter-id',
  days: 30, // optional
});

if (result.success) {
  console.log('Invite sent successfully');
}

Send Multiple Invites

const results = await sendUserInvites([
  {
    name: 'John Doe',
    email: '[email protected]',
    id: 'user-id-1',
    organizationName: 'My Organization',
    invitedBy: 'inviter-id',
  },
  {
    name: 'Jane Smith',
    email: '[email protected]',
    id: 'user-id-2',
    organizationName: 'My Organization',
    invitedBy: 'inviter-id',
  },
]);
// Returns only successful invites

Service Management

Create Service

await createService({
  name: 'My Service',
  subdomain: 'myservice',
  type: 'private',
  url: 'https://myservice.example.com',
});

Check Service Access

Check if the current user has access to a service:

const hasAccess = await checkServiceAccess('https://myservice.example.com');
if (hasAccess) {
  console.log('User has access');
} else {
  console.log('User does not have access');
}

Utility Functions

Encrypt URL

const encrypted = encryptURL('https://example.com');

Decrypt URL

const decrypted = decryptURL(encryptedUrl);

Validate Email

if (isValidEmail('[email protected]')) {
  console.log('Valid email');
}

Add Days to Date

const futureDate = addDays(7); // 7 days from now

User Data Fields

The currentUser object includes comprehensive user information (available in v2.0.7+):

Basic Information

  • _id, email, firstName, lastName, fullName, accountStatus, avatar

Personal Information

  • DOB - Date of birth (string or Date)
  • gender - User's gender
  • pronouns - Preferred pronouns
  • phone - Phone number
  • phone_country_code - Country code for phone (e.g., '+91')
  • secondaryEmail - Secondary email address

Location Information

  • country - Country name
  • country_code - ISO country code
  • countryMetadata - Additional country metadata (flag, emoji, etc.)

Preferences

  • defaultLanguage - User's default language preference

Additional Information

  • addresses - Work and home addresses
  • about - Personal interests (introduction, sports, music, books)
  • workAndEducationDetails - Work experience and education history

Example Usage

const auth = await getAuth();
if (auth?.currentUser) {
  const user = auth.currentUser;
  
  // Personal info
  console.log('Name:', user.fullName);
  console.log('DOB:', user.DOB);
  console.log('Gender:', user.gender);
  console.log('Phone:', user.phone_country_code, user.phone);
  
  // Location
  console.log('Country:', user.country);
  
  // Preferences
  console.log('Language:', user.defaultLanguage);
  
  // Additional info
  if (user.addresses) {
    console.log('Work Address:', user.addresses.workAddress);
    console.log('Home Address:', user.addresses.homeAddress);
  }
}

Cookie Names

The SDK uses the following cookie names:

  • token - JWT authentication token (primary)
  • GAS-SE - Session ID in format: ${random}-${mongoId} (primary)
  • frontendCookie - Legacy cookie name (fallback for backward compatibility)

API Endpoints

The SDK communicates with the following endpoints:

  • Base URL: https://accounts.miratsgroup.com (or your configured origin)
  • Accounts API: ${baseURL}/accounts
  • Public Package APIs: https://accounts-public-apis.miratsgroup.com (or override via window.MAMAUTH_PUBLIC_API_URL)

Override Public API URL

You can override the public API base URL by setting a global variable:

// In your application initialization
(window as any).MAMAUTH_PUBLIC_API_URL = 'https://your-custom-api.com';

Error Handling

All functions that make API calls will throw errors or return null/false on failure. Always check the return values:

try {
  const auth = await getAuth();
  if (!auth) {
    // User not authenticated
    await signIn();
  }
} catch (error) {
  console.error('Authentication error:', error);
}

User Data Fields

The currentUser object includes comprehensive user information:

Basic Information

  • _id, email, firstName, lastName, fullName, accountStatus, avatar

Personal Information

  • DOB - Date of birth (string or Date)
  • gender - User's gender
  • pronouns - Preferred pronouns
  • phone - Phone number
  • phone_country_code - Country code for phone (e.g., '+91')
  • secondaryEmail - Secondary email address

Location Information

  • country - Country name
  • country_code - ISO country code
  • countryMetadata - Additional country metadata (flag, emoji, etc.)

Preferences

  • defaultLanguage - User's default language preference

Additional Information

  • addresses - Work and home addresses
  • about - Personal interests (introduction, sports, music, books)
  • workAndEducationDetails - Work experience and education history

Example Usage

const auth = await getAuth();
if (auth?.currentUser) {
  const user = auth.currentUser;
  
  // Personal info
  console.log('Name:', user.fullName);
  console.log('DOB:', user.DOB);
  console.log('Gender:', user.gender);
  console.log('Phone:', user.phone_country_code, user.phone);
  
  // Location
  console.log('Country:', user.country);
  
  // Preferences
  console.log('Language:', user.defaultLanguage);
}

TypeScript Support

The SDK is written in TypeScript and includes type definitions. All exported functions and interfaces are fully typed.

Browser Compatibility

The SDK requires:

  • Modern browsers with ES6+ support
  • crypto-js and jwt-decode libraries
  • Access to window, document, and fetch APIs

Security Notes

  • The secret key used for encryption/decryption is embedded in the SDK. For production use, ensure your backend uses the same secret key.
  • Tokens are stored in cookies with appropriate expiration times.
  • Always use HTTPS in production to protect tokens in transit.
  • The SDK now validates sessions server-side for enhanced security.
  • Service access is checked at authentication time to prevent unauthorized access.
  • Session validation includes optional IP and device fingerprinting checks (configurable on backend).

License

MIT