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

auth-node-test

v1.0.7

Published

DAuth SDK - OAuth 2.0 with PKCE and Wallet Authentication

Readme

DAuth SDK

A modern JavaScript SDK for DAuth OAuth 2.0 with PKCE and Wallet Authentication, similar to Auth0 and Google Auth SDKs.

Installation

npm install dauth
# or
yarn add dauth

Quick Start

Basic Usage (Vanilla JavaScript)

import { DAuth } from 'dauth';

// Initialize the SDK
const dauth = new DAuth({
  clientId: 'your_client_id',
  redirectUri: 'http://localhost:3000/callback',
});

// Login
await dauth.login();

// Handle callback (in your callback route)
const tokens = await dauth.handleCallback();

// Check authentication
if (dauth.isAuthenticated()) {
  const tokens = dauth.getTokens();
  const user = await dauth.getUserInfo();
}

// Logout
dauth.logout({ returnTo: '/' });

React Usage with Hooks

import { useDAuth } from 'dauth';

function App() {
  const { 
    isAuthenticated, 
    isLoading, 
    user, 
    login, 
    logout 
  } = useDAuth({
    clientId: 'your_client_id',
    redirectUri: 'http://localhost:3000/callback',
  });

  if (isLoading) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      {isAuthenticated ? (
        <div>
          <p>Welcome, {user?.name}!</p>
          <button onClick={() => logout()}>Logout</button>
        </div>
      ) : (
        <button onClick={() => login()}>Login</button>
      )}
    </div>
  );
}

Protected Routes

import { useDAuth, useRequireAuth } from 'dauth';

function Dashboard() {
  const { isAuthenticated } = useDAuth({
    clientId: 'your_client_id',
    redirectUri: 'http://localhost:3000/callback'
  });

  // Redirect to login if not authenticated
  useRequireAuth({ 
    isAuthenticated, 
    redirectTo: '/login' 
  });

  return <div>Protected Dashboard</div>;
}

Callback Handler

import { useDAuth } from 'dauth';
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

function Callback() {
  const { handleCallback, isLoading } = useDAuth({
    clientId: 'your_client_id',
    redirectUri: 'http://localhost:3000/callback'
  });
  const navigate = useNavigate();

  useEffect(() => {
    const processCallback = async () => {
      try {
        await handleCallback();
        navigate('/dashboard');
      } catch (error) {
        console.error('Callback error:', error);
        navigate('/login');
      }
    };

    processCallback();
  }, [handleCallback, navigate]);

  return <div>Completing sign-in...</div>;
}

API Reference

DAuth Class

Constructor Options

interface DAuthConfig {
  clientId: string;           // Required: Your client ID
  clientSecret?: string;      // Optional: Client secret (for confidential clients)
  redirectUri: string;        // Required: Callback URL
  apiUrl?: string;            // Optional: API base URL
  authUrl?: string;           // Optional: Authorization server URL
  scope?: string;             // Optional: OAuth scope (default: 'openid profile email')
  responseType?: string;      // Optional: Response type (default: 'code')
  tokenStorageKey?: string;   // Optional: localStorage key for tokens (default: 'dauth_tokens')
  pkceStorageKey?: string;    // Optional: localStorage key for PKCE verifier
  stateStorageKey?: string;   // Optional: localStorage key for state
}

Methods

login(options?: { state?: string, loginUrl?: string }): Promise<void>

Initiates the login flow by redirecting to the authorization server.

await dauth.login();
handleCallback(options?: { code?: string, state?: string }): Promise<Object>

Handles the OAuth callback and exchanges the authorization code for tokens.

const tokens = await dauth.handleCallback();
logout(options?: { returnTo?: string }): void

Clears stored tokens and optionally redirects.

dauth.logout({ returnTo: '/' });
isAuthenticated(): boolean

Checks if the user is currently authenticated.

if (dauth.isAuthenticated()) {
  // User is logged in
}
getTokens(): Object | null

Retrieves stored tokens.

const tokens = dauth.getTokens();
// { access_token, id_token, token_type, expires_in, expires_at }
getAuthHeader(): Object

Returns authorization header for API requests.

const headers = dauth.getAuthHeader();
// { Authorization: 'Bearer <token>' }
getUserInfo(): Promise<Object>

Fetches user information using the access token.

const user = await dauth.getUserInfo();
refreshToken(): Promise<Object>

Refreshes the access token using the refresh token.

const newTokens = await dauth.refreshToken();
clearTokens(): void

Clears all stored tokens and PKCE data.

dauth.clearTokens();

Wallet Methods

getWallet(): Promise<Object | null>

Gets the connected wallet account.

const wallet = await dauth.getWallet();
getSignature(message: string): Promise<string | null>

Requests signature from wallet.

const signature = await dauth.getSignature('Sign this message');
getUserAccounts(walletAddress: string): Promise<Array>

Gets user accounts associated with a wallet address.

const accounts = await dauth.getUserAccounts(walletAddress);

React Hooks

useDAuth(config: DAuthConfig)

Returns authentication state and methods.

interface UseDAuthReturn {
  dauth: DAuth;                    // DAuth instance
  isAuthenticated: boolean;         // Authentication status
  isLoading: boolean;              // Loading state
  user: Object | null;             // User information
  error: Error | null;             // Error state
  login: (options?) => Promise<void>;
  logout: (options?) => void;
  handleCallback: (options?) => Promise<Object>;
  getUserInfo: () => Promise<Object>;
  getTokens: () => Object | null;
  refreshToken: () => Promise<Object>;
}

useRequireAuth(options: { isAuthenticated: boolean, redirectTo?: string })

Hook to protect routes by redirecting unauthenticated users.

useRequireAuth({ 
  isAuthenticated, 
  redirectTo: '/login' 
});

Advanced Usage

Custom Token Storage

class CustomStorage {
  getItem(key) { /* ... */ }
  setItem(key, value) { /* ... */ }
  removeItem(key) { /* ... */ }
}

// You can override token storage by modifying the DAuth class
// or use the tokenStorageKey option to use a different localStorage key

Error Handling

try {
  await dauth.login();
} catch (error) {
  if (error.message === 'Failed to initiate login') {
    // Handle login error
  }
}

try {
  await dauth.handleCallback();
} catch (error) {
  if (error.message === 'Authorization code not found') {
    // Handle callback error
  }
}

Making Authenticated API Requests

import axios from 'axios';

const dauth = new DAuth({ /* config */ });

async function fetchProtectedData() {
  const headers = dauth.getAuthHeader();
  
  try {
    const response = await axios.get('https://api.example.com/data', {
      headers
    });
    return response.data;
  } catch (error) {
    if (error.response?.status === 401) {
      // Token expired, try refresh
      await dauth.refreshToken();
      // Retry request
      const newHeaders = dauth.getAuthHeader();
      const retryResponse = await axios.get('https://api.example.com/data', {
        headers: newHeaders
      });
      return retryResponse.data;
    }
    throw error;
  }
}

Configuration

Environment Variables

You can use environment variables for configuration:

const dauth = new DAuth({
  clientId: import.meta.env.VITE_DAUTH_CLIENT_ID,
  redirectUri: import.meta.env.VITE_DAUTH_REDIRECT_URI,
  apiUrl: import.meta.env.VITE_DAUTH_API_URL
});

Browser Support

  • Modern browsers with ES6+ support
  • Requires Web Crypto API for PKCE
  • Wallet functionality requires NCOG provider

License

MIT