πŸš€ DAY 5 OF LAUNCH WEEK: Introducing Socket Firewall Enterprise.Learn more β†’
Socket
Book a DemoInstallSign in
Socket

@blackcode_sa/aios-commercial-integration

Package Overview
Dependencies
Maintainers
1
Versions
20
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@blackcode_sa/aios-commercial-integration

Framework-agnostic commercial integration package for AIOS with Firebase Auth, Stripe billing, and LangGraph integration. Works with any JavaScript environment.

latest
Source
npmnpm
Version
1.0.20
Version published
Maintainers
1
Created
Source

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-integration

Peer 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: "user@example.com",
  password: "SecurePass123!",
  displayName: "John Doe",
  acceptTerms: true,
});

// Sign in existing user
const loginResult = await authService.signIn({
  email: "user@example.com",
  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 environments

Key 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 process

Electron 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 subscription
  • ENTERPRISE_USER - Full feature access
  • ADMIN - 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 required

Advanced 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: "user@example.com",
  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 watch

Testing

npm test              # Run tests
npm run test:watch    # Run tests in watch mode

Linting

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 registry

Version 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/callback to authorized redirect URIs

Facebook Developers:

  • Create new app with Facebook Login
  • Add http://localhost:3000/oauth/callback to 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.

πŸ”§ Advanced Configuration

Keywords

firebase

FAQs

Package last updated on 16 Jul 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts