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

streamline-cross-app-sdk

v1.0.0

Published

Cross-app authentication and credit management SDK for Stream-line AI

Readme

Cross-App Authentication & Credit SDK

A comprehensive TypeScript/JavaScript SDK for integrating cross-app authentication and credit management with the Stream-line AI Automate platform.

🚀 Features

  • Seamless Cross-App Authentication: JWT-based authentication that works across different domains
  • Credit System Integration: Direct credit purchase and consumption bypassing the dashboard
  • Permission Management: App-specific permissions and access control
  • Automatic Token Refresh: Handles session management automatically
  • React Components: Pre-built UI components for easy integration
  • TypeScript Support: Full type safety and IntelliSense
  • Event System: Real-time authentication state updates

📦 Installation

npm install @streamline/cross-app-sdk
# or
yarn add @streamline/cross-app-sdk

🎯 Quick Start

Basic Authentication

import { createCrossAppSDK } from '@streamline/cross-app-sdk';

const sdk = createCrossAppSDK({
  appId: 'my-video-app',
  domain: 'stream-lineai.com',
  debug: true
});

// Check if user is authenticated
if (!sdk.isAuthenticated()) {
  // Login user
  const user = await sdk.login({
    email: '[email protected]',
    password: 'password123'
  });
}

// Get current user
const currentUser = sdk.getCurrentUser();
console.log('Welcome,', currentUser.name);

Credit Management

// Check credit balance
const balance = await sdk.credits.getCreditBalance(10);

if (balance.can_consume) {
  // Consume credits for service
  await sdk.credits.consumeCredits(10, 'video-generation');
} else {
  // Purchase more credits
  const purchase = await sdk.credits.purchaseCredits({
    credits: 50,
    returnUrl: 'https://myapp.com/credits-purchased'
  });
  
  // Redirect to Stripe checkout
  window.location.href = purchase.checkout_url;
}

🏗️ Architecture

Core Classes

  • CrossAppAuthSDK: Handles authentication, session management, and permissions
  • CreditSDK: Manages credit operations, purchases, and consumption
  • createCrossAppSDK: Factory function that creates both SDKs with shared configuration

Data Flow

User Action → SDK Method → API Call → Backend Validation → Response → State Update → Event Emission

📚 API Reference

CrossAppAuthSDK

Constructor

new CrossAppAuthSDK(config: SDKConfig)

Configuration Options:

  • appId: Unique identifier for your application
  • domain: Stream-line AI domain (e.g., 'stream-lineai.com')
  • apiBase: Optional custom API base URL
  • debug: Enable debug logging
  • redirectUrl: Optional redirect URL for authentication flows

Methods

Authentication
  • login(options: LoginOptions): Promise<User> - Authenticate user
  • logout(): Promise<void> - Logout current user
  • isAuthenticated(): boolean - Check authentication status
  • getCurrentUser(): User | null - Get current user info
Session Management
  • refreshToken(): Promise<string> - Refresh authentication token
  • validateToken(): Promise<TokenValidationResult> - Validate current token
  • getSessionToken(): string | null - Get current session token
  • isSessionExpiringSoon(thresholdMinutes?: number): boolean - Check if session expires soon
Permissions
  • hasPermission(permission: string): boolean - Check user permission
  • onAuthChange(callback: AuthEventListener): () => void - Listen for auth events

CreditSDK

Methods

Credit Operations
  • getCreditBalance(requiredCredits?: number): Promise<CreditBalance> - Get current balance
  • hasSufficientCredits(requiredCredits: number): Promise<boolean> - Check if user has enough credits
  • consumeCredits(credits: number, service: string, description?: string): Promise<CreditConsumption> - Use credits
  • purchaseCredits(request: CreditPurchaseRequest): Promise<CreditPurchase> - Buy credits
Package Management
  • getCreditPackages(): Promise<CreditPackage[]> - Get available packages
  • getUserSubscriptions(): Promise<UserSubscription[]> - Get user subscriptions
  • getRecommendedPackage(targetCredits: number): Promise<CreditPackage | null> - Get best package
Utilities
  • validateCreditRequirements(requiredCredits: number, service: string): Promise<CreditValidation> - Validate credit needs
  • quickCreditCheck(requiredCredits: number): Promise<QuickCreditCheckResult> - Quick credit validation

🎨 React Components

CrossAppLogin

A pre-built login component that can be embedded in your application.

import { CrossAppLogin } from '@streamline/cross-app-sdk/components';

function MyApp() {
  const [showLogin, setShowLogin] = useState(false);
  const [user, setUser] = useState(null);

  return (
    <div>
      {!user ? (
        <button onClick={() => setShowLogin(true)}>
          Sign In
        </button>
      ) : (
        <div>Welcome, {user.name}!</div>
      )}

      {showLogin && (
        <CrossAppLogin
          sdk={sdk.auth}
          onLoginSuccess={(user) => {
            setUser(user);
            setShowLogin(false);
          }}
          onClose={() => setShowLogin(false)}
        />
      )}
    </div>
  );
}

🔐 Security Features

  • JWT Tokens: Secure, time-limited authentication tokens
  • App Validation: Domain and app ID validation for all requests
  • Permission Scoping: Granular access control per application
  • Automatic Token Refresh: Prevents session expiration
  • Secure Storage: LocalStorage with automatic cleanup

🌐 Cross-Domain Support

The SDK automatically handles:

  • Cross-domain authentication
  • Cookie sharing across subdomains
  • CORS configuration
  • Domain validation

📱 Mobile Support

  • Responsive design for mobile devices
  • Touch-friendly interface
  • Progressive Web App compatible
  • Offline session management

🧪 Testing

import { CrossAppAuthSDK } from '@streamline/cross-app-sdk';

// Mock the SDK for testing
const mockSDK = {
  isAuthenticated: jest.fn().mockReturnValue(true),
  getCurrentUser: jest.fn().mockReturnValue({ id: 1, email: '[email protected]' }),
  login: jest.fn().mockResolvedValue({ id: 1, email: '[email protected]' })
};

// Test your components
test('shows user info when authenticated', () => {
  render(<UserProfile sdk={mockSDK} />);
  expect(screen.getByText('[email protected]')).toBeInTheDocument();
});

🚨 Error Handling

The SDK provides comprehensive error handling:

try {
  await sdk.login({ email: '[email protected]', password: 'wrong' });
} catch (error) {
  if (error instanceof CrossAppAuthError) {
    console.error('Auth error:', error.code, error.message);
    // Handle specific error codes
    switch (error.code) {
      case 'AUTH_FAILED':
        // Show login error
        break;
      case 'INSUFFICIENT_PERMISSIONS':
        // Show permission error
        break;
    }
  }
}

📊 Event System

Listen for authentication state changes:

const unsubscribe = sdk.auth.onAuthChange((event) => {
  switch (event.type) {
    case 'AUTH_SUCCESS':
      console.log('User logged in:', event.data.user);
      break;
    case 'AUTH_LOGOUT':
      console.log('User logged out');
      break;
    case 'TOKEN_REFRESH':
      console.log('Token refreshed');
      break;
  }
});

// Clean up listener
unsubscribe();

🔧 Configuration

Environment Variables

# Required
NEXT_PUBLIC_STREAMLINE_DOMAIN=stream-lineai.com
NEXT_PUBLIC_APP_ID=my-video-app

# Optional
NEXT_PUBLIC_API_BASE=https://api.stream-lineai.com
NEXT_PUBLIC_DEBUG=true

SDK Configuration

const sdkConfig = {
  appId: process.env.NEXT_PUBLIC_APP_ID!,
  domain: process.env.NEXT_PUBLIC_STREAMLINE_DOMAIN!,
  apiBase: process.env.NEXT_PUBLIC_API_BASE,
  debug: process.env.NODE_ENV === 'development',
  redirectUrl: 'https://myapp.com/auth-callback'
};

📈 Performance

  • Lazy Loading: Components load only when needed
  • Efficient State Management: Minimal re-renders
  • Automatic Cleanup: Memory leak prevention
  • Optimized API Calls: Minimal network requests

🔄 Migration Guide

From v0.x to v1.0

// Old way
import { AuthSDK } from '@streamline/cross-app-sdk';

// New way
import { createCrossAppSDK } from '@streamline/cross-app-sdk';

const sdk = createCrossAppSDK(config);

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

📄 License

MIT License - see LICENSE file for details

🆘 Support

🗺️ Roadmap

  • [ ] OAuth 2.0 support
  • [ ] Multi-factor authentication
  • [ ] Advanced analytics
  • [ ] Webhook support
  • [ ] Rate limiting
  • [ ] Offline mode

Built with ❤️ by Stream-line AI