streamline-cross-app-sdk
v1.0.0
Published
Cross-app authentication and credit management SDK for Stream-line AI
Maintainers
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 permissionsCreditSDK: Manages credit operations, purchases, and consumptioncreateCrossAppSDK: 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 applicationdomain: Stream-line AI domain (e.g., 'stream-lineai.com')apiBase: Optional custom API base URLdebug: Enable debug loggingredirectUrl: Optional redirect URL for authentication flows
Methods
Authentication
login(options: LoginOptions): Promise<User>- Authenticate userlogout(): Promise<void>- Logout current userisAuthenticated(): boolean- Check authentication statusgetCurrentUser(): User | null- Get current user info
Session Management
refreshToken(): Promise<string>- Refresh authentication tokenvalidateToken(): Promise<TokenValidationResult>- Validate current tokengetSessionToken(): string | null- Get current session tokenisSessionExpiringSoon(thresholdMinutes?: number): boolean- Check if session expires soon
Permissions
hasPermission(permission: string): boolean- Check user permissiononAuthChange(callback: AuthEventListener): () => void- Listen for auth events
CreditSDK
Methods
Credit Operations
getCreditBalance(requiredCredits?: number): Promise<CreditBalance>- Get current balancehasSufficientCredits(requiredCredits: number): Promise<boolean>- Check if user has enough creditsconsumeCredits(credits: number, service: string, description?: string): Promise<CreditConsumption>- Use creditspurchaseCredits(request: CreditPurchaseRequest): Promise<CreditPurchase>- Buy credits
Package Management
getCreditPackages(): Promise<CreditPackage[]>- Get available packagesgetUserSubscriptions(): Promise<UserSubscription[]>- Get user subscriptionsgetRecommendedPackage(targetCredits: number): Promise<CreditPackage | null>- Get best package
Utilities
validateCreditRequirements(requiredCredits: number, service: string): Promise<CreditValidation>- Validate credit needsquickCreditCheck(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=trueSDK 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
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
📄 License
MIT License - see LICENSE file for details
🆘 Support
- Documentation: docs.stream-lineai.com
- Issues: GitHub Issues
- Email: [email protected]
🗺️ Roadmap
- [ ] OAuth 2.0 support
- [ ] Multi-factor authentication
- [ ] Advanced analytics
- [ ] Webhook support
- [ ] Rate limiting
- [ ] Offline mode
Built with ❤️ by Stream-line AI
