@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 startUsage
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 authenticatedactiveSubscription: boolean- Whether user has active subscriptionemail: string- User's primary email addressfriendlyName: string- User's display nameversion: string- Library version
Methods
login()- Authenticate user via browser OAuthlogout()- Sign out and clear authentication datadestroy()- 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 lintArchitecture
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
