@blackcode_sa/aios-commercial-integration
v1.0.20
Published
Framework-agnostic commercial integration package for AIOS with Firebase Auth, Stripe billing, and LangGraph integration. Works with any JavaScript environment.
Readme
AIOS Commercial Integration
A comprehensive NPM package for integrating Firebase Authentication, Stripe billing, and LangGraph token management into Electron applications. Built with TypeScript and designed for enterprise-grade security and scalability.
🚀 Features
✅ Zero-Configuration User Onboarding
- Automatic profile creation with default preferences upon first sign-in.
- Enables automatic flows for trial credit allocation and billing setup.
- Designed for immediate use, allowing new users to quickly access features.
- Custom claims for role-based access can be configured in your backend.
✅ Complete Authentication System
- Email/Password authentication with verification
- Social logins (Google, Facebook, GitHub)
- Multi-factor authentication (SMS, TOTP)
- Session management with auto-refresh
- Profile management with user preferences
- Platform-agnostic storage with custom adapters
✅ Production-Ready Security
- Input validation with comprehensive Zod schemas
- Error handling with user-friendly messages
- Re-authentication for sensitive operations
- Rate limiting protection
✅ Cross-Platform Storage
- Storage adapter pattern for platform independence
- Built-in adapters for Web, Electron, React Native, Node.js
- Custom storage implementation support
- Automatic fallbacks for unsupported environments
- Node.js persistence for server environments (Electron main, Pipedream, Langgraph servers)
✅ Billing Integration Ready
- Stripe customer management
- Subscription tracking and status monitoring
- Usage-based billing with detailed analytics
- Credit system with atomic transactions
🚀 Overview
AIOS Commercial Integration provides a complete foundation for your 4-week commercial integration plan, combining:
- Firebase Authentication with 2FA/MFA support
- Stripe Billing integration for payments
- LangGraph token usage tracking
- User Management with role-based access
- Security Features with input validation and error handling
📦 Installation
npm install @blackcode_sa/aios-commercial-integrationPeer Dependencies
npm install firebase🏗️ Architecture
The package follows a singleton service pattern with centralized configuration management:
@blackcode_sa/aios-commercial-integration/
├── src/
│ ├── config/ # Configuration management
│ ├── services/ # Business logic services
│ ├── adapters/ # Platform-specific storage adapters
│ ├── types/ # TypeScript definitions
│ ├── validations/ # Input validation schemas
│ ├── errors/ # Error handling system
│ └── index.ts # Main exports⚡ Quick Start
1. Initialize Configuration
import {
initializeAIOS,
createConfig,
} from "@blackcode_sa/aios-commercial-integration";
const config = createConfig(
{
firebase: {
apiKey: "your-api-key",
authDomain: "your-project.firebaseapp.com",
projectId: "your-project-id",
storageBucket: "your-project.appspot.com",
messagingSenderId: "123456789",
appId: "your-app-id",
functionsUrl: "https://your-region-your-project.cloudfunctions.net",
},
stripe: {
publishableKey: "pk_test_...",
},
langraph: {
apiUrl: "https://your-langgraph-api.com",
enableDirectCalls: true,
},
},
"development"
); // or 'staging' | 'production'
// Initialize the system
await initializeAIOS(config);2. Use Authentication Service
import { AuthService } from "@blackcode_sa/aios-commercial-integration";
const authService = AuthService.getInstance();
await authService.initialize();
// Sign up new user
const result = await authService.signUp({
email: "[email protected]",
password: "SecurePass123!",
displayName: "John Doe",
acceptTerms: true,
});
// Sign in existing user
const loginResult = await authService.signIn({
email: "[email protected]",
password: "SecurePass123!",
});
// Social authentication
const googleResult = await authService.signInWithGoogle();3. Configure Platform-Specific Storage
The AuthService supports platform-agnostic authentication persistence through storage adapters with automatic Node.js environment detection:
🆕 Node.js Environments (Automatic)
The AuthService now automatically detects Node.js environments and enables enhanced persistence for:
- Electron main processes
- Pipedream workflows
- Langgraph servers
- Node.js servers and scripts
import {
AuthService,
ElectronMainStorageAdapter,
} from "@blackcode_sa/aios-commercial-integration";
import Store from "electron-store";
// The service automatically detects Node.js environment
const store = new Store({ name: "aios-auth" });
const storageAdapter = new ElectronMainStorageAdapter(store);
const authService = AuthService.getInstance(storageAdapter);
await authService.initialize();
// ✅ Auth context is automatically restored from storage on startup
// ✅ No need to re-authenticate users after app restarts
// ✅ Seamless experience across all Node.js environmentsKey Benefits for Node.js Environments:
- 🔄 Automatic persistence restoration on application startup
- 🚀 Instant authentication state without waiting for Firebase callbacks
- ⚡ Zero-config setup for server-side implementations
- 🛡️ Secure storage with validation and error recovery
Web Browser (Default)
import { AuthService } from "@blackcode_sa/aios-commercial-integration";
// Uses localStorage automatically in browser environments
const authService = AuthService.getInstance();Electron Main Process
import Store from "electron-store";
import {
AuthService,
ElectronMainStorageAdapter,
} from "@blackcode_sa/aios-commercial-integration";
// Set up electron-store
const store = new Store({
name: "aios-auth",
encryptionKey: "your-encryption-key", // Optional encryption
});
// Create storage adapter
const storageAdapter = new ElectronMainStorageAdapter(store);
// Initialize AuthService with Electron storage
const authService = AuthService.getInstance(storageAdapter);
await authService.initialize();
// ✅ Auth state is automatically restored from storage
// ✅ Works seamlessly in Electron main processElectron Renderer Process
import { ipcRenderer } from "electron";
import {
AuthService,
ElectronRendererStorageAdapter,
} from "@blackcode_sa/aios-commercial-integration";
// Set up IPC storage adapter
const storageAdapter = new ElectronRendererStorageAdapter(ipcRenderer);
// Initialize AuthService with IPC storage
const authService = AuthService.getInstance(storageAdapter);
await authService.initialize();React Native
import AsyncStorage from "@react-native-async-storage/async-storage";
import {
AuthService,
ReactNativeStorageAdapter,
} from "@blackcode_sa/aios-commercial-integration";
// Set up AsyncStorage adapter
const storageAdapter = new ReactNativeStorageAdapter(AsyncStorage);
// Initialize AuthService with React Native storage
const authService = AuthService.getInstance(storageAdapter);
await authService.initialize();Node.js/Server
import {
AuthService,
NodeStorageAdapter,
} from "@blackcode_sa/aios-commercial-integration";
// Custom Node.js storage using file system
const storageAdapter = new NodeStorageAdapter({
storageDir: "./data/auth",
encryptionKey: "your-encryption-key",
});
const authService = AuthService.getInstance(storageAdapter);
await authService.initialize();Custom Storage Implementation
import {
AuthService,
StorageAdapter,
} from "@blackcode_sa/aios-commercial-integration";
class MyCustomStorageAdapter implements StorageAdapter {
isAvailable(): boolean {
return true; // Your availability check
}
async getItem(key: string): Promise<string | null> {
// Your get implementation
return await myStorage.get(key);
}
async setItem(key: string, value: string): Promise<void> {
// Your set implementation
await myStorage.set(key, value);
}
async removeItem(key: string): Promise<void> {
// Your remove implementation
await myStorage.remove(key);
}
}
// Use your custom adapter
const authService = AuthService.getInstance(new MyCustomStorageAdapter());4. Set Up Multi-Factor Authentication
// Set up SMS 2FA
const smsSetup = await authService.setupSMSMFA({
phoneNumber: "+1234567890",
displayName: "My Phone",
});
// Set up TOTP (Authenticator app) 2FA
const totpSetup = await authService.setupTOTPMFA({
displayName: "My Authenticator",
});
// Verify and enroll MFA
await authService.verifyAndEnrollMFA({
code: "123456",
verificationId: smsSetup.verificationId,
displayName: "My Phone",
type: "sms",
});🔐 Authentication Features
NEW: Automatic User Onboarding
- ✅ Streamlined setup - A user document is automatically created in Firestore on the first sign-in.
- ✅ Enables trial credits - The system is designed for other services to easily grant trial credits to new users.
- ✅ Profile with preferences created with sensible defaults.
- ✅ Foundation for billing - The user's profile is ready for a billing service to attach a subscription.
- ✅ Custom claims can be configured on your backend to manage authorization.
Basic Authentication
- ✅ Email/Password sign up and sign in
- ✅ Email verification with resend capability
- ✅ Password reset and change
- ✅ Automatic profile creation with default preferences
- ✅ Session management with automatic token refresh
Social Authentication
- ✅ Google Sign-In with automatic profile creation.
- ✅ Facebook Sign-In with a flow ready for billing setup.
- ✅ GitHub Sign-In with a flow ready for trial credit allocation.
- ✅ Unified user experience regardless of auth method.
Multi-Factor Authentication (2FA/MFA)
- ✅ SMS-based verification
- ✅ TOTP Authenticator apps (Google Authenticator, Authy)
- ✅ Multiple factor enrollment and management
- ✅ QR code generation for TOTP setup
- ✅ Factor removal and management
Enhanced Security Features
- ✅ Input validation with comprehensive Zod schemas
- ✅ Re-authentication for sensitive operations
- ✅ User-friendly error handling with detailed messages
- ✅ Rate limiting protection
- ✅ Secure token management with refresh capability
Authentication Persistence
- ✅ Cross-platform compatibility - Works in web, Electron, React Native, Node.js
- ✅ Firebase token persistence - Automatic token refresh and validation
- ✅ Backup auth context - Non-sensitive data cached for immediate access
- ✅ Seamless app restarts - Users stay logged in across app sessions
- ✅ Storage flexibility - Choose your preferred storage backend
- ✅ Automatic fallbacks - Graceful degradation when storage unavailable
🎯 Integration Patterns
Electron Application Integration
// In your main Electron process
import {
initializeAIOS,
AuthService,
} from "@blackcode_sa/aios-commercial-integration";
class AppManager {
private authService: AuthService;
async initialize() {
// Initialize AIOS configuration
await initializeAIOS(yourConfig);
// Get auth service instance
this.authService = AuthService.getInstance();
await this.authService.initialize();
// Monitor authentication state
const authContext = this.authService.getAuthContext();
// Check if user has credits for LLM calls
if (authContext.isAuthenticated && authContext.availableCredits > 0) {
console.log(
`User ready for LLM calls with ${authContext.availableCredits} credits`
);
}
}
async handleUserSignup(email: string, password: string, displayName: string) {
try {
// Automatic user document creation happens here!
const result = await this.authService.signUp({
email,
password,
displayName,
acceptTerms: true,
});
if (result.status === "requires_email_verification") {
// The user document is created, enabling other services to provision
// trial credits or a default billing plan.
console.log("User created and ready for feature access!");
return result;
}
} catch (error) {
console.error("Signup failed:", error);
}
}
}React Component Integration
import { AuthService } from "@blackcode_sa/aios-commercial-integration";
import { useState, useEffect } from "react";
function AuthenticatedApp() {
const [authService] = useState(() => AuthService.getInstance());
const [userProfile, setUserProfile] = useState(null);
const [credits, setCredits] = useState(0);
useEffect(() => {
const loadUserData = async () => {
if (authService.isAuthenticated()) {
// Get complete user profile with billing info
const profile = await authService.getUserProfile();
setUserProfile(profile);
setCredits(profile.availableCredits);
}
};
loadUserData();
}, [authService]);
const handleLogin = async (email: string, password: string) => {
try {
const result = await authService.signIn({ email, password });
if (result.status === "success") {
// Reload user data after login
const profile = await authService.getUserProfile();
setUserProfile(profile);
setCredits(profile.availableCredits);
}
} catch (error) {
// Handle error
}
};
return (
<div>
{userProfile && (
<div>
<h1>Welcome, {userProfile.displayName}!</h1>
<p>Available Credits: {credits}</p>
<p>Plan: {userProfile.plan}</p>
<p>MFA Enabled: {userProfile.mfaEnabled ? "Yes" : "No"}</p>
</div>
)}
</div>
);
}🏢 Enterprise Features
Automatic User Lifecycle Management
- Profile Creation - Default preferences and settings.
- Enables Credit Allocation - System is designed for easy allocation of trial credits on signup.
- Billing Setup - Ready for rate limits and plan configuration by a billing service.
- Custom Claims - Role-based access control.
User Roles and Permissions (Auto-Configured)
FREE_USER- Basic access with trial credits (default)PRO_USER- Enhanced features with subscriptionENTERPRISE_USER- Full feature accessADMIN- Administrative privileges
Billing Integration (Ready-to-Use)
- Stripe customer management with automatic setup
- Subscription tracking with real-time status
- Usage-based billing with detailed analytics
- Credit system with atomic transaction support
Usage Tracking (Built-in)
- LangGraph integration with usage decorators
- Token consumption monitoring with cost tracking
- API usage analytics with performance metrics
- Cost tracking with per-model pricing
🛠️ Configuration
Environment-Specific Configs
import { createConfig } from "@blackcode_sa/aios-commercial-integration";
// Development environment
const devConfig = createConfig(baseConfig, "development");
// Features: No encryption, analytics disabled, debug mode on, extra logging
// Staging environment
const stagingConfig = createConfig(baseConfig, "staging");
// Features: Encryption enabled, analytics on, debug mode on, trial credits
// Production environment
const prodConfig = createConfig(baseConfig, "production");
// Features: Full encryption, analytics on, debug off, MFA requiredAdvanced User Profile Configuration
// Configure default user preferences
const config = {
// ... firebase config
userDefaults: {
preferences: {
theme: "light",
notifications: true,
language: "en",
timezone: "UTC",
defaultModel: "gpt-4",
maxTokensPerRequest: 4000,
autoSaveChats: true,
},
credits: {
trialAmount: 1000,
welcomeBonus: 500, // Additional credits for first-time users
},
billing: {
plan: "free",
rateLimits: {
requestsPerMinute: 10,
requestsPerHour: 200,
requestsPerDay: 2000,
},
},
},
};Health Monitoring
import { getConfigManager } from "@blackcode_sa/aios-commercial-integration";
const configManager = getConfigManager();
const health = await configManager.getHealthStatus();
console.log(health);
// {
// status: "healthy" | "degraded" | "down",
// services: {
// firebase: true,
// auth: true,
// firestore: true,
// functions: true,
// },
// timestamp: Date
// }🚀 What's New in This Version
✅ Automatic User Onboarding
- Streamlined setup for new users with automatic profile creation.
- Enables automatic trial credits and billing plan assignment.
- Complete profile creation with sensible defaults.
- Immediate feature access capability after registration.
✅ Enhanced Profile Management
- Comprehensive user profiles with preferences
- Real-time billing status integration
- MFA status and security settings
- Customizable user preferences (theme, notifications, etc.)
✅ Streamlined Authentication Flow
- Unified experience across all auth methods (email, social)
- Automatic billing setup regardless of signup method
- Instant credit allocation for immediate usage
- Custom claims configured automatically
✅ Production-Ready Security
- Input validation with Zod schemas throughout
- Comprehensive error handling with user-friendly messages
- Rate limiting protection at multiple levels
- MFA support with SMS and TOTP options
💻 Developer Experience
Simplified Integration
// Before: Complex setup required
// After: One line integration
const authService = AuthService.getInstance();
await authService.signUp(userDetails); // Core user document and profile created automatically.Rich Type Safety
interface UserProfile {
uid: string;
email: string;
displayName: string;
preferences: UserPreferences;
mfaEnabled: boolean;
plan: "free" | "starter" | "advanced" | "pro";
availableCredits: number;
subscriptionStatus: "trialing" | "active" | "canceled";
}Comprehensive Error Handling
try {
await authService.signUp(userData);
} catch (error) {
if (error.code === "auth/email-already-in-use") {
// Handle existing user
} else if (error.code === "auth/weak-password") {
// Handle weak password
}
// Detailed error information provided
}🎯 Migration from Basic Auth
If you're upgrading from a basic authentication system:
✅ Automatic Migration Benefits
- Existing users get automatic profile creation on next login
- Enables trial credits to be granted to all existing users
- Billing structure can be created retroactively
- Zero breaking changes to existing authentication calls
Migration Example
// Your existing code works as-is:
const result = await authService.signIn({ email, password });
// But now you get additional benefits:
const profile = await authService.getUserProfile();
console.log(`Welcome back! You have ${profile.availableCredits} credits`);This enhanced SDK provides a complete commercial authentication solution with automatic user onboarding, trial credit system, and production-ready security features. Perfect for Electron applications requiring immediate LLM usage capability.
📚 API Reference
Here are the core components of the AIOS Commercial Integration package. For more detailed documentation, please refer to the README files within the src directory.
Authentication Service (AuthService)
The AuthService provides a complete solution for user authentication and management, with automatic user profile creation in Firestore on first sign-in.
Key Methods:
signUp(data): Creates a new user with email/password.signIn(data): Signs in an existing user.signInWithGoogle(),signInWithFacebook(),signInWithGitHub(): Handles social authentication.signOut(): Clears the user session.getUserProfile(): Fetches a consolidated user profile including preferences and billing status.setupSMSMFA(data),setupTOTPMFA(data): Manages multi-factor authentication setup.verifyAndEnrollMFA(data): Verifies and completes MFA enrollment.
Example: User Sign-Up
const authService = AuthService.getInstance();
const result = await authService.signUp({
email: "[email protected]",
password: "SecurePass123!",
displayName: "John Doe",
acceptTerms: true,
});
if (result.status === "requires_email_verification") {
// The user document is created, enabling other services to provision
// trial credits or a default billing plan.
console.log("User created and ready for feature access!");
}Billing Service (BillingService)
The BillingService manages subscriptions, token credits, and usage tracking. It reads data in real-time from Firestore and uses secure cloud functions for payment operations.
Key Features:
- Real-time Billing State: Get live updates on a user's token balance and subscription status.
- Token Management: Track individual token batches from purchases or subscriptions.
- Subscription Management: Fetch and subscribe to a user's Stripe subscriptions.
- Usage Tracking: Access detailed usage history for conversations and messages.
- Secure Payments: Integrates with Stripe for checkout and customer portal sessions.
Key Methods:
getBillingState(): Gets the user's aggregated billing state.subscribeToBillingState(callback): Subscribes to real-time billing state updates.getTokenBatches(): Retrieves all active token batches.getUserSubscriptions(): Fetches user subscription records created by Stripe webhooks.subscribeToUserSubscriptions(callback): Subscribes to real-time subscription changes.getUsageConversations(options): Gets a paginated history of usage conversations.createCheckoutSession(request): Creates a Stripe checkout session for purchases.createPortalSession(request): Creates a Stripe customer portal session for subscription management.
Core Data Types
The package is strongly typed with TypeScript. Here are some of the central interfaces:
UserProfile: A consolidated view of the user.
interface UserProfile {
uid: string;
email: string;
displayName: string;
mfaEnabled: boolean;
plan: "free" | "starter" | "advanced" | "pro";
availableCredits: number;
subscriptionStatus: "trialing" | "active" | "canceled" | "past_due";
// ... and more
}BillingState: Real-time summary of a user's billing status.
interface BillingState {
tokenCredits: number;
activeBatches: number;
planType: "free" | "starter" | "advanced" | "pro";
subscriptionStatus:
| "active"
| "canceled"
| "pending_cancellation"
| "past_due"
| "trialing";
// ... and more
}UserSubscription: Represents a single user subscription from Stripe.
interface UserSubscription {
subscriptionId: string;
userId: string;
subscriptionStatus:
| "active"
| "canceled"
| "pending_cancellation"
| "past_due"
| "trialing"
| "incomplete";
plan: "free" | "starter" | "advanced" | "pro";
currentPeriodEnd: Date | null;
// ... and more
}Input Validation
All service inputs are validated using Zod schemas to ensure data integrity and security.
Validation Philosophy:
- Security-First: All inputs are sanitized to prevent common vulnerabilities.
- Type Safety: Zod schemas provide runtime type checking that integrates seamlessly with TypeScript.
- Detailed Errors: Get clear error messages when validation fails.
Example: Password Schema
import { z } from "zod";
export const passwordSchema = z
.string()
.min(8, "Password must be at least 8 characters")
.regex(/[A-Z]/, "Password must contain at least one uppercase letter")
.regex(/[a-z]/, "Password must contain at least one lowercase letter")
.regex(/\d/, "Password must contain at least one number")
.regex(/[@$!%*?&]/, "Password must contain at least one special character");All schemas are exported and can be used for client-side validation in your application.
🔧 Development
Building the Package
npm run build # Build TypeScript
npm run build:watch # Build with watch mode
npm run dev # Development mode with watchTesting
npm test # Run tests
npm run test:watch # Run tests in watch modeLinting
npm run lint # Check code style
npm run lint:fix # Fix linting issues🚀 Deployment
NPM Publishing
npm run build # Build the package
npm publish # Publish to NPM registryVersion Management
The package follows semantic versioning (semver):
MAJOR.MINOR.PATCH- Breaking changes increment MAJOR
- New features increment MINOR
- Bug fixes increment PATCH
🔒 Security Considerations
Production Checklist
- ✅ Use environment-specific configurations
- ✅ Enable encryption for production
- ✅ Require MFA for admin users
- ✅ Implement proper error logging
- ✅ Monitor authentication metrics
- ✅ Regular security audits
Best Practices
- Store sensitive config in environment variables
- Use HTTPS only in production
- Implement proper CORS policies
- Regular dependency updates
- Monitor for security vulnerabilities
🤝 Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Run linting and tests
- Submit a pull request
📄 License
MIT License - see LICENSE file for details
🆘 Support
For issues and questions:
- Create an issue on GitHub
- Check existing documentation
- Review the type definitions for API details
🗺️ Roadmap
Current Version (1.0.3)
- ✅ Firebase Authentication with 2FA/MFA support
- ✅ Platform-agnostic storage adapters
- ✅ Cross-platform compatibility (Web, Electron, React Native, Node.js)
- ✅ TypeScript support with comprehensive type definitions
- ✅ Input validation with Zod schemas
- ✅ Comprehensive error handling system
- ✅ Authentication persistence across app restarts
- ✅ Custom storage adapter implementation support
Upcoming Features
- 🔄 Stripe billing integration
- 🔄 LangGraph usage tracking and analytics
- 🔄 User onboarding flows
- 🔄 Advanced security analytics
- 🔄 Audit logging and security events
- 🔄 Real-time usage monitoring
- 🔄 Enhanced billing management
Built with ❤️ for the AIOS ecosystem
🖥️ Electron Social Authentication
⚠️ CRITICAL SECURITY WARNING ⚠️
The current client-side OAuth implementation has serious security vulnerabilities and should ONLY be used for testing.
🔴 Security Issues:
- OAuth client secrets exposed in client code
- Secrets extractable through app reverse-engineering
- Violates OAuth 2.0 security standards
- Not suitable for production deployment
✅ For Testing: Use client-side methods during development
🛡️ For Production: Use secure server-side token exchange via cloud function
Problem with Standard Social Login
Firebase's signInWithPopup doesn't work in Electron because it requires browser popup functionality. This affects Google, Facebook, and GitHub social authentication in native Electron apps.
Solution Options
Option 1: Client-Side (Testing Only) ⚠️
For development and testing, you can use the built-in client-side OAuth methods:
import { AuthService } from "@blackcode_sa/aios-commercial-integration";
const authService = AuthService.getInstance();
// ⚠️ TESTING ONLY - Client secrets exposed
const result = await authService.signInWithSocialElectron("google");Option 2: Server-Side (Production) 🛡️
For production, use the secure cloud function approach:
Step 1: Cloud Function Available
- URL:
https://us-central1-aios-ce15f.cloudfunctions.net/exchangeOAuthToken - Status: ✅ Deployed and configured
- Access: ✅ Public (authenticated users only)
Step 2: Secure Implementation
// 1. Get authorization code from OAuth flow
const authCode = await electronOAuthFlow(provider);
// 2. Exchange via secure cloud function
const response = await fetch(
"https://us-central1-aios-ce15f.cloudfunctions.net/exchangeOAuthToken",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
provider: "google",
authCode: authCode,
idToken: await user.getIdToken(), // Optional
}),
}
);
const { accessToken } = await response.json();
// 3. Sign in with Firebase
const credential = GoogleAuthProvider.credential(null, accessToken);
await signInWithCredential(auth, credential);Configuration
Development Configuration (Testing)
import { createConfig } from "@blackcode_sa/aios-commercial-integration";
const config = createConfig({
firebase: {
/* your config */
},
oauth: {
redirectUri: "http://localhost:3000/oauth/callback",
google: {
clientId: "your-google-client-id",
clientSecret: process.env.GOOGLE_CLIENT_SECRET, // ⚠️ Testing only
},
// Only include secrets for development
},
});Production Configuration (Secure)
const config = createConfig({
firebase: {
/* your config */
},
oauth: {
redirectUri: "http://localhost:3000/oauth/callback",
cloudFunctionUrl:
"https://us-central1-aios-ce15f.cloudfunctions.net/exchangeOAuthToken",
useSecureExchange: true, // Use cloud function instead of client-side
// No client secrets in production config
},
});Migration Path
- Phase 1 (Current): Use client-side for testing and development
- Phase 2 (Coming Soon): Implement
signInWithSocialElectronSecure()method - Phase 3 (Production): Remove client secrets, use cloud function only
OAuth Provider Setup
Google Cloud Console:
- Create OAuth 2.0 credentials
- Add
http://localhost:3000/oauth/callbackto authorized redirect URIs
Facebook Developers:
- Create new app with Facebook Login
- Add
http://localhost:3000/oauth/callbackto valid OAuth redirect URIs
GitHub OAuth Apps:
- Create new OAuth app in Developer settings
- Set authorization callback URL to
http://localhost:3000/oauth/callback
Security Checklist
✅ For Testing:
- [ ] Store secrets in environment variables
- [ ] Never commit secrets to version control
- [ ] Mark as development-only in documentation
🛡️ For Production:
- [ ] Use cloud function for token exchange
- [ ] Remove client secrets from app
- [ ] Set Firebase Function environment variables
- [ ] Test secure OAuth flow
- [ ] Deploy with production configuration
For detailed implementation examples, see the Services Documentation.
