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

@mycuppa/auth

v0.0.0

Published

Authentication utilities and helpers for Cuppa framework

Downloads

14

Readme

@mycuppa/auth

Authentication utilities and helpers for Cuppa framework.

Features

  • Login/logout functionality
  • Token management (access + refresh tokens)
  • Token refresh logic with auto-refresh support
  • User session persistence (localStorage/sessionStorage)
  • Authentication state observers
  • Protected route helpers
  • Role-based access control (RBAC) utilities
  • React hooks for easy integration
  • TypeScript support with full type definitions

Installation

pnpm add @mycuppa/auth

Usage

Basic Setup

import { createAuthManager, useAuth } from '@mycuppa/auth'

// Create auth manager instance
const authManager = createAuthManager({
  storageKey: 'my_app_auth',
  storageType: 'localStorage',
  autoRefresh: true,
  refreshThreshold: 300000, // 5 minutes
  onTokenRefresh: async (tokens) => {
    // Call your API to refresh tokens
    const response = await fetch('/api/auth/refresh', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ refreshToken: tokens.refreshToken }),
    })
    return response.json()
  },
  onLogout: async () => {
    // Optional cleanup on logout
    console.log('User logged out')
  },
  onError: (error) => {
    // Optional error handling
    console.error('Auth error:', error)
  },
})

React Hook Usage

import { useAuth } from '@mycuppa/auth'

function MyComponent() {
  const {
    user,
    isAuthenticated,
    isLoading,
    login,
    logout,
    hasRole,
    hasPermission,
  } = useAuth(authManager)

  const handleLogin = async () => {
    const user = { id: '1', email: '[email protected]', roles: ['user'] }
    const tokens = { accessToken: 'xxx', refreshToken: 'yyy' }
    await login(user, tokens)
  }

  if (isLoading) return <div>Loading...</div>

  if (!isAuthenticated) {
    return <button onClick={handleLogin}>Login</button>
  }

  return (
    <div>
      <p>Welcome, {user?.email}</p>
      <button onClick={logout}>Logout</button>
      {hasRole('admin') && <AdminPanel />}
    </div>
  )
}

Role-Based Access Control

// Check single role
if (authManager.hasRole('admin')) {
  // User is an admin
}

// Check any of multiple roles
if (authManager.hasAnyRole(['admin', 'moderator'])) {
  // User has at least one of these roles
}

// Check all roles
if (authManager.hasAllRoles(['user', 'verified'])) {
  // User has all these roles
}

// Check permissions
if (authManager.hasPermission('write')) {
  // User has write permission
}

if (authManager.hasAllPermissions(['read', 'write', 'delete'])) {
  // User has all these permissions
}

Protected Routes

// Check if user can access a route
const canAccess = authManager.canAccessRoute({
  requireAuth: true,
  requiredRoles: ['admin'],
  requiredPermissions: ['read'],
})

if (!canAccess) {
  // Redirect to login or show error
}

Direct Auth Manager Usage (without React)

import { AuthManager } from '@mycuppa/auth'

const authManager = new AuthManager({
  storageType: 'sessionStorage',
})

// Subscribe to auth state changes
const unsubscribe = authManager.subscribe((state) => {
  console.log('Auth state changed:', state)
})

// Login
await authManager.login(user, tokens)

// Get current state
const state = authManager.getState()

// Get access token
const token = authManager.getAccessToken()

// Update user
authManager.updateUser({ name: 'New Name' })

// Logout
await authManager.logout()

// Cleanup
unsubscribe()
authManager.destroy()

API Reference

AuthManager

Constructor Options

  • storageKey?: string - Storage key for tokens (default: 'cuppa_auth_tokens')
  • storageType?: 'localStorage' | 'sessionStorage' - Storage type (default: 'localStorage')
  • autoRefresh?: boolean - Enable automatic token refresh (default: false)
  • refreshThreshold?: number - Time in ms before token refresh (default: 300000)
  • onTokenRefresh?: (tokens: TokenPair) => Promise<TokenPair> - Token refresh handler
  • onLogout?: () => void | Promise<void> - Logout callback
  • onError?: (error: Error) => void - Error handler

Methods

  • login(user: User, tokens: TokenPair): Promise<void> - Login user
  • logout(): Promise<void> - Logout user
  • refreshTokens(): Promise<TokenPair | null> - Refresh access tokens
  • getTokens(): TokenPair | null - Get current tokens
  • getAccessToken(): string | null - Get access token
  • updateUser(user: Partial<User>): void - Update user data
  • getState(): AuthState - Get current auth state
  • subscribe(observer: AuthStateObserver): () => void - Subscribe to state changes
  • hasRole(role: string): boolean - Check if user has role
  • hasAnyRole(roles: string[]): boolean - Check if user has any role
  • hasAllRoles(roles: string[]): boolean - Check if user has all roles
  • hasPermission(permission: string): boolean - Check if user has permission
  • hasAnyPermission(permissions: string[]): boolean - Check if user has any permission
  • hasAllPermissions(permissions: string[]): boolean - Check if user has all permissions
  • canAccessRoute(config: ProtectedRouteConfig): boolean - Check route access
  • destroy(): void - Clean up resources

TypeScript

The package is written in TypeScript and includes full type definitions.

import type {
  User,
  TokenPair,
  AuthState,
  AuthConfig,
  ProtectedRouteConfig,
} from '@mycuppa/auth'

License

MIT