
Product
Introducing Socket Firewall Enterprise: Flexible, Configurable Protection for Modern Package Ecosystems
Socket Firewall Enterprise is now available with flexible deployment, configurable policies, and expanded language support.
@blackcode_sa/aios-commercial-integration
Advanced tools
Framework-agnostic commercial integration package for AIOS with Firebase Auth, Stripe billing, and LangGraph integration. Works with any JavaScript environment.
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.
AIOS Commercial Integration provides a complete foundation for your 4-week commercial integration plan, combining:
npm install @blackcode_sa/aios-commercial-integration
npm install firebase
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
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);
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();
The AuthService supports platform-agnostic authentication persistence through storage adapters with automatic Node.js environment detection:
The AuthService now automatically detects Node.js environments and enables enhanced persistence for:
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:
import { AuthService } from "@blackcode_sa/aios-commercial-integration";
// Uses localStorage automatically in browser environments
const authService = AuthService.getInstance();
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
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();
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();
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();
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());
// 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",
});
// 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);
}
}
}
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>
);
}
FREE_USER - Basic access with trial credits (default)PRO_USER - Enhanced features with subscriptionENTERPRISE_USER - Full feature accessADMIN - Administrative privilegesimport { 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
// 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,
},
},
},
};
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
// }
// Before: Complex setup required
// After: One line integration
const authService = AuthService.getInstance();
await authService.signUp(userDetails); // Core user document and profile created automatically.
interface UserProfile {
uid: string;
email: string;
displayName: string;
preferences: UserPreferences;
mfaEnabled: boolean;
plan: "free" | "starter" | "advanced" | "pro";
availableCredits: number;
subscriptionStatus: "trialing" | "active" | "canceled";
}
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
}
If you're upgrading from a basic authentication system:
// 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.
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.
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!");
}
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:
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.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
}
All service inputs are validated using Zod schemas to ensure data integrity and security.
Validation Philosophy:
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.
npm run build # Build TypeScript
npm run build:watch # Build with watch mode
npm run dev # Development mode with watch
npm test # Run tests
npm run test:watch # Run tests in watch mode
npm run lint # Check code style
npm run lint:fix # Fix linting issues
npm run build # Build the package
npm publish # Publish to NPM registry
The package follows semantic versioning (semver):
MAJOR.MINOR.PATCHMIT License - see LICENSE file for details
For issues and questions:
Built with β€οΈ for the AIOS ecosystem
β οΈ CRITICAL SECURITY WARNING β οΈ
The current client-side OAuth implementation has serious security vulnerabilities and should ONLY be used for testing.
π΄ Security Issues:
β
For Testing: Use client-side methods during development
π‘οΈ For Production: Use secure server-side token exchange via cloud function
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.
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");
For production, use the secure cloud function approach:
Step 1: Cloud Function Available
https://us-central1-aios-ce15f.cloudfunctions.net/exchangeOAuthTokenStep 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);
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
},
});
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
},
});
signInWithSocialElectronSecure() methodGoogle Cloud Console:
http://localhost:3000/oauth/callback to authorized redirect URIsFacebook Developers:
http://localhost:3000/oauth/callback to valid OAuth redirect URIsGitHub OAuth Apps:
http://localhost:3000/oauth/callbackβ For Testing:
π‘οΈ For Production:
For detailed implementation examples, see the Services Documentation.
FAQs
Framework-agnostic commercial integration package for AIOS with Firebase Auth, Stripe billing, and LangGraph integration. Works with any JavaScript environment.
We found that @blackcode_sa/aios-commercial-integration demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.Β It has 1 open source maintainer collaborating on the project.
Did you know?

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.

Product
Socket Firewall Enterprise is now available with flexible deployment, configurable policies, and expanded language support.

Security News
Open source dashboard CNAPulse tracks CVE Numbering Authoritiesβ publishing activity, highlighting trends and transparency across the CVE ecosystem.

Product
Detect malware, unsafe data flows, and license issues in GitHub Actions with Socketβs new workflow scanning support.