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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@tonk/tonk-auth

v0.2.2

Published

A secure authentication library for Tonk CLI tools, providing seamless user authentication and subscription management through Clerk integration.

Readme

tonk-auth

A secure authentication library for Tonk CLI tools, providing seamless user authentication and subscription management through Clerk integration.

tonk-auth handles the complete authentication flow for internal Tonk CLI applications, including browser-based OAuth, subscription validation, and automatic token management.

Key Features

  • Browser-Based OAuth: Secure authentication flow using Clerk with automatic browser opening
  • Subscription Management: Real-time subscription status checking and caching
  • Token Caching: Secure local storage of authentication tokens using keytar
  • Automatic Renewal: Background subscription validation with configurable intervals
  • Type-Safe API: Full TypeScript support with comprehensive type definitions
  • Error Handling: Robust error handling with detailed Result types

Quick Start

# Install dependencies
bun install

# Run the interactive test
bun run start

Usage

Basic Authentication

import { TonkAuth } from '@tonk/tonk-auth';

// Initialize the auth client
const auth = await TonkAuth();

// Login user via browser
const loginResult = await auth.login();
if (loginResult.ok) {
  console.log(`Welcome ${auth.friendlyName}!`);
  console.log(`Subscription active: ${auth.activeSubscription}`);
} else {
  console.error('Login failed:', loginResult.error.message);
}

// Check authentication status
if (auth.isSignedIn) {
  console.log(`Logged in as: ${auth.email}`);
}

// Logout when done
await auth.logout();

Advanced Configuration

import { TonkAuth, type TonkAuthOptions } from '@tonk/tonk-auth';

const options: TonkAuthOptions = {
  // Handle subscription expiration
  onSubscriptionDisabled: () => {
    console.log('⚠️ Your subscription has expired!');
    process.exit(1);
  },
  
  // Check subscription every 30 seconds
  checkInterval: 30 * 1000,
  
  // Retry failed requests up to 5 times
  retryAttempts: 5,
  
  // Wait 2 seconds between retries
  retryDelay: 2000
};

const auth = await TonkAuth(options);

// Clean up when your app shuts down
process.on('SIGINT', () => {
  auth.destroy();
  process.exit(0);
});

CLI Integration Example

import { intro, log } from '@clack/prompts';
import { TonkAuth } from '@tonk/tonk-auth';

const runCLI = async () => {
  intro('🔐 My Tonk CLI Tool');
  
  const auth = await TonkAuth({
    onSubscriptionDisabled: () => {
      log.error('Subscription required for this feature');
      process.exit(1);
    }
  });

  // Ensure user is authenticated
  if (!auth.isSignedIn) {
    log.step('Authentication required...');
    const result = await auth.login();
    if (!result.ok) {
      log.error('Authentication failed');
      return;
    }
  }

  // Verify subscription
  if (!auth.activeSubscription) {
    log.warn('Active subscription required');
    return;
  }

  log.success(`Welcome ${auth.friendlyName}! 🎉`);
  
  // Your CLI logic here...
};

runCLI();

API Reference

TonkAuth(options?)

Creates a new TonkAuth client instance.

Parameters:

  • options (optional): Configuration options

Returns: Promise<TonkAuthClient>

TonkAuthClient

Properties

  • isSignedIn: boolean - Whether user is currently authenticated
  • activeSubscription: boolean - Whether user has active subscription
  • email: string - User's primary email address
  • friendlyName: string - User's display name
  • version: string - Library version

Methods

  • login() - Authenticate user via browser OAuth
  • logout() - Sign out and clear authentication data
  • destroy() - Clean up resources and stop background checks

Configuration Options

interface TonkAuthOptions {
  onSubscriptionDisabled?: () => void;    // Called when subscription expires
  checkInterval?: number;                 // Subscription check interval (ms)
  retryAttempts?: number;                // Max retry attempts for failed requests
  retryDelay?: number;                   // Base delay between retries (ms)
}

Development

# Install dependencies
bun install

# Run tests and interactive demo
bun run start

# Build the library
bun run build

# Lint code
bun run lint

Architecture

tonk-auth integrates with:

  • Clerk: For OAuth authentication and user management
  • Keytar: For secure local token storage
  • Jose: For JWT token verification
  • Node.js Crypto: For RSA public key validation

The library handles the complete authentication lifecycle including secure token caching, automatic renewal, and graceful error handling.

License

Simplicity and freedom.

MIT © Tonk