npm package: @miranlabs/react-auth-sdk
Description: ID Miran SDK for React Single Page Applications using Authorization Code Grant Flow with PKCE
Author: Mirae Team
Latest version: 1.1.1

# Miran Auth SDK for React

```diff
! ⚠️  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 suporte@miranlabs.com.br.
```

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

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

## Quick Start

### 1. Wrap your app with AuthProvider

```tsx
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

```tsx
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

```tsx
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

```tsx
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:

```tsx
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

```tsx
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:

```tsx
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:

```tsx
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:

```tsx
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:

```tsx
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:

```tsx
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

```bash
# 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](https://github.com/miran/sdk-auth-react/issues).