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 🙏

© 2024 – Pkg Stats / Ryan Hefner

reclaim-identity-js

v1.2.1

Published

Reclaim Identity is a JavaScript SDK that provides seamless integration with Reclaim Protocol's authentication system. The SDK manages OAuth 2.0 flows, popup windows, token management, and user session handling.

Downloads

543

Readme

Reclaim Identity JS SDK

Reclaim Identity is a JavaScript SDK that provides seamless integration with Reclaim Protocol's authentication system. The SDK manages OAuth 2.0 flows, popup windows, token management, and user session handling.

Features

  • Simple OAuth 2.0 authentication flow
  • Popup-based authentication
  • Secure token management with httpOnly cookies
  • Event-based state management
  • CSRF protection
  • Session handling
  • AMD module support
  • Singleton pattern implementation

Installation

NPM

npm install reclaim-identity-js

CDN

Include directly via CDN:

<script src="https://unpkg.com/reclaim-identity-js@latest"></script>

Usage

Initialization

const clientId = 'your-client-id';
const clientSecret = 'your-client-secret'
const redirectUri = 'your-redirect-uri';
const reclaimAuth = getReclaimAuth(clientId, clientSecret,redirectUri);

Authentication

// Sign In
reclaimAuth.signIn()
  .then(user => {
    console.log('Signed in:', user);
  })
  .catch(error => {
    if (error.message.includes('popup')) {
      console.error('Popup was blocked');
    } else {
      console.error('Authentication error:', error);
    }
  });

// Sign Out
reclaimAuth.signOut()
  .then(() => {
    console.log('Signed out successfully');
  })
  .catch(error => {
    console.error('Sign out error:', error);
  });

// Get Current User
const user = reclaimAuth.getCurrentUser();

// Listen for Auth State Changes
const unsubscribe = reclaimAuth.onAuthStateChanged(user => {
  if (user) {
    console.log('User state changed:', user);
  } else {
    console.log('User signed out');
  }
});

// Clean up listener when done
unsubscribe();

Complete Browser Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reclaim Identity Demo</title>
</head>
<body>
    <div>
        <button id="signInBtn">Sign In</button>
        <button id="signOutBtn">Sign Out</button>
        <div id="userInfo"></div>
    </div>

    <script src="https://unpkg.com/reclaim-identity-js@latest"></script>
    <script>
        const clientId = 'your-client-id';
        const clientSecret = 'your-client-secret'
        const redirectUri = 'your-redirect-uri';
        const reclaimAuth = getReclaimAuth(clientId, clientSecret,redirectUri);

        // Handle Auth State Changes
        auth.onAuthStateChanged(user => {
            const userInfo = document.getElementById('userInfo');
            if (user) {
                userInfo.textContent = JSON.stringify(user, null, 2);
            } else {
                userInfo.textContent = 'No user signed in';
            }
        });

        // Sign In Handler
        document.getElementById('signInBtn').addEventListener('click', async () => {
            try {
                const user = await auth.signIn();
                console.log('Signed in successfully:', user);
            } catch (error) {
                console.error('Sign in failed:', error);
            }
        });

        // Sign Out Handler
        document.getElementById('signOutBtn').addEventListener('click', async () => {
            try {
                await auth.signOut();
                console.log('Signed out successfully');
            } catch (error) {
                console.error('Sign out failed:', error);
            }
        });
    </script>
</body>
</html>

API Reference

getReclaimAuth(clientId: string, clientSecret: string, redirectUri: string)

Returns a singleton instance of the ReclaimAuth class. Both parameters are required for initial setup.

auth.signIn(): Promise

Initiates the authentication flow by opening a popup window. Returns a promise that resolves with the user data.

auth.signOut(): Promise

Signs out the current user and clears authentication state.

auth.getCurrentUser(): User | null

Returns the currently authenticated user or null if not authenticated.

auth.onAuthStateChanged(callback: (user: User | null) => void): () => void

Subscribes to authentication state changes. Returns an unsubscribe function.

Configuration

The SDK uses the following defaults:

{
    apiBaseUrl: 'https://identity.reclaimprotocol.org',
    env: 'production',
    popupWidth: 600,
    popupHeight: 600
}

Security Features

  • CSRF protection using state parameter
  • Secure cookie handling
  • Origin validation for popup messages
  • Cross-window communication security
  • Credentials included in API requests

Browser Compatibility

The SDK requires browsers with support for:

  • Web Crypto API for secure random values
  • Fetch API for network requests
  • PostMessage API for popup communication
  • ES6+ features (can be polyfilled)
  • Cookies

Error Handling

Common error scenarios:

try {
    await auth.signIn();
} catch (error) {
    switch (true) {
        case error.message.includes('popup'):
            // Handle popup blocked
            break;
        case error.message.includes('code'):
            // Handle authorization code error
            break;
        case error.message.includes('token'):
            // Handle token exchange error
            break;
        default:
            // Handle other errors
    }
}

Advanced Usage

Custom Event Handling

class AuthenticationManager {
    constructor() {
        this.auth = getReclaimAuth(clientId, clientSecret, redirectUri);
        this.setupAuthListeners();
    }

    setupAuthListeners() {
        this.unsubscribe = this.auth.onAuthStateChanged(user => {
            if (user) {
                this.handleSignedIn(user);
            } else {
                this.handleSignedOut();
            }
        });
    }

    async handleSignedIn(user) {
        // Handle successful sign in
    }

    async handleSignedOut() {
        // Handle sign out
    }

    cleanup() {
        // Clean up listeners
        this.unsubscribe();
    }
}

Best Practices

  1. Error Handling

    • Always implement proper error handling for authentication operations
    • Handle popup blocking scenarios
    • Implement proper cleanup for event listeners
  2. Security

    • Use HTTPS in production
    • Store client credentials securely
    • Implement proper CORS settings
    • Validate authentication state consistently
  3. User Experience

    • Handle loading states during authentication
    • Provide clear feedback for authentication errors
    • Implement proper session management
    • Handle page refreshes gracefully

Troubleshooting

Common issues and solutions:

  1. Popup Blocked

    • Ensure signIn is called in response to user action
    • Check browser popup settings
  2. Authentication Failures

    • Verify clientId and redirectUri
    • Check network requests
    • Verify cookie settings
  3. Security Errors

    • Check origin settings
    • Verify CORS configuration
    • Validate SSL certificates

Support

For issues, questions, or feature requests:

License

MIT License - see LICENSE for details

Contributing

Contributions are welcome! Please read our contributing guidelines for details.