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

@miranlabs/react-auth-sdk

v1.1.1

Published

ID Miran SDK for React Single Page Applications using Authorization Code Grant Flow with PKCE

Readme

Miran Auth SDK for React

! ⚠️  AVISO IMPORTANTE
! 
! Este SDK é um Authorization Server desenvolvido exclusivamente para MIRAN LABS.
! Integrações e autenticações para terceiros estão sujeitas à análise e 
! aprovação interna da equipe MIRAN LABS.
! 
! Para solicitar acesso ou integração, entre em contato com nossa equipe em [email protected].

A React SDK for implementing authentication using Authorization Code Grant Flow with PKCE (Proof Key for Code Exchange)

Features

  • 🏢 MIRAN LABS Integration - Built exclusively for MIRAN LABS authentication servers
  • 🔐 Secure Authentication - OAuth 2.0 Authorization Code Grant with PKCE
  • React Hooks - Easy-to-use hooks for authentication state management
  • 🎯 TypeScript Support - Full TypeScript definitions included
  • 🛡️ Protected Routes - Built-in component for protecting routes
  • 🔄 Token Management - Automatic token refresh and secure cookie storage
  • 📱 Popup & Redirect - Support for both popup and redirect login flows
  • 🔒 Built-in Security - Hardcoded domains with automatic fallback and validation
  • 🧪 Testing Ready - Jest configuration and test utilities included

Installation

npm install @miranlabs/react-auth-sdk
# ou
yarn add @miranlabs/react-auth-sdk

Quick Start

1. Wrap your app with AuthProvider

import React from 'react';
import { AuthProvider } from '@miranlabs/react-auth-sdk';

function App() {
  return (
    <AuthProvider
      clientId="seu-client-id"
      redirectUri={window.location.origin + '/callback'}
      scope="openid profile email"
      useRefreshTokens={true}
      cacheLocation="cookies"
    >
      <YourApp />
    </AuthProvider>
  );
}

2. Use the authentication hook

import React from 'react';
import { useAuth } from '@miranlabs/react-auth-sdk';

function LoginButton() {
  const { login, loginWithPopup, isLoading } = useAuth();

  return (
    <div>
      <button onClick={login} disabled={isLoading}>
        Login (Redirect)
      </button>
      <button onClick={loginWithPopup} disabled={isLoading}>
        Login (Popup)
      </button>
    </div>
  );
}

3. Display user profile

import React from 'react';
import { useAuth } from '@miranlabs/react-auth-sdk';

function Profile() {
  const { user, logout, isAuthenticated } = useAuth();

  if (!isAuthenticated) {
    return <div>Please log in</div>;
  }

  return (
    <div>
      <img src={user?.picture} alt="Profile" />
      <h2>Welcome, {user?.name}!</h2>
      <p>Email: {user?.email}</p>
      <button onClick={logout}>Logout</button>
    </div>
  );
}

4. Protect routes

import React from 'react';
import { ProtectedRoute } from '@miranlabs/react-auth-sdk';

function App() {
  return (
    <ProtectedRoute>
      <Dashboard />
    </ProtectedRoute>
  );
}

API Reference

AuthProvider Props

| Prop | Type | Required | Description | |------|------|----------|-------------| | clientId | string | ✅ | Your OAuth2 client ID | | redirectUri | string | ✅ | The callback URL for authentication | | scope | string | ❌ | OAuth2 scopes (default: "openid profile email") | | audience | string | ❌ | API identifier for the access token | | useRefreshTokens | boolean | ❌ | Enable refresh token rotation (default: false) | | cacheLocation | 'memory' \\| 'cookies' | ❌ | Token storage location (default: 'cookies') |

useAuth Hook

The useAuth hook returns an object with the following properties:

interface AuthContextType {
  user: User | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  login: () => Promise<void>;
  loginWithPopup: () => Promise<void>;
  logout: () => void;
  getToken: () => Promise<string | null>;
  handleRedirectCallback: () => Promise<void>;
  handleRefreshToken: () => Promise<void>;
}

User Object

interface User {
  id: string;
  email: string;
  name: string;
  picture?: string;
  email_verified: boolean;
  sub: string;
  iat: number;
  exp: number;
}

Components

AuthCallback

Handles the authentication callback after redirect:

import { AuthCallback } from '@miranlabs/react-auth-sdk';

function CallbackPage() {
  return (
    <AuthCallback 
      onSuccess={() => window.location.href = '/dashboard'}
      onError={(error) => console.error(error)}
      loadingComponent={<div>Completing authentication...</div>}
    />
  );
}

ProtectedRoute

Protects components that require authentication:

import { ProtectedRoute } from '@miranlabs/react-auth-sdk';

function App() {
  return (
    <ProtectedRoute 
      fallback={<div>Please log in</div>}
      onUnauthorized={() => console.log('User not authenticated')}
    >
      <SecureContent />
    </ProtectedRoute>
  );
}

AuthService Methods

The SDK also provides direct access to the AuthService class for advanced use cases:

import { AuthService } from '@miranlabs/react-auth-sdk';

const authService = new AuthService({
  clientId: 'your-client-id',
  redirectUri: 'http://localhost:3000/callback',
});

// Get user information from the OAuth2 userinfo endpoint
const user = await authService.getUserInfo(accessToken);

// Validate if a token is still valid
const isValid = await authService.validateToken(accessToken);

Additional Hooks

useAuthToken

Get the current access token:

import { useAuthToken } from '@miranlabs/react-auth-sdk';

function ApiComponent() {
  const { token, isLoading, error, refreshToken } = useAuthToken();
  
  // Use token for API calls
}

useAuthenticatedFetch

Automatically add auth headers to fetch requests:

import { useAuthenticatedFetch } from '@miranlabs/react-auth-sdk';

function DataComponent() {
  const authenticatedFetch = useAuthenticatedFetch();
  
  const fetchData = async () => {
    const response = await authenticatedFetch('/api/data');
    return response.json();
  };
}

Examples

Check the examples/ directory for complete implementation examples:

  • basic-usage/ - Simple authentication flow
  • with-router/ - Integration with React Router

Development

# Install dependencies
npm install

# Run tests
npm test

# Build the library
npm run build

# Lint code
npm run lint

# Type checking
npm run typecheck

Security Considerations

  • Fixed MIRAN Authentication - Uses hardcoded MIRAN LABS authentication servers with automatic fallback
  • Secure Cookie Storage - Tokens stored using secure cookies with HttpOnly, Secure, and SameSite flags
  • PKCE Implementation - Uses crypto-secure random bytes generation for PKCE code challenge/verifier
  • Domain Security Validation - Built-in validation of MIRAN authentication domains and security headers
  • No Client Secret Required - Follows OAuth2 best practices for public clients (SPAs)
  • Redirect URI Validation - Automatic validation of redirect URIs against security policies
  • Automatic Fallback - Built-in fallback to backup authentication servers if primary fails
  • XSS/CSRF Protection - Secure cookie configuration prevents common web vulnerabilities
  • Enhanced Error Handling - Detailed OAuth2 error responses without exposing sensitive data

Changelog

v1.0.0

  • 🏢 MIRAN LABS Integration - Built exclusively for MIRAN LABS authentication servers
  • 🔐 Secure Authentication - OAuth 2.0 Authorization Code Grant with PKCE
  • 🍪 Secure Cookie Storage - Tokens stored using secure cookies with proper flags
  • 🛡️ Enhanced Security Validation - Comprehensive domain and redirect URI validation
  • 🔒 No Client Secret Required - Follows OAuth2 best practices for public clients (SPAs)
  • 🔄 Automatic Domain Fallback - Built-in fallback to backup authentication servers
  • React Hooks - Easy-to-use hooks for authentication state management
  • 🎯 TypeScript Support - Full TypeScript definitions included
  • 📱 Popup & Redirect - Support for both popup and redirect login flows

License

MIT

Contributing

Contributions are welcome! Please read the contributing guidelines before submitting PRs.

Support

If you encounter any issues, please file them in the GitHub issue tracker.