@al-hamoud/firebase-supabase-bridge
v2.0.1
Published
Enterprise Firebase Auth + Supabase/PostgreSQL bridge with zero rate limiting and comprehensive business logic support
Maintainers
Readme
🔐 Firebase Auth + PostgreSQL — Enterprise Authentication System
A production-ready hybrid authentication system combining Firebase Auth for authentication with PostgreSQL/Supabase for 100% database-native business logic. Features zero rate limiting, monad-based error handling, and PostgreSQL-first architecture for maximum performance.
Live System: https://supa-claims-bridge-001.web.app
✨ Features
🔥 Firebase Authentication (Enhanced)
- Phone OTP Authentication: Production-ready SMS verification
- JWT Token Generation: Secure token handling with custom claims
- Zero Rate Limiting: No artificial restrictions on legitimate usage
- Security Headers: HTTPS-only, API restrictions, CORS protection
🗄️ PostgreSQL Business Logic (Zero Rate Limiting Architecture)
- 100% Database-Native: All business operations in PostgreSQL functions
- Zero Cold Starts: Instant response times vs Firebase Functions
- Row Level Security: Database-enforced data isolation
- Audit Trails: Complete operation logging (not for limiting)
- No Rate Limiting: Unlimited legitimate operations
- Monad Error Handling: Consistent Result<T,E> pattern throughout
🛡️ Enterprise Security
- Defense-in-Depth: Multi-layer security validation
- Claims Versioning: Future-proof JWT schema evolution
- Input Validation: Strict parameter and role validation
- Search Path Security: Protection against injection attacks
Details: Architecture & Security, Claims Versioning, Rate Limiting.
🧩 Functions Overview
Blocking Triggers
authBeforeUserCreated— set initial claims at sign-upauthBeforeUserSignedIn— ensure roles/claims on every sign-in
Callable HTTPS
setCustomClaimsForUser— update a single user’s claimsbulkSetCustomClaims— admin bulk operations (hardened flow)verifyTokenClaims— debug/inspect decoded token + claims
Source pointers and constraints live under functions/src/ (types/validators/limiter). See the Developer Guide for dev/test/deploy.
� Architecture
This system uses a hybrid architecture combining Firebase Authentication with PostgreSQL business logic:
🔄 Authentication Flow (Firebase)
- Phone OTP: User authenticates via Firebase Phone Auth
- JWT Generation: Firebase issues secure tokens with user identity
- Token Validation: PostgreSQL validates Firebase JWTs for business operations
🗄️ Business Logic Flow (PostgreSQL)
- Client requests a business role via Supabase RPC call
- PostgreSQL function validates Firebase JWT and request parameters
- Database operation updates user business role with audit logging
- Response confirms role assignment with security validation
🛡️ Security Architecture
- ✅ Firebase JWT Validation: PostgreSQL verifies Firebase token authenticity
- ✅ Row Level Security: Database-enforced data isolation per user
- ✅ Rate Limiting: PostgreSQL-native request throttling
- ✅ Audit Logging: Complete operation history in database
- ✅ Input Validation: Strict parameter checking in PostgreSQL functions
- ✅ Search Path Security: Protection against SQL injection attacks
Read: Architecture & Security
🚦 Rate Limiting (Configurable)
- Dual Rate Limits: X1 requests per Y1 seconds AND X2 requests per Y2 seconds
- Environment Configurable: Set limits via
.envvariables (VITE_RATE_LIMIT_1_REQUESTS, etc.) - Default: 1 request/minute AND 3 requests/15 minutes (original Firebase behavior)
- Database Enforced: PostgreSQL-native rate limiting with complete audit trails
- Flexible Examples: 5/minute + 20/hour (dev), 1/2min + 2/hour (enterprise)
Reference: Configurable Rate Limiting Guide
🔄 Claims Versioning
- Adds
claims_vto new claims writes; utilities handle legacy vs modern formats. - Version helpers:
getCurrentClaimsVersion(),getClaimsVersion(claims), etc. - Validates claims size (~900 bytes enforced) before updates.
Summary & examples: CLAIMS-VERSIONING-SUMMARY.md
📚 Documentation
🚀 Getting Started
- Quick Setup Guide - Get up and running in minutes
- Deployment Guide - Deploy to Firebase & Supabase
- Architecture Overview - System design and principles
� Development
- Testing Guide - Comprehensive testing documentation
- Troubleshooting Guide - Common issues and solutions
- API Reference - Complete API documentation
- Integration Guide - Client integration examples
📦 NPM Package
- NPM Package - Install via npm
- Package README - Package-specific documentation
- Release Process - How to publish new versions
🔐 Security & Operations
- Security Checklist - Security hardening guide
- Contributing Guide - How to contribute
- Changelog - Version history and changes
�🛠️ Quick Setup
Prerequisites
- ✅ Firebase Project with Phone Authentication enabled
- ✅ Supabase Project for PostgreSQL database
- ✅ Node.js 18+ installed
- ✅ Firebase CLI installed (
npm install -g firebase-tools)
Installation
Clone the repository:
git clone https://github.com/Opena-app/firebase-auth-claims.git cd firebase-auth-claimsInstall dependencies:
npm install cd functions && npm install && cd ..Configure environment:
cp .env.example .env # Edit .env with your Firebase and Supabase credentialsBuild configuration:
npm run build:configDeploy to Firebase:
firebase deploy --only hosting
For detailed setup instructions, see the Quick Setup Guide.
💻 Usage Example
Client Integration
import { initializeApp } from 'firebase/app';
import { getAuth, signInWithPhoneNumber } from 'firebase/auth';
import { createClient } from '@supabase/supabase-js';
// Initialize Firebase
const app = initializeApp(window.FIREBASE_CONFIG);
const auth = getAuth(app);
// Initialize Supabase
const supabase = createClient(
window.SUPABASE_CONFIG.url,
window.SUPABASE_CONFIG.publishableKey
);
// Authenticate with phone
const confirmationResult = await signInWithPhoneNumber(
auth,
'+447746506658',
recaptchaVerifier
);
await confirmationResult.confirm('123456');
// Set business role via PostgreSQL
const { data, error } = await supabase.rpc('set_user_business_role', {
target_uid: auth.currentUser.uid,
new_role: 'super-admin',
admin_uid: auth.currentUser.uid
});
if (data.success) {
console.log('✅ Role set:', data.business_role);
// Refresh token to get updated claims
await auth.currentUser.getIdToken(true);
}NPM Package Usage
npm install @al-hamoud/firebase-supabase-bridgeimport {
Result,
ok,
err,
safeValidateUserId,
AUTH_CONSTRAINTS
} from '@al-hamoud/firebase-supabase-bridge';
// Use Result monad for error handling
const userIdResult = safeValidateUserId('firebase-user-123');
if (userIdResult.isOk()) {
console.log('Valid user ID:', userIdResult.value);
} else {
console.error('Invalid:', userIdResult.error.message);
}🧪 Testing
Run the comprehensive test suite:
cd functions
npm test # Run all tests
npm test -- --coverage # With coverage report
npm test -- --watch # Watch mode for developmentTest Coverage: 74+ passing tests covering authentication, business logic, security, and performance.
See the Testing Guide for detailed testing documentation.
🚀 Live Demo
Production System: https://supa-claims-bridge-001.web.app
Features:
- Phone OTP authentication
- Custom business roles (super-admin, admin, member)
- Real-time JWT custom claims
- PostgreSQL business logic
- Zero rate limiting
🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
Quick Contribution Steps:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes and add tests
- Run tests:
npm test - Commit:
git commit -m 'feat: add amazing feature' - Push:
git push origin feature/amazing-feature - Open a Pull Request
📄 License
MIT © al-hamoud — see LICENSE.
🔗 Links
- Live System: https://supa-claims-bridge-001.web.app
- NPM Package: https://www.npmjs.com/package/@al-hamoud/firebase-supabase-bridge
- GitHub Repository: https://github.com/Opena-app/firebase-auth-claims
- Issue Tracker: https://github.com/Opena-app/firebase-auth-claims/issues
- Firebase Console: https://console.firebase.google.com/project/supa-claims-bridge-001
- Supabase Dashboard: https://app.supabase.com
Built with ❤️ for enterprise-grade authentication systems
� Usage & Deployment
Deploy PostgreSQL Functions
# Deploy business logic to your PostgreSQL/Supabase database
psql -h YOUR_DB_HOST -d YOUR_DB_NAME -f postgresql-business-logic-complete.sql
# Deploy Firebase JWT integration
psql -h YOUR_DB_HOST -d YOUR_DB_NAME -f postgresql-firebase-jwt-fix.sqlClient Integration
// Initialize Firebase Auth and Supabase
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
import { createClient } from '@supabase/supabase-js';
// Set business role using Supabase RPC with Firebase authentication
try {
const { data, error } = await supabase.rpc('set_user_business_role_firebase', {
firebase_uid: firebase_user.uid,
business_role: 'merchant'
});
if (error) throw error;
console.log('Role set successfully:', data);
} catch (error) {
console.error('Error setting role:', error);
}🧑💻 Developer Guide
- Database: PostgreSQL 14+ with Supabase recommended
- Authentication: Firebase Auth with Phone provider
- Testing: End-to-end tests with Firebase Auth + PostgreSQL
- Security: RLS policies and audit logging enabled
Full setup: Developer Guide
🌐 Web Tester (Invisible reCAPTCHA) + Firebase Hosting
This repo includes a lightweight web tester (public/index.html + styles.css) to:
- Sign in with phone (Invisible reCAPTCHA)
- Call
verifyTokenClaimsonce or in bursts (to exercise rate limits)
Setup (Option A — Firebase Hosting):
firebase init hosting→publicdir, SPA = No- Put
index.htmlandstyles.cssinpublic/ - Deploy:
firebase deploy --only hosting - Ensure Authentication → Settings → Authorized domains contains your
*.web.app,*.firebaseapp.com,localhost - For heavy testing, prefer Auth Emulator or test phone numbers to avoid SMS throttling
The tester uses modular v10 SDK and manages the reCAPTCHA verifier correctly to avoid duplicate renders. Buttons include a burst tester to observe limiting.
🔒 Security Implementation Checklist
A pragmatic, phased checklist (API key restrictions, authorized domains, billing alerts, etc.) is included to harden your project. Start with referrer/API restrictions and domain whitelisting; add monitoring next.
Checklist: SECURITY-IMPLEMENTATION-CHECKLIST.md
🤝 Contributing & Release
- Dev prerequisites, scripts, and CI expectations
- Release checklist (tests, secrets, limits, deploy, monitor)
- PR template & quality gates
Start here:
📄 License
MIT — see LICENSE.
📚 Doc Index (paths fixed)
- Architecture & Security →
./Architecture-and-Security.md - Rate Limiting →
./Rate-Limiting.md - Admin Operations & Claims →
./Admin-Operations-and-Claims.md - Claims Versioning Summary →
./CLAIMS-VERSIONING-SUMMARY.md - Developer Guide →
./Developer-Guide.md - Security Checklist →
./SECURITY-IMPLEMENTATION-CHECKLIST.md - Contributing →
./CONTRIBUTING.md/./Contributing-and-Release.md
Credits
Built with a security-first, SSOT architecture, and comprehensive tests.
