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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@jager-ai/holy-auth-firebase

v1.0.0

Published

Firebase Authentication module with Google Sign-In support

Readme

@mvp-factory/holy-auth-firebase

Firebase Authentication module with Google Sign-In support. Extracted from Holy Habit Phase 2 authentication system.

🚀 Features

  • Google Sign-In - One-click Google authentication
  • 🔒 Token Management - Automatic ID token handling and refresh
  • 🔄 Backend Sync - Automatic session synchronization with backend
  • 🛡️ Server-side Verification - JWT token verification utilities
  • 🎯 TypeScript Support - Full type definitions included
  • 🔌 Event System - Subscribe to auth state changes
  • 💾 Auto-save Integration - Built-in auto-save functionality
  • 🔐 Authenticated Fetch - HTTP utilities with automatic token attachment

📦 Installation

npm install @mvp-factory/holy-auth-firebase
# or
yarn add @mvp-factory/holy-auth-firebase
# or
pnpm add @mvp-factory/holy-auth-firebase

Peer Dependencies

npm install firebase@^10.0.0

For server-side token verification:

npm install jsonwebtoken@^9.0.0

🔧 Quick Start

1. Basic Setup

import { initializeFirebaseAuth } from '@mvp-factory/holy-auth-firebase';

// Initialize Firebase Auth
const authManager = await initializeFirebaseAuth({
  apiKey: "your-api-key",
  authDomain: "your-auth-domain",
  projectId: "your-project-id",
  appId: "your-app-id"
});

// Sign in with Google
const result = await authManager.signInWithGoogle();
console.log('Signed in:', result.user.email);

2. With React

import { FirebaseAuthManager, updateAuthUI } from '@mvp-factory/holy-auth-firebase';

function App() {
  const [user, setUser] = useState(null);
  
  useEffect(() => {
    const authManager = FirebaseAuthManager.getInstance();
    
    // Listen to auth state changes
    const unsubscribe = authManager.on('auth_state_changed', (event, data) => {
      setUser(data.user);
      updateAuthUI(!!data.user, data.user);
    });
    
    return unsubscribe;
  }, []);
  
  const handleLogin = async () => {
    try {
      await authManager.signInWithGoogle();
    } catch (error) {
      console.error('Login failed:', error);
    }
  };
  
  return (
    <div>
      {user ? (
        <p>Welcome, {user.email}!</p>
      ) : (
        <button onClick={handleLogin}>Sign in with Google</button>
      )}
    </div>
  );
}

📖 API Reference

FirebaseAuthManager

Singleton class for managing Firebase authentication.

const authManager = FirebaseAuthManager.getInstance(options?: AuthOptions);

// Methods
authManager.initialize(config: FirebaseConfig): Promise<void>
authManager.signInWithGoogle(customParams?: Record<string, string>): Promise<SignInResult>
authManager.signOut(): Promise<void>
authManager.getCurrentUser(): AuthUser | null
authManager.getAuthState(): AuthState
authManager.getIdToken(forceRefresh?: boolean): Promise<string | null>
authManager.isAuthenticated(): boolean

// Events
authManager.on(event: AuthEvent, listener: AuthEventListener): () => void
authManager.off(event: AuthEvent, listener: AuthEventListener): void

Authenticated Fetch Utilities

import { authenticatedFetch, authenticatedJSON, createAuthenticatedClient } from '@mvp-factory/holy-auth-firebase';

// Simple authenticated fetch
const response = await authenticatedFetch('/api/data');

// Fetch JSON with authentication
const data = await authenticatedJSON('/api/users');

// Create authenticated client
const api = createAuthenticatedClient('https://api.example.com');
const users = await api.get('/users');
const newUser = await api.post('/users', { name: 'John' });

Server-side Token Verification

import { TokenVerifier, createAuthMiddleware } from '@mvp-factory/holy-auth-firebase';

// Express middleware
app.use(createAuthMiddleware('your-project-id'));

// Manual verification
const verifier = new TokenVerifier('your-project-id');
const result = await verifier.verifyIdToken(idToken);
if (result) {
  console.log('Verified user:', result.uid, result.email);
}

⚙️ Configuration

AuthOptions

interface AuthOptions {
  persistence?: 'local' | 'session' | 'none';  // Default: 'local'
  customParameters?: Record<string, string>;   // Google OAuth custom params
  scopes?: string[];                          // Additional OAuth scopes
  autoSync?: boolean;                         // Auto sync with backend (default: true)
  syncEndpoint?: string;                      // Backend sync endpoint (default: '/api/auth/firebase/sync')
}

Firebase Configuration

interface FirebaseConfig {
  apiKey: string;
  authDomain: string;
  projectId: string;
  storageBucket?: string;
  messagingSenderId?: string;
  appId: string;
  measurementId?: string;
}

🔥 Firebase Console Setup

  1. Go to Firebase Console

  2. Create a new project or select existing

  3. Enable Authentication service

  4. Enable Google Sign-In provider:

    • Authentication → Sign-in method → Google → Enable
    • Configure OAuth consent screen
    • Add authorized domains
  5. Get your configuration:

    • Project Settings → General → Your apps → Web app
    • Copy the configuration object

🔐 Backend Integration

PHP Backend Example

// api/auth/firebase/sync.php
<?php
require_once '../vendor/autoload.php';
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

// Get ID token from Authorization header
$headers = getallheaders();
$authHeader = $headers['Authorization'] ?? '';

if (!str_starts_with($authHeader, 'Bearer ')) {
    http_response_code(401);
    die(json_encode(['error' => 'Unauthorized']));
}

$idToken = substr($authHeader, 7);

// Verify token (implement your verification logic)
try {
    // Decode and verify the token
    $decoded = verifyFirebaseToken($idToken);
    
    // Create/update session
    $_SESSION['user_uid'] = $decoded->sub;
    $_SESSION['user_email'] = $decoded->email;
    
    echo json_encode([
        'success' => true,
        'user' => [
            'uid' => $decoded->sub,
            'email' => $decoded->email,
            'name' => $decoded->name
        ]
    ]);
} catch (Exception $e) {
    http_response_code(401);
    echo json_encode(['error' => 'Invalid token']);
}

Node.js Backend Example

const express = require('express');
const { createAuthMiddleware } = require('@mvp-factory/holy-auth-firebase');

const app = express();

// Apply auth middleware
app.use('/api/*', createAuthMiddleware('your-project-id'));

// Protected route
app.get('/api/profile', (req, res) => {
  // req.user contains verified user info
  res.json({
    uid: req.user.uid,
    email: req.user.email
  });
});

🎯 Use Cases

Auto-save with Authentication

import { setupAutoSave, getAutoSavedContent } from '@mvp-factory/holy-auth-firebase';

// Setup auto-save
const cleanup = setupAutoSave(
  () => document.getElementById('content').value,
  {
    interval: 30000, // 30 seconds
    key: 'my_app_autosave',
    onSave: (data) => console.log('Saved:', data),
    onError: (error) => console.error('Save failed:', error)
  }
);

// Restore saved content
const saved = getAutoSavedContent('my_app_autosave');
if (saved) {
  document.getElementById('content').value = saved.content;
}

Protected API Calls

const api = createAuthenticatedClient('https://api.example.com');

// All requests automatically include auth token
try {
  const profile = await api.get('/user/profile');
  const posts = await api.get('/user/posts');
  
  // Upload with authentication
  const file = document.getElementById('file').files[0];
  const upload = await api.upload('/upload', file, {
    fieldName: 'avatar'
  });
} catch (error) {
  if (error.message.includes('401')) {
    // Token expired or invalid
    await authManager.signOut();
  }
}

🧪 Testing

// Mock Firebase Auth for testing
import { FirebaseAuthManager } from '@mvp-factory/holy-auth-firebase';

// In your test setup
const mockUser = {
  uid: 'test-uid',
  email: '[email protected]',
  displayName: 'Test User'
};

// Mock the sign in method
jest.spyOn(authManager, 'signInWithGoogle').mockResolvedValue({
  user: mockUser,
  token: 'mock-token'
});

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📝 License

MIT © MVP Factory

🔗 Related Packages