Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
feat(skills): Add Firebase plugin with Firestore, Auth, and Storage skills (#18)
Jeremy Dawes6b95510463e9
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex 202c80c6..6815a10c 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -5,9 +5,9 @@"email": "[email protected]"},"metadata": {- "description": "Production-tested skills for Claude Code - Cloudflare, AI, React, Tailwind v4, and modern web development",- "version": "3.1.0",- "updated": "2026-01-14"+ "description": "Production-tested skills for Claude Code - Cloudflare, Firebase, AI, React, Tailwind v4, and modern web development",+ "version": "3.2.0",+ "updated": "2026-01-25"},"plugins": [{@@ -120,6 +120,16 @@"./skills/vercel-blob"]},+ {+ "name": "firebase",+ "description": "Firebase platform skills - Firestore NoSQL database, Authentication, and Cloud Storage. 3 production-tested skills for building Firebase applications.",+ "source": "./",+ "skills": [+ "./skills/firebase-firestore",+ "./skills/firebase-auth",+ "./skills/firebase-storage"+ ]+ },{"name": "cms","description": "Content management skills - TinaCMS, Sveltia CMS, and WordPress plugin development.",diff --git a/skills/firebase-auth/README.md b/skills/firebase-auth/README.mdnew file mode 100644index 00000000..d754b49d--- /dev/null+++ b/skills/firebase-auth/README.md@@ -0,0 +1,84 @@+# Firebase Authentication Skill++Production-tested skill for implementing Firebase Authentication in web and mobile applications.++## Auto-Trigger Keywords++This skill activates when Claude detects these keywords:++### Technology Keywords+- firebase auth, firebase authentication+- firebase login, firebase sign in, firebase signup+- firebase user, firebase session+- firebase-admin auth+- firebase oauth, firebase social login++### Operation Keywords+- signInWithEmailAndPassword, createUserWithEmailAndPassword+- signInWithPopup, signInWithRedirect+- onAuthStateChanged, auth state+- getIdToken, verifyIdToken+- firebase session cookie+- firebase custom claims+- firebase phone auth, firebase mfa+- firebase password reset+- firebase email verification++### Provider Keywords+- firebase google sign in+- firebase github login+- firebase facebook auth+- firebase apple sign in+- firebase microsoft auth+- firebase twitter auth++### Error Keywords+- auth/invalid-credential+- auth/user-not-found+- auth/wrong-password+- auth/email-already-in-use+- auth/popup-closed-by-user+- auth/popup-blocked+- auth/requires-recent-login+- auth/too-many-requests+- firebase token expired+- firebase auth cors error++### Framework Keywords+- next.js firebase auth+- react firebase auth+- firebase auth middleware+- firebase protected route+- firebase auth context++## What This Skill Covers++- Email/password authentication+- OAuth providers (Google, GitHub, etc.)+- Phone authentication+- Multi-factor authentication (MFA)+- Auth state management+- Token management and verification+- Session cookies for SSR+- Custom claims and roles+- Protected routes+- Error handling best practices++## When to Use This Skill++Use when:+- Setting up authentication in a Firebase project+- Implementing sign-in/sign-up flows+- Adding social login providers+- Managing user sessions+- Protecting API routes and pages+- Implementing role-based access control+- Handling authentication errors+- Migrating to modular SDK (v9+)++## Related Skills++- `firebase-firestore` - Firebase Firestore database+- `firebase-storage` - Firebase Cloud Storage+- `clerk-auth` - Alternative: Clerk authentication+- `better-auth` - Alternative: Better Auth librarydiff --git a/skills/firebase-auth/SKILL.md b/skills/firebase-auth/SKILL.mdnew file mode 100644index 00000000..8e2fc75b--- /dev/null+++ b/skills/firebase-auth/SKILL.md@@ -0,0 +1,734 @@+---+name: firebase-auth+description: |+ Build with Firebase Authentication - email/password, OAuth providers, phone auth, and custom tokens. Use when: setting up auth flows, implementing sign-in/sign-up, managing user sessions, protecting routes, or troubleshooting auth/invalid-credential, auth/popup-closed, auth/user-not-found, or token refresh errors. Prevents 12 documented errors.+user-invocable: true+---++# Firebase Authentication++**Status**: Production Ready+**Last Updated**: 2026-01-25+**Dependencies**: None (standalone skill)+**Latest Versions**: [email protected], [email protected]++---++## Quick Start (5 Minutes)++### 1. Enable Auth Providers in Firebase Console++1. Go to Firebase Console > Authentication > Sign-in method+2. Enable desired providers (Email/Password, Google, etc.)+3. Configure OAuth providers with client ID/secret++### 2. Initialize Firebase Auth (Client)++```typescript+// src/lib/firebase.ts+import { initializeApp } from 'firebase/app';+import { getAuth } from 'firebase/auth';++const firebaseConfig = {+ apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,+ authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,+ projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,+ // ... other config+};++const app = initializeApp(firebaseConfig);+export const auth = getAuth(app);+```++### 3. Initialize Firebase Admin (Server)++```typescript+// src/lib/firebase-admin.ts+import { initializeApp, cert, getApps } from 'firebase-admin/app';+import { getAuth } from 'firebase-admin/auth';++if (!getApps().length) {+ initializeApp({+ credential: cert({+ projectId: process.env.FIREBASE_PROJECT_ID,+ clientEmail: process.env.FIREBASE_CLIENT_EMAIL,+ privateKey: process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n'),+ }),+ });+}++export const adminAuth = getAuth();+```++---++## Email/Password Authentication++### Sign Up++```typescript+import { createUserWithEmailAndPassword, sendEmailVerification, updateProfile } from 'firebase/auth';+import { auth } from './firebase';++async function signUp(email: string, password: string, displayName: string) {+ try {+ const userCredential = await createUserWithEmailAndPassword(auth, email, password);+ const user = userCredential.user;++ // Update display name+ await updateProfile(user, { displayName });++ // Send verification email+ await sendEmailVerification(user);++ return user;+ } catch (error: any) {+ switch (error.code) {+ case 'auth/email-already-in-use':+ throw new Error('Email already registered');+ case 'auth/invalid-email':+ throw new Error('Invalid email address');+ case 'auth/weak-password':+ throw new Error('Password must be at least 6 characters');+ default:+ throw new Error('Sign up failed');+ }+ }+}+```++### Sign In++```typescript+import { signInWithEmailAndPassword } from 'firebase/auth';+import { auth } from './firebase';++async function signIn(email: string, password: string) {+ try {+ const userCredential = await signInWithEmailAndPassword(auth, email, password);+ return userCredential.user;+ } catch (error: any) {+ switch (error.code) {+ case 'auth/user-not-found':+ case 'auth/wrong-password':+ case 'auth/invalid-credential':+ throw new Error('Invalid email or password');+ case 'auth/user-disabled':+ throw new Error('Account has been disabled');+ case 'auth/too-many-requests':+ throw new Error('Too many attempts. Try again later.');+ default:+ throw new Error('Sign in failed');+ }+ }+}+```++### Sign Out++```typescript+import { signOut } from 'firebase/auth';+import { auth } from './firebase';++async function handleSignOut() {+ await signOut(auth);+ // Redirect to login page+}+```++### Password Reset++```typescript+import { sendPasswordResetEmail, confirmPasswordReset } from 'firebase/auth';+import { auth } from './firebase';++// Send reset email+async function resetPassword(email: string) {+ await sendPasswordResetEmail(auth, email);+}++// Confirm reset (from email link)+async function confirmReset(oobCode: string, newPassword: string) {+ await confirmPasswordReset(auth, oobCode, newPassword);+}+```++---++## OAuth Providers (Google, GitHub, etc.)++### Google Sign-In++```typescript+import { signInWithPopup, signInWithRedirect, GoogleAuthProvider } from 'firebase/auth';+import { auth } from './firebase';++const googleProvider = new GoogleAuthProvider();+googleProvider.addScope('email');+googleProvider.addScope('profile');++// Popup method (recommended for desktop)+async function signInWithGoogle() {+ try {+ const result = await signInWithPopup(auth, googleProvider);+ const credential = GoogleAuthProvider.credentialFromResult(result);+ const token = credential?.accessToken;+ return result.user;+ } catch (error: any) {+ if (error.code === 'auth/popup-closed-by-user') {+ // User closed popup - not an error+ return null;+ }+ if (error.code === 'auth/popup-blocked') {+ // Fallback to redirect+ await signInWithRedirect(auth, googleProvider);+ return null;+ }+ throw error;+ }+}++// Redirect method (for mobile or popup-blocked)+async function signInWithGoogleRedirect() {+ await signInWithRedirect(auth, googleProvider);+}+```++### Handle Redirect Result++```typescript+import { getRedirectResult, GoogleAuthProvider } from 'firebase/auth';+import { auth } from './firebase';++// Call on page load+async function handleRedirectResult() {+ try {+ const result = await getRedirectResult(auth);+ if (result) {+ const credential = GoogleAuthProvider.credentialFromResult(result);+ return result.user;+ }+ } catch (error) {+ console.error('Redirect sign-in error:', error);+ }+ return null;+}+```++### Other OAuth Providers++```typescript+import {+ GithubAuthProvider,+ TwitterAuthProvider,+ FacebookAuthProvider,+ OAuthProvider,+} from 'firebase/auth';++// GitHub+const githubProvider = new GithubAuthProvider();+githubProvider.addScope('read:user');++// Microsoft+const microsoftProvider = new OAuthProvider('microsoft.com');+microsoftProvider.addScope('email');+microsoftProvider.addScope('profile');++// Apple+const appleProvider = new OAuthProvider('apple.com');+appleProvider.addScope('email');+appleProvider.addScope('name');+```++---++## Auth State Management++### Listen to Auth State Changes++```typescript+import { onAuthStateChanged, User } from 'firebase/auth';+import { auth } from './firebase';++// React hook example+function useAuth() {+ const [user, setUser] = useState<User | null>(null);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ const unsubscribe = onAuthStateChanged(auth, (user) => {+ setUser(user);+ setLoading(false);+ });++ return () => unsubscribe();+ }, []);++ return { user, loading };+}+```++### Auth Context Provider (React)++```typescript+// src/contexts/AuthContext.tsx+import { createContext, useContext, useEffect, useState, ReactNode } from 'react';+import { onAuthStateChanged, User } from 'firebase/auth';+import { auth } from '@/lib/firebase';++interface AuthContextType {+ user: User | null;+ loading: boolean;+}++const AuthContext = createContext<AuthContextType>({ user: null, loading: true });++export function AuthProvider({ children }: { children: ReactNode }) {+ const [user, setUser] = useState<User | null>(null);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ const unsubscribe = onAuthStateChanged(auth, (user) => {+ setUser(user);+ setLoading(false);+ });++ return () => unsubscribe();+ }, []);++ return (+ <AuthContext.Provider value={{ user, loading }}>+ {children}+ </AuthContext.Provider>+ );+}++export const useAuth = () => useContext(AuthContext);+```++---++## Token Management++### Get ID Token (for API calls)++```typescript+import { auth } from './firebase';++async function getIdToken() {+ const user = auth.currentUser;+ if (!user) throw new Error('Not authenticated');++ // Force refresh to get fresh token+ const token = await user.getIdToken(/* forceRefresh */ true);+ return token;+}++// Use in API calls+async function callProtectedAPI() {+ const token = await getIdToken();++ const response = await fetch('/api/protected', {+ headers: {+ Authorization: `Bearer ${token}`,+ },+ });++ return response.json();+}+```++### Verify ID Token (Server-side)++```typescript+// API route (Next.js example)+import { adminAuth } from '@/lib/firebase-admin';++export async function GET(request: Request) {+ const authHeader = request.headers.get('authorization');+ if (!authHeader?.startsWith('Bearer ')) {+ return Response.json({ error: 'Unauthorized' }, { status: 401 });+ }++ const token = authHeader.split('Bearer ')[1];++ try {+ const decodedToken = await adminAuth.verifyIdToken(token);+ const uid = decodedToken.uid;++ // User is authenticated, proceed with request+ return Response.json({ uid, message: 'Authenticated' });+ } catch (error) {+ return Response.json({ error: 'Invalid token' }, { status: 401 });+ }+}+```++### Session Cookies (Server-Side Rendering)++```typescript+import { adminAuth } from '@/lib/firebase-admin';++// Create session cookie+async function createSessionCookie(idToken: string) {+ const expiresIn = 60 * 60 * 24 * 5 * 1000; // 5 days++ const sessionCookie = await adminAuth.createSessionCookie(idToken, {+ expiresIn,+ });++ return sessionCookie;+}++// Verify session cookie+async function verifySessionCookie(sessionCookie: string) {+ try {+ const decodedClaims = await adminAuth.verifySessionCookie(sessionCookie, true);+ return decodedClaims;+ } catch (error) {+ return null;+ }+}++// Revoke session+async function revokeSession(uid: string) {+ await adminAuth.revokeRefreshTokens(uid);+}+```++---++## Custom Claims & Roles++### Set Custom Claims (Admin SDK)++```typescript+import { adminAuth } from '@/lib/firebase-admin';++// Set admin role+async function setAdminRole(uid: string) {+ await adminAuth.setCustomUserClaims(uid, {+ admin: true,+ role: 'admin',+ });+}++// Set custom permissions+async function setUserPermissions(uid: string, permissions: string[]) {+ await adminAuth.setCustomUserClaims(uid, {+ permissions,+ });+}+```++### Check Custom Claims (Client)++```typescript+import { auth } from './firebase';++async function checkAdminStatus() {+ const user = auth.currentUser;+ if (!user) return false;++ // Force token refresh to get latest claims+ const tokenResult = await user.getIdTokenResult(true);+ return tokenResult.claims.admin === true;+}++// In component+const isAdmin = await checkAdminStatus();+```++**CRITICAL:** Custom claims are cached in the ID token. After setting claims, the user must:+1. Sign out and sign in again, OR+2. Force refresh the token with `getIdTokenResult(true)`++---++## Phone Authentication++```typescript+import {+ signInWithPhoneNumber,+ RecaptchaVerifier,+ ConfirmationResult,+} from 'firebase/auth';+import { auth } from './firebase';++let confirmationResult: ConfirmationResult;++// Step 1: Setup reCAPTCHA (required)+function setupRecaptcha() {+ window.recaptchaVerifier = new RecaptchaVerifier(auth, 'recaptcha-container', {+ size: 'normal',+ callback: () => {+ // reCAPTCHA solved+ },+ });+}++// Step 2: Send verification code+async function sendVerificationCode(phoneNumber: string) {+ const appVerifier = window.recaptchaVerifier;+ confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, appVerifier);+}++// Step 3: Verify code+async function verifyCode(code: string) {+ const result = await confirmationResult.confirm(code);+ return result.user;+}+```++---++## Multi-Factor Authentication (MFA)++```typescript+import {+ multiFactor,+ PhoneAuthProvider,+ PhoneMultiFactorGenerator,+ getMultiFactorResolver,+} from 'firebase/auth';+import { auth } from './firebase';++// Enroll phone as second factor+async function enrollPhoneMFA(phoneNumber: string) {+ const user = auth.currentUser;+ if (!user) throw new Error('Not authenticated');++ const multiFactorSession = await multiFactor(user).getSession();++ const phoneAuthProvider = new PhoneAuthProvider(auth);+ const verificationId = await phoneAuthProvider.verifyPhoneNumber(+ { phoneNumber, session: multiFactorSession },+ window.recaptchaVerifier+ );++ // Return verificationId to complete enrollment after user enters code+ return verificationId;+}++// Complete enrollment+async function completeEnrollment(verificationId: string, verificationCode: string) {+ const user = auth.currentUser;+ if (!user) throw new Error('Not authenticated');++ const credential = PhoneAuthProvider.credential(verificationId, verificationCode);+ const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(credential);++ await multiFactor(user).enroll(multiFactorAssertion, 'Phone Number');+}++// Handle MFA during sign-in+async function handleMFASignIn(error: any) {+ if (error.code !== 'auth/multi-factor-auth-required') {+ throw error;+ }++ const resolver = getMultiFactorResolver(auth, error);+ // Show UI to select MFA method and enter code+ return resolver;+}+```++---++## Protected Routes (Next.js)++### Middleware Protection++```typescript+// middleware.ts+import { NextResponse } from 'next/server';+import type { NextRequest } from 'next/server';++export function middleware(request: NextRequest) {+ const sessionCookie = request.cookies.get('session')?.value;++ // Protect /dashboard routes+ if (request.nextUrl.pathname.startsWith('/dashboard')) {+ if (!sessionCookie) {+ return NextResponse.redirect(new URL('/login', request.url));+ }+ }++ // Redirect authenticated users away from /login+ if (request.nextUrl.pathname === '/login') {+ if (sessionCookie) {+ return NextResponse.redirect(new URL('/dashboard', request.url));+ }+ }++ return NextResponse.next();+}++export const config = {+ matcher: ['/dashboard/:path*', '/login'],+};+```++### Client-Side Route Guard++```typescript+// components/ProtectedRoute.tsx+import { useAuth } from '@/contexts/AuthContext';+import { useRouter } from 'next/navigation';+import { useEffect } from 'react';++export function ProtectedRoute({ children }: { children: React.ReactNode }) {+ const { user, loading } = useAuth();+ const router = useRouter();++ useEffect(() => {+ if (!loading && !user) {+ router.push('/login');+ }+ }, [user, loading, router]);++ if (loading) {+ return <div>Loading...</div>;+ }++ if (!user) {+ return null;+ }++ return <>{children}</>;+}+```++---++## Error Handling++### Common Auth Errors++| Error Code | Description | User-Friendly Message |+|------------|-------------|----------------------|+| `auth/invalid-credential` | Wrong email/password | Invalid email or password |+| `auth/user-not-found` | Email not registered | Invalid email or password |+| `auth/wrong-password` | Incorrect password | Invalid email or password |+| `auth/email-already-in-use` | Email registered | This email is already registered |+| `auth/weak-password` | Password < 6 chars | Password must be at least 6 characters |+| `auth/invalid-email` | Malformed email | Please enter a valid email |+| `auth/user-disabled` | Account disabled | Your account has been disabled |+| `auth/too-many-requests` | Rate limited | Too many attempts. Try again later |+| `auth/popup-closed-by-user` | User closed popup | Sign-in cancelled |+| `auth/popup-blocked` | Browser blocked popup | Please allow popups |+| `auth/requires-recent-login` | Sensitive operation | Please sign in again |+| `auth/network-request-failed` | Network error | Please check your connection |++### Error Handler Utility++```typescript+export function getAuthErrorMessage(error: any): string {+ const errorMessages: Record<string, string> = {+ 'auth/invalid-credential': 'Invalid email or password',+ 'auth/user-not-found': 'Invalid email or password',+ 'auth/wrong-password': 'Invalid email or password',+ 'auth/email-already-in-use': 'This email is already registered',+ 'auth/weak-password': 'Password must be at least 6 characters',+ 'auth/invalid-email': 'Please enter a valid email address',+ 'auth/user-disabled': 'Your account has been disabled',+ 'auth/too-many-requests': 'Too many attempts. Please try again later',+ 'auth/popup-closed-by-user': 'Sign-in was cancelled',+ 'auth/network-request-failed': 'Network error. Please check your connection',+ };++ return errorMessages[error.code] || 'An unexpected error occurred';+}+```++---++## Known Issues Prevention++This skill prevents **12** documented Firebase Auth errors:++| Issue # | Error/Issue | Description | How to Avoid | Source |+|---------|-------------|-------------|--------------|--------|+| **#1** | `auth/invalid-credential` | Generic error for wrong email/password | Show generic "invalid email or password" message | Common |+| **#2** | `auth/popup-blocked` | Browser blocks OAuth popup | Implement redirect fallback | [Docs](https://firebase.google.com/docs/auth/web/google-signin#redirect-mode) |+| **#3** | `auth/requires-recent-login` | Sensitive operations need fresh login | Re-authenticate before password change, delete | [Docs](https://firebase.google.com/docs/auth/web/manage-users#re-authenticate_a_user) |+| **#4** | Custom claims not updating | Claims cached in ID token | Force token refresh after setting claims | [Docs](https://firebase.google.com/docs/auth/admin/custom-claims) |+| **#5** | Token expiration | ID tokens expire after 1 hour | Always call `getIdToken()` before API calls | Common |+| **#6** | Memory leak from auth listener | Not unsubscribing from `onAuthStateChanged` | Return cleanup function in useEffect | Common |+| **#7** | CORS errors on localhost | Auth domain mismatch | Add localhost to authorized domains in console | Common |+| **#8** | Private key newline issue | Escaped `\n` in env var | Use `.replace(/\\n/g, '\n')` | Common |+| **#9** | Session cookie not persisting | Cookie settings wrong | Set `secure: true`, `sameSite: 'lax'` in production | Common |+| **#10** | OAuth state mismatch | User navigates away during OAuth | Handle `auth/popup-closed-by-user` gracefully | Common |+| **#11** | Rate limiting | Too many auth attempts | Implement exponential backoff | [Docs](https://firebase.google.com/docs/auth/limits) |+| **#12** | Email enumeration | Different errors for existing/non-existing emails | Use same message for both | Security best practice |++---++## Security Best Practices++### Always Do++1. **Use HTTPS in production** - Required for secure cookies+2. **Validate tokens server-side** - Never trust client claims alone+3. **Handle token expiration** - Refresh before API calls+4. **Implement rate limiting** - Prevent brute force attacks+5. **Use same error message** for wrong email/password - Prevent enumeration+6. **Enable email verification** - Verify user owns email+7. **Use session cookies for SSR** - More secure than ID tokens in cookies+8. **Revoke tokens on password change** - Invalidate old sessions++### Never Do++1. **Never expose private key** in client code+2. **Never trust client-provided claims** - Always verify server-side+3. **Never store ID tokens in localStorage** - Use httpOnly cookies+4. **Never disable email enumeration protection** in production+5. **Never skip CORS configuration** for your domains++---++## Firebase CLI Commands++```bash+# Initialize Firebase project+firebase init++# Enable auth emulator+firebase emulators:start --only auth++# Export auth users+firebase auth:export users.json --format=json++# Import auth users+firebase auth:import users.json+```++---++## Package Versions (Verified 2026-01-25)++```json+{+ "dependencies": {+ "firebase": "^12.8.0"+ },+ "devDependencies": {+ "firebase-admin": "^13.6.0"+ }+}+```++---++## Official Documentation++- **Firebase Auth Overview**: https://firebase.google.com/docs/auth+- **Web Get Started**: https://firebase.google.com/docs/auth/web/start+- **Admin Auth**: https://firebase.google.com/docs/auth/admin+- **Custom Claims**: https://firebase.google.com/docs/auth/admin/custom-claims+- **Session Cookies**: https://firebase.google.com/docs/auth/admin/manage-cookies+- **Security Rules**: https://firebase.google.com/docs/rules++---++**Last verified**: 2026-01-25 | **Skill version**: 1.0.0diff --git a/skills/firebase-auth/rules/firebase-auth.md b/skills/firebase-auth/rules/firebase-auth.mdnew file mode 100644index 00000000..a2972c9f--- /dev/null+++ b/skills/firebase-auth/rules/firebase-auth.md@@ -0,0 +1,180 @@+# Firebase Authentication Correction Rules++## SDK Version ([email protected]+)++Use the modular API (v9+), not the namespaced API:++```typescript+// CORRECT - Modular API+import { signInWithEmailAndPassword, createUserWithEmailAndPassword } from 'firebase/auth';+import { auth } from './firebase';++await signInWithEmailAndPassword(auth, email, password);++// WRONG - Namespaced API (deprecated)+import firebase from 'firebase/app';+await firebase.auth().signInWithEmailAndPassword(email, password);+```++## Auth State Listener++Always unsubscribe from `onAuthStateChanged`:++```typescript+// CORRECT - With cleanup+useEffect(() => {+ const unsubscribe = onAuthStateChanged(auth, (user) => {+ setUser(user);+ });+ return () => unsubscribe(); // Cleanup+}, []);++// WRONG - Memory leak+useEffect(() => {+ onAuthStateChanged(auth, (user) => {+ setUser(user);+ });+ // No cleanup!+}, []);+```++## ID Token Handling++Always get fresh token before API calls:++```typescript+// CORRECT - Get fresh token+const token = await user.getIdToken(/* forceRefresh */ true);++// WRONG - Use cached token (may be expired)+const token = await user.getIdToken(); // May return expired token+```++## Error Handling++Use same message for email/password errors (prevent enumeration):++```typescript+// CORRECT - Same message prevents enumeration+case 'auth/user-not-found':+case 'auth/wrong-password':+case 'auth/invalid-credential':+ return 'Invalid email or password';++// WRONG - Reveals which field is wrong+case 'auth/user-not-found':+ return 'Email not found'; // Reveals email doesn't exist+case 'auth/wrong-password':+ return 'Password incorrect'; // Reveals email exists+```++## Custom Claims++Force token refresh after setting claims:++```typescript+// CORRECT - Force refresh to get new claims+await adminAuth.setCustomUserClaims(uid, { admin: true });+// Client side: user must refresh token+const tokenResult = await user.getIdTokenResult(true); // Force refresh++// WRONG - Claims won't be available immediately+await adminAuth.setCustomUserClaims(uid, { admin: true });+// User still has old token without admin claim+```++## OAuth Popup Handling++Handle popup-closed gracefully:++```typescript+// CORRECT - Handle user cancellation+try {+ await signInWithPopup(auth, provider);+} catch (error: any) {+ if (error.code === 'auth/popup-closed-by-user') {+ // User cancelled - not an error+ return;+ }+ throw error;+}++// WRONG - Shows error for user cancellation+try {+ await signInWithPopup(auth, provider);+} catch (error) {+ setError('Sign-in failed'); // Shows error even when user cancelled+}+```++## Session Cookies++Set secure cookie options in production:++```typescript+// CORRECT+cookies.set('session', sessionCookie, {+ httpOnly: true,+ secure: process.env.NODE_ENV === 'production',+ sameSite: 'lax',+ maxAge: expiresIn / 1000,+});++// WRONG - Not secure+cookies.set('session', sessionCookie); // Missing security options+```++## Private Key in Environment++Handle escaped newlines:++```typescript+// CORRECT+privateKey: process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n'),++// WRONG - Will fail with "invalid_grant"+privateKey: process.env.FIREBASE_PRIVATE_KEY,+```++## Admin SDK Initialization++Check if already initialized:++```typescript+// CORRECT - Singleton pattern+import { getApps, initializeApp } from 'firebase-admin/app';++if (!getApps().length) {+ initializeApp(config);+}++// WRONG - May initialize multiple times+initializeApp(config); // Crashes on second import+```++## Token Verification++Always verify tokens server-side:++```typescript+// CORRECT - Server-side verification+const decodedToken = await adminAuth.verifyIdToken(token);+const uid = decodedToken.uid;++// WRONG - Trusting client claims+const claims = JSON.parse(atob(token.split('.')[1])); // Can be forged!+```++## Re-authentication for Sensitive Operations++```typescript+// CORRECT - Re-authenticate before sensitive operations+import { reauthenticateWithCredential, EmailAuthProvider } from 'firebase/auth';++const credential = EmailAuthProvider.credential(email, password);+await reauthenticateWithCredential(user, credential);+await user.delete();++// WRONG - Will throw auth/requires-recent-login+await user.delete(); // May fail if signed in too long ago+```diff --git a/skills/firebase-auth/templates/api-session.ts b/skills/firebase-auth/templates/api-session.tsnew file mode 100644index 00000000..bb4090b3--- /dev/null+++ b/skills/firebase-auth/templates/api-session.ts@@ -0,0 +1,123 @@+// src/app/api/auth/session/route.ts+// API route for managing Firebase session cookies++import { NextResponse } from 'next/server';+import { cookies } from 'next/headers';+import { adminAuth } from '@/lib/firebase-admin';++// Create session cookie from ID token+export async function POST(request: Request) {+ try {+ const { idToken } = await request.json();++ if (!idToken) {+ return NextResponse.json(+ { error: 'ID token required' },+ { status: 400 }+ );+ }++ // Verify the ID token+ const decodedToken = await adminAuth.verifyIdToken(idToken);++ // Check if user is recent (within 5 minutes) for security+ const authTime = decodedToken.auth_time * 1000;+ if (Date.now() - authTime > 5 * 60 * 1000) {+ return NextResponse.json(+ { error: 'Recent sign-in required' },+ { status: 401 }+ );+ }++ // Create session cookie (5 days)+ const expiresIn = 60 * 60 * 24 * 5 * 1000;+ const sessionCookie = await adminAuth.createSessionCookie(idToken, {+ expiresIn,+ });++ // Set cookie+ const cookieStore = await cookies();+ cookieStore.set('session', sessionCookie, {+ httpOnly: true,+ secure: process.env.NODE_ENV === 'production',+ sameSite: 'lax',+ maxAge: expiresIn / 1000,+ path: '/',+ });++ return NextResponse.json({ success: true });+ } catch (error: any) {+ console.error('Session creation error:', error);+ return NextResponse.json(+ { error: 'Failed to create session' },+ { status: 401 }+ );+ }+}++// Delete session cookie (sign out)+export async function DELETE() {+ try {+ const cookieStore = await cookies();+ const sessionCookie = cookieStore.get('session')?.value;++ if (sessionCookie) {+ // Verify and revoke refresh tokens+ try {+ const decodedClaims = await adminAuth.verifySessionCookie(sessionCookie);+ await adminAuth.revokeRefreshTokens(decodedClaims.uid);+ } catch {+ // Session might be invalid, continue with deletion+ }+ }++ // Clear cookie+ cookieStore.delete('session');++ return NextResponse.json({ success: true });+ } catch (error: any) {+ console.error('Session deletion error:', error);+ return NextResponse.json(+ { error: 'Failed to delete session' },+ { status: 500 }+ );+ }+}++// Verify session cookie+export async function GET() {+ try {+ const cookieStore = await cookies();+ const sessionCookie = cookieStore.get('session')?.value;++ if (!sessionCookie) {+ return NextResponse.json(+ { authenticated: false },+ { status: 401 }+ );+ }++ // Verify session cookie and check if revoked+ const decodedClaims = await adminAuth.verifySessionCookie(+ sessionCookie,+ true // Check if revoked+ );++ return NextResponse.json({+ authenticated: true,+ uid: decodedClaims.uid,+ email: decodedClaims.email,+ emailVerified: decodedClaims.email_verified,+ claims: {+ admin: decodedClaims.admin || false,+ role: decodedClaims.role || 'user',+ },+ });+ } catch (error: any) {+ console.error('Session verification error:', error);+ return NextResponse.json(+ { authenticated: false },+ { status: 401 }+ );+ }+}diff --git a/skills/firebase-auth/templates/auth-context.tsx b/skills/firebase-auth/templates/auth-context.tsxnew file mode 100644index 00000000..b60b575a--- /dev/null+++ b/skills/firebase-auth/templates/auth-context.tsx@@ -0,0 +1,170 @@+// src/contexts/AuthContext.tsx+// Complete Firebase Auth Context with TypeScript++'use client';++import {+ createContext,+ useContext,+ useEffect,+ useState,+ ReactNode,+ useCallback,+} from 'react';+import {+ User,+ onAuthStateChanged,+ signInWithEmailAndPassword,+ createUserWithEmailAndPassword,+ signOut as firebaseSignOut,+ signInWithPopup,+ GoogleAuthProvider,+ sendPasswordResetEmail,+ updateProfile,+ sendEmailVerification,+} from 'firebase/auth';+import { auth } from '@/lib/firebase';++interface AuthContextType {+ user: User | null;+ loading: boolean;+ error: string | null;+ signIn: (email: string, password: string) => Promise<void>;+ signUp: (email: string, password: string, displayName: string) => Promise<void>;+ signOut: () => Promise<void>;+ signInWithGoogle: () => Promise<void>;+ resetPassword: (email: string) => Promise<void>;+ clearError: () => void;+}++const AuthContext = createContext<AuthContextType | undefined>(undefined);++const googleProvider = new GoogleAuthProvider();+googleProvider.addScope('email');+googleProvider.addScope('profile');++function getAuthErrorMessage(code: string): string {+ const messages: Record<string, string> = {+ 'auth/invalid-credential': 'Invalid email or password',+ 'auth/user-not-found': 'Invalid email or password',+ 'auth/wrong-password': 'Invalid email or password',+ 'auth/email-already-in-use': 'This email is already registered',+ 'auth/weak-password': 'Password must be at least 6 characters',+ 'auth/invalid-email': 'Please enter a valid email address',+ 'auth/user-disabled': 'Your account has been disabled',+ 'auth/too-many-requests': 'Too many attempts. Please try again later',+ 'auth/popup-closed-by-user': 'Sign-in was cancelled',+ 'auth/popup-blocked': 'Please allow popups for this site',+ 'auth/network-request-failed': 'Network error. Please check your connection',+ };+ return messages[code] || 'An unexpected error occurred';+}++export function AuthProvider({ children }: { children: ReactNode }) {+ const [user, setUser] = useState<User | null>(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ const unsubscribe = onAuthStateChanged(auth, (user) => {+ setUser(user);+ setLoading(false);+ });++ return () => unsubscribe();+ }, []);++ const clearError = useCallback(() => {+ setError(null);+ }, []);++ const signIn = useCallback(async (email: string, password: string) => {+ try {+ setError(null);+ await signInWithEmailAndPassword(auth, email, password);+ } catch (err: any) {+ const message = getAuthErrorMessage(err.code);+ setError(message);+ throw new Error(message);+ }+ }, []);++ const signUp = useCallback(+ async (email: string, password: string, displayName: string) => {+ try {+ setError(null);+ const userCredential = await createUserWithEmailAndPassword(+ auth,+ email,+ password+ );+ await updateProfile(userCredential.user, { displayName });+ await sendEmailVerification(userCredential.user);+ } catch (err: any) {+ const message = getAuthErrorMessage(err.code);+ setError(message);+ throw new Error(message);+ }+ },+ []+ );++ const signOut = useCallback(async () => {+ try {+ setError(null);+ await firebaseSignOut(auth);+ } catch (err: any) {+ const message = getAuthErrorMessage(err.code);+ setError(message);+ throw new Error(message);+ }+ }, []);++ const signInWithGoogle = useCallback(async () => {+ try {+ setError(null);+ await signInWithPopup(auth, googleProvider);+ } catch (err: any) {+ if (err.code === 'auth/popup-closed-by-user') {+ // User cancelled - not an error+ return;+ }+ const message = getAuthErrorMessage(err.code);+ setError(message);+ throw new Error(message);+ }+ }, []);++ const resetPassword = useCallback(async (email: string) => {+ try {+ setError(null);+ await sendPasswordResetEmail(auth, email);+ } catch (err: any) {+ const message = getAuthErrorMessage(err.code);+ setError(message);+ throw new Error(message);+ }+ }, []);++ const value: AuthContextType = {+ user,+ loading,+ error,+ signIn,+ signUp,+ signOut,+ signInWithGoogle,+ resetPassword,+ clearError,+ };++ return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;+}++export function useAuth() {+ const context = useContext(AuthContext);+ if (context === undefined) {+ throw new Error('useAuth must be used within an AuthProvider');+ }+ return context;+}diff --git a/skills/firebase-auth/templates/middleware.ts b/skills/firebase-auth/templates/middleware.tsnew file mode 100644index 00000000..4f2479b2--- /dev/null+++ b/skills/firebase-auth/templates/middleware.ts@@ -0,0 +1,52 @@+// middleware.ts+// Next.js middleware for Firebase Auth with session cookies++import { NextResponse } from 'next/server';+import type { NextRequest } from 'next/server';++// Routes that require authentication+const protectedRoutes = ['/dashboard', '/profile', '/settings'];++// Routes only accessible to non-authenticated users+const authRoutes = ['/login', '/register', '/forgot-password'];++export function middleware(request: NextRequest) {+ const { pathname } = request.nextUrl;+ const sessionCookie = request.cookies.get('session')?.value;++ // Check if route requires authentication+ const isProtectedRoute = protectedRoutes.some((route) =>+ pathname.startsWith(route)+ );++ // Check if route is for non-authenticated users only+ const isAuthRoute = authRoutes.some((route) => pathname.startsWith(route));++ // Redirect unauthenticated users away from protected routes+ if (isProtectedRoute && !sessionCookie) {+ const loginUrl = new URL('/login', request.url);+ loginUrl.searchParams.set('redirect', pathname);+ return NextResponse.redirect(loginUrl);+ }++ // Redirect authenticated users away from auth routes+ if (isAuthRoute && sessionCookie) {+ return NextResponse.redirect(new URL('/dashboard', request.url));+ }++ return NextResponse.next();+}++export const config = {+ matcher: [+ /*+ * Match all request paths except:+ * - api routes+ * - _next/static (static files)+ * - _next/image (image optimization files)+ * - favicon.ico+ * - public files (public folder)+ */+ '/((?!api|_next/static|_next/image|favicon.ico|public).*)',+ ],+};diff --git a/skills/firebase-auth/templates/protected-route.tsx b/skills/firebase-auth/templates/protected-route.tsxnew file mode 100644index 00000000..54ba396f--- /dev/null+++ b/skills/firebase-auth/templates/protected-route.tsx@@ -0,0 +1,67 @@+// src/components/ProtectedRoute.tsx+// Client-side route protection++'use client';++import { useEffect } from 'react';+import { useRouter } from 'next/navigation';+import { useAuth } from '@/contexts/AuthContext';++interface ProtectedRouteProps {+ children: React.ReactNode;+ requireEmailVerified?: boolean;+ requireAdmin?: boolean;+ fallbackUrl?: string;+}++export function ProtectedRoute({+ children,+ requireEmailVerified = false,+ requireAdmin = false,+ fallbackUrl = '/login',+}: ProtectedRouteProps) {+ const { user, loading } = useAuth();+ const router = useRouter();++ useEffect(() => {+ if (loading) return;++ if (!user) {+ router.push(fallbackUrl);+ return;+ }++ if (requireEmailVerified && !user.emailVerified) {+ router.push('/verify-email');+ return;+ }++ // For admin check, you'd need to verify custom claims+ // This is a simplified example+ if (requireAdmin) {+ user.getIdTokenResult().then((tokenResult) => {+ if (!tokenResult.claims.admin) {+ router.push('/unauthorized');+ }+ });+ }+ }, [user, loading, router, requireEmailVerified, requireAdmin, fallbackUrl]);++ if (loading) {+ return (+ <div className="flex items-center justify-center min-h-screen">+ <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900" />+ </div>+ );+ }++ if (!user) {+ return null;+ }++ if (requireEmailVerified && !user.emailVerified) {+ return null;+ }++ return <>{children}</>;+}diff --git a/skills/firebase-firestore/README.md b/skills/firebase-firestore/README.mdnew file mode 100644index 00000000..be80098f--- /dev/null+++ b/skills/firebase-firestore/README.md@@ -0,0 +1,75 @@+# Firebase Firestore Skill++Production-tested skill for building applications with Firebase Firestore NoSQL database.++## Auto-Trigger Keywords++This skill activates when Claude detects these keywords:++### Technology Keywords+- firebase, firestore, firebase firestore+- firebase database, firebase db+- firebase-admin, firebase admin sdk+- firebase client sdk, firebase web sdk+- cloud firestore, google firestore++### Operation Keywords+- firebase collection, firebase document+- firebase query, firestore query+- firebase real-time, real-time listener+- onSnapshot, firebase listener+- firebase security rules, firestore rules+- firebase indexes, composite index+- collection group query+- firebase batch, writeBatch+- firebase transaction, runTransaction+- firebase offline, offline persistence++### Error Keywords+- permission-denied firebase+- firestore permission denied+- failed-precondition index+- firebase index missing+- resource-exhausted firestore+- firebase quota exceeded+- firestore invalid query+- firebase offline error+- firebase listener memory leak++### Framework Keywords+- react firebase, next.js firebase+- firebase typescript, firebase types+- firebase modular api, firebase v9+- firebase server side, firebase ssr++## What This Skill Covers++- Client SDK setup (modular v9+ API)+- Admin SDK setup for server-side+- CRUD operations and queries+- Real-time listeners with proper cleanup+- Compound queries and pagination+- Batch writes and transactions+- Security rules best practices+- Composite and collection group indexes+- Offline persistence configuration+- Data modeling patterns+- Error handling and common issues++## When to Use This Skill++Use when:+- Setting up Firestore in a new project+- Writing Firestore queries and operations+- Implementing real-time data sync+- Creating or debugging security rules+- Optimizing query performance with indexes+- Handling offline/online state+- Migrating from older Firebase SDK versions++## Related Skills++- `firebase-auth` - Firebase Authentication+- `firebase-storage` - Firebase Cloud Storage+- `cloudflare-d1` - Alternative: Edge SQLite database+- `neon-vercel-postgres` - Alternative: Serverless PostgreSQLdiff --git a/skills/firebase-firestore/SKILL.md b/skills/firebase-firestore/SKILL.mdnew file mode 100644index 00000000..661be712--- /dev/null+++ b/skills/firebase-firestore/SKILL.md@@ -0,0 +1,731 @@+---+name: firebase-firestore+description: |+ Build with Firestore NoSQL database - real-time sync, offline support, and scalable document storage. Use when: creating collections, querying documents, setting up security rules, handling real-time listeners, or troubleshooting permission-denied, quota exceeded, invalid query, or offline persistence errors. Prevents 10 documented errors.+user-invocable: true+---++# Firebase Firestore Database++**Status**: Production Ready+**Last Updated**: 2026-01-25+**Dependencies**: None (standalone skill)+**Latest Versions**: [email protected], [email protected]++---++## Quick Start (5 Minutes)++### 1. Install Firebase SDK++```bash+# Client SDK (web/mobile)+npm install firebase++# Admin SDK (server/backend)+npm install firebase-admin+```++### 2. Initialize Firebase (Client)++```typescript+// src/lib/firebase.ts+import { initializeApp } from 'firebase/app';+import { getFirestore } from 'firebase/firestore';++const firebaseConfig = {+ apiKey: process.env.FIREBASE_API_KEY,+ authDomain: process.env.FIREBASE_AUTH_DOMAIN,+ projectId: process.env.FIREBASE_PROJECT_ID,+ storageBucket: process.env.FIREBASE_STORAGE_BUCKET,+ messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,+ appId: process.env.FIREBASE_APP_ID,+};++const app = initializeApp(firebaseConfig);+export const db = getFirestore(app);+```++### 3. Initialize Firebase Admin (Server)++```typescript+// src/lib/firebase-admin.ts+import { initializeApp, cert, getApps } from 'firebase-admin/app';+import { getFirestore } from 'firebase-admin/firestore';++// Initialize only once+if (!getApps().length) {+ initializeApp({+ credential: cert({+ projectId: process.env.FIREBASE_PROJECT_ID,+ clientEmail: process.env.FIREBASE_CLIENT_EMAIL,+ // Replace escaped newlines in private key+ privateKey: process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n'),+ }),+ });+}++export const adminDb = getFirestore();+```++**CRITICAL:**+- Never expose `FIREBASE_PRIVATE_KEY` in client code+- Use Admin SDK for server-side operations (bypasses security rules)+- Use Client SDK for authenticated user operations++---++## Core Operations++### Document CRUD (Client SDK - Modular v9+)++```typescript+import {+ collection,+ doc,+ addDoc,+ getDoc,+ getDocs,+ setDoc,+ updateDoc,+ deleteDoc,+ query,+ where,+ orderBy,+ limit,+ serverTimestamp,+ Timestamp,+} from 'firebase/firestore';+import { db } from './firebase';++// CREATE - Auto-generated ID+const docRef = await addDoc(collection(db, 'users'), {+ name: 'John Doe',+ email: '[email protected]',+ createdAt: serverTimestamp(),+});+console.log('Created document with ID:', docRef.id);++// CREATE - Specific ID+await setDoc(doc(db, 'users', 'user-123'), {+ name: 'Jane Doe',+ email: '[email protected]',+ createdAt: serverTimestamp(),+});++// READ - Single document+const docSnap = await getDoc(doc(db, 'users', 'user-123'));+if (docSnap.exists()) {+ console.log('Document data:', docSnap.data());+} else {+ console.log('No such document!');+}++// READ - Collection with query+const q = query(+ collection(db, 'users'),+ where('email', '==', '[email protected]'),+ orderBy('createdAt', 'desc'),+ limit(10)+);+const querySnapshot = await getDocs(q);+querySnapshot.forEach((doc) => {+ console.log(doc.id, ' => ', doc.data());+});++// UPDATE - Merge fields (doesn't overwrite entire document)+await updateDoc(doc(db, 'users', 'user-123'), {+ name: 'Jane Smith',+ updatedAt: serverTimestamp(),+});++// UPDATE - Set with merge (creates if doesn't exist)+await setDoc(doc(db, 'users', 'user-123'), {+ lastLogin: serverTimestamp(),+}, { merge: true });++// DELETE+await deleteDoc(doc(db, 'users', 'user-123'));+```++### Document CRUD (Admin SDK)++```typescript+import { adminDb } from './firebase-admin';+import { FieldValue, Timestamp } from 'firebase-admin/firestore';++// CREATE+const docRef = await adminDb.collection('users').add({+ name: 'John Doe',+ createdAt: FieldValue.serverTimestamp(),+});++// CREATE with specific ID+await adminDb.collection('users').doc('user-123').set({+ name: 'Jane Doe',+ createdAt: FieldValue.serverTimestamp(),+});++// READ+const doc = await adminDb.collection('users').doc('user-123').get();+if (doc.exists) {+ console.log('Document data:', doc.data());+}++// READ with query+const snapshot = await adminDb+ .collection('users')+ .where('email', '==', '[email protected]')+ .orderBy('createdAt', 'desc')+ .limit(10)+ .get();++snapshot.forEach((doc) => {+ console.log(doc.id, '=>', doc.data());+});++// UPDATE+await adminDb.collection('users').doc('user-123').update({+ name: 'Jane Smith',+ updatedAt: FieldValue.serverTimestamp(),+});++// DELETE+await adminDb.collection('users').doc('user-123').delete();+```++---++## Real-Time Listeners (Client SDK)++```typescript+import { onSnapshot, query, where, collection, doc } from 'firebase/firestore';+import { db } from './firebase';++// Listen to single document+const unsubscribe = onSnapshot(doc(db, 'users', 'user-123'), (doc) => {+ if (doc.exists()) {+ console.log('Current data:', doc.data());+ }+});++// Listen to collection with query+const q = query(+ collection(db, 'messages'),+ where('roomId', '==', 'room-123'),+ orderBy('createdAt', 'desc'),+ limit(50)+);++const unsubscribeMessages = onSnapshot(q, (querySnapshot) => {+ const messages: Message[] = [];+ querySnapshot.forEach((doc) => {+ messages.push({ id: doc.id, ...doc.data() } as Message);+ });+ // Update UI with messages+ setMessages(messages);+});++// Handle errors+const unsubscribeWithError = onSnapshot(+ doc(db, 'users', 'user-123'),+ (doc) => {+ // Handle updates+ },+ (error) => {+ console.error('Listener error:', error);+ // Handle permission denied, etc.+ }+);++// IMPORTANT: Unsubscribe when done (React useEffect cleanup)+useEffect(() => {+ const unsubscribe = onSnapshot(/* ... */);+ return () => unsubscribe();+}, []);+```++**CRITICAL:**+- Always unsubscribe from listeners to prevent memory leaks+- Listeners count against your concurrent connection limit+- Each listener is a WebSocket connection++---++## Query Patterns++### Compound Queries++```typescript+import { query, where, orderBy, limit, startAfter, collection } from 'firebase/firestore';++// Multiple where clauses (requires composite index)+const q = query(+ collection(db, 'products'),+ where('category', '==', 'electronics'),+ where('price', '<=', 1000),+ orderBy('price', 'asc')+);++// Range query (only one field can have inequality)+const rangeQuery = query(+ collection(db, 'events'),+ where('date', '>=', new Date('2025-01-01')),+ where('date', '<=', new Date('2025-12-31')),+ orderBy('date', 'asc')+);++// Array contains+const arrayQuery = query(+ collection(db, 'posts'),+ where('tags', 'array-contains', 'firebase')+);++// Array contains any (max 30 values)+const arrayAnyQuery = query(+ collection(db, 'posts'),+ where('tags', 'array-contains-any', ['firebase', 'google', 'cloud'])+);++// In query (max 30 values)+const inQuery = query(+ collection(db, 'users'),+ where('status', 'in', ['active', 'pending'])+);++// Not in query (max 10 values)+const notInQuery = query(+ collection(db, 'users'),+ where('status', 'not-in', ['banned', 'deleted'])+);+```++### Pagination with Cursors++```typescript+import { query, orderBy, limit, startAfter, getDocs, collection, DocumentSnapshot } from 'firebase/firestore';++let lastVisible: DocumentSnapshot | null = null;++async function getNextPage() {+ let q = query(+ collection(db, 'posts'),+ orderBy('createdAt', 'desc'),+ limit(10)+ );++ if (lastVisible) {+ q = query(q, startAfter(lastVisible));+ }++ const snapshot = await getDocs(q);++ // Save last document for next page+ lastVisible = snapshot.docs[snapshot.docs.length - 1] || null;++ return snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));+}+```++### Collection Group Queries++```typescript+import { collectionGroup, query, where, getDocs } from 'firebase/firestore';++// Query across all subcollections named 'comments'+// Structure: posts/{postId}/comments/{commentId}+const q = query(+ collectionGroup(db, 'comments'),+ where('authorId', '==', 'user-123')+);++const snapshot = await getDocs(q);+// Returns all comments by user-123 across all posts+```++**CRITICAL:** Collection group queries require an index. Create in Firebase Console or deploy via `firestore.indexes.json`.++---++## Batch Operations & Transactions++### Batch Writes (Up to 500 operations)++```typescript+import { writeBatch, doc, collection, serverTimestamp } from 'firebase/firestore';+import { db } from './firebase';++const batch = writeBatch(db);++// Add multiple documents+const usersRef = collection(db, 'users');+batch.set(doc(usersRef), { name: 'User 1', createdAt: serverTimestamp() });+batch.set(doc(usersRef), { name: 'User 2', createdAt: serverTimestamp() });++// Update existing document+batch.update(doc(db, 'counters', 'users'), { total: 100 });++// Delete document+batch.delete(doc(db, 'temp', 'old-doc'));++// Commit all operations atomically+await batch.commit();+```++### Transactions (Read then Write)++```typescript+import { runTransaction, doc, increment } from 'firebase/firestore';+import { db } from './firebase';++// Transfer credits between users+async function transferCredits(fromId: string, toId: string, amount: number) {+ await runTransaction(db, async (transaction) => {+ const fromRef = doc(db, 'users', fromId);+ const toRef = doc(db, 'users', toId);++ const fromDoc = await transaction.get(fromRef);+ const toDoc = await transaction.get(toRef);++ if (!fromDoc.exists() || !toDoc.exists()) {+ throw new Error('User not found');+ }++ const fromCredits = fromDoc.data().credits;+ if (fromCredits < amount) {+ throw new Error('Insufficient credits');+ }++ transaction.update(fromRef, { credits: fromCredits - amount });+ transaction.update(toRef, { credits: increment(amount) });+ });+}+```++**CRITICAL:**+- Transactions can fail and retry automatically (up to 5 times)+- Don't perform side effects inside transaction (may run multiple times)+- All reads must come before writes in a transaction++---++## Security Rules++### Basic Rules Structure++```javascript+// firestore.rules+rules_version = '2';++service cloud.firestore {+ match /databases/{database}/documents {++ // Helper functions+ function isAuthenticated() {+ return request.auth != null;+ }++ function isOwner(userId) {+ return request.auth.uid == userId;+ }++ function isValidUser() {+ return request.resource.data.keys().hasAll(['name', 'email'])+ && request.resource.data.name is string+ && request.resource.data.email is string;+ }++ // Users collection+ match /users/{userId} {+ allow read: if isAuthenticated();+ allow create: if isAuthenticated() && isOwner(userId) && isValidUser();+ allow update: if isOwner(userId);+ allow delete: if isOwner(userId);+ }++ // Posts collection with subcollections+ match /posts/{postId} {+ allow read: if resource.data.published == true || isOwner(resource.data.authorId);+ allow create: if isAuthenticated() && request.resource.data.authorId == request.auth.uid;+ allow update, delete: if isOwner(resource.data.authorId);++ // Comments subcollection+ match /comments/{commentId} {+ allow read: if true;+ allow create: if isAuthenticated();+ allow update, delete: if isOwner(resource.data.authorId);+ }+ }++ // Admin-only collection+ match /admin/{document=**} {+ allow read, write: if request.auth.token.admin == true;+ }+ }+}+```++### Deploy Rules++```bash+# Deploy rules+firebase deploy --only firestore:rules++# Deploy rules and indexes+firebase deploy --only firestore+```++---++## Indexes++### Composite Indexes (firestore.indexes.json)++```json+{+ "indexes": [+ {+ "collectionGroup": "products",+ "queryScope": "COLLECTION",+ "fields": [+ { "fieldPath": "category", "order": "ASCENDING" },+ { "fieldPath": "price", "order": "ASCENDING" }+ ]+ },+ {+ "collectionGroup": "comments",+ "queryScope": "COLLECTION_GROUP",+ "fields": [+ { "fieldPath": "authorId", "order": "ASCENDING" },+ { "fieldPath": "createdAt", "order": "DESCENDING" }+ ]+ }+ ],+ "fieldOverrides": []+}+```++```bash+# Deploy indexes+firebase deploy --only firestore:indexes+```++**CRITICAL:**+- Firestore auto-creates single-field indexes+- Composite indexes must be created manually or via error link+- Collection group queries always require an index++---++## Offline Persistence++### Enable Offline Support (Web)++```typescript+import { initializeFirestore, persistentLocalCache, persistentMultipleTabManager } from 'firebase/firestore';+import { app } from './firebase';++// Enable multi-tab offline persistence+const db = initializeFirestore(app, {+ localCache: persistentLocalCache({+ tabManager: persistentMultipleTabManager()+ })+});++// OR: Enable single-tab persistence (simpler)+import { enableIndexedDbPersistence, getFirestore } from 'firebase/firestore';++const db = getFirestore(app);+enableIndexedDbPersistence(db).catch((err) => {+ if (err.code === 'failed-precondition') {+ // Multiple tabs open, persistence can only be enabled in one tab+ console.warn('Persistence failed: multiple tabs open');+ } else if (err.code === 'unimplemented') {+ // Browser doesn't support persistence+ console.warn('Persistence not supported');+ }+});+```++### Handle Offline State++```typescript+import { onSnapshot, doc, SnapshotMetadata } from 'firebase/firestore';++onSnapshot(doc(db, 'users', 'user-123'), (doc) => {+ const source = doc.metadata.fromCache ? 'local cache' : 'server';+ console.log(`Data came from ${source}`);++ if (doc.metadata.hasPendingWrites) {+ console.log('Local changes pending sync');+ }+});+```++---++## Data Modeling Best Practices++### Denormalization for Read Performance++```typescript+// Instead of joining users and posts...+// Store author info directly in post document++// posts/{postId}+{+ title: 'My Post',+ content: '...',+ authorId: 'user-123',+ // Denormalized author data for fast reads+ author: {+ name: 'John Doe',+ avatarUrl: 'https://...'+ },+ createdAt: Timestamp+}+```++### Subcollections vs Root Collections++```typescript+// Subcollections: Good for parent-child relationships+// posts/{postId}/comments/{commentId}+// - Easy to query all comments for a post+// - Deleting post doesn't auto-delete comments (use Cloud Functions)++// Root collections: Good for cross-cutting queries+// comments (with postId field)+// - Easy to query all comments by a user across posts+// - Requires manual data consistency+```++### Counter Pattern (High-Write Scenarios)++```typescript+// Direct increment (low traffic)+await updateDoc(doc(db, 'posts', postId), {+ viewCount: increment(1)+});++// Distributed counter (high traffic - 1000+ writes/sec)+// Use Cloud Functions to aggregate shard counts+// counters/{counterId}/shards/{shardId}+```++---++## Error Handling++### Common Errors and Solutions++| Error | Cause | Solution |+|-------|-------|----------|+| `permission-denied` | Security rules blocking access | Check rules, ensure user authenticated |+| `not-found` | Document doesn't exist | Use `exists()` check before accessing data |+| `already-exists` | Document with ID already exists | Use `setDoc` with merge or generate new ID |+| `resource-exhausted` | Quota exceeded | Upgrade plan or optimize queries |+| `failed-precondition` | Index missing for query | Create composite index (link in error) |+| `unavailable` | Service temporarily unavailable | Implement retry with backoff |+| `invalid-argument` | Invalid query combination | Check query constraints (see below) |+| `deadline-exceeded` | Operation timeout | Reduce data size or paginate |++### Query Constraints++```typescript+// INVALID: Multiple inequality filters on different fields+query(collection(db, 'posts'),+ where('date', '>', startDate),+ where('likes', '>', 100) // ERROR: Can't use inequality on second field+);++// VALID: Use range on one field, equality on others+query(collection(db, 'posts'),+ where('category', '==', 'tech'),+ where('date', '>', startDate)+);++// INVALID: orderBy field different from inequality field+query(collection(db, 'posts'),+ where('date', '>', startDate),+ orderBy('likes') // ERROR: Must orderBy('date') first+);++// VALID: orderBy inequality field first+query(collection(db, 'posts'),+ where('date', '>', startDate),+ orderBy('date'),+ orderBy('likes')+);+```++---++## Known Issues Prevention++This skill prevents **10** documented Firestore errors:++| Issue # | Error/Issue | Description | How to Avoid | Source |+|---------|-------------|-------------|--------------|--------|+| **#1** | `permission-denied` | Security rules blocking operation | Test rules in Firebase Console emulator first | Common |+| **#2** | `failed-precondition` (index) | Composite index missing | Click error link to create index, or define in firestore.indexes.json | Common |+| **#3** | Invalid query combination | Multiple inequality filters | Use inequality on one field only, equality on others | [Docs](https://firebase.google.com/docs/firestore/query-data/queries#query_limitations) |+| **#4** | Memory leak from listeners | Not unsubscribing from onSnapshot | Always call unsubscribe in cleanup (useEffect return) | Common |+| **#5** | Offline persistence conflict | Multiple tabs with persistence | Use `persistentMultipleTabManager()` or handle error | [Docs](https://firebase.google.com/docs/firestore/manage-data/enable-offline) |+| **#6** | Transaction side effects | Side effects run multiple times | Never perform side effects inside runTransaction | [Docs](https://firebase.google.com/docs/firestore/manage-data/transactions) |+| **#7** | Batch limit exceeded | More than 500 operations | Split into multiple batches | [Docs](https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes) |+| **#8** | `resource-exhausted` | Quota limits hit | Implement pagination, reduce reads, use caching | Common |+| **#9** | Private key newline issue | `\\n` not converted in env var | Use `.replace(/\\n/g, '\n')` on private key | Common |+| **#10** | Collection group query fails | Missing collection group index | Create index with `queryScope: COLLECTION_GROUP` | [Docs](https://firebase.google.com/docs/firestore/query-data/queries#collection-group-query) |++---++## Firebase CLI Commands++```bash+# Initialize Firestore+firebase init firestore++# Start emulators+firebase emulators:start --only firestore++# Deploy rules and indexes+firebase deploy --only firestore++# Export data (for backup)+gcloud firestore export gs://your-bucket/backups/$(date +%Y%m%d)++# Import data+gcloud firestore import gs://your-bucket/backups/20250125+```++---++## Package Versions (Verified 2026-01-25)++```json+{+ "dependencies": {+ "firebase": "^12.8.0"+ },+ "devDependencies": {+ "firebase-admin": "^13.6.0"+ }+}+```++---++## Official Documentation++- **Firestore Overview**: https://firebase.google.com/docs/firestore+- **Get Started**: https://firebase.google.com/docs/firestore/quickstart+- **Data Model**: https://firebase.google.com/docs/firestore/data-model+- **Security Rules**: https://firebase.google.com/docs/firestore/security/get-started+- **Query Data**: https://firebase.google.com/docs/firestore/query-data/queries+- **Manage Data**: https://firebase.google.com/docs/firestore/manage-data/add-data+- **Offline Data**: https://firebase.google.com/docs/firestore/manage-data/enable-offline++---++**Last verified**: 2026-01-25 | **Skill version**: 1.0.0diff --git a/skills/firebase-firestore/rules/firebase-firestore.md b/skills/firebase-firestore/rules/firebase-firestore.mdnew file mode 100644index 00000000..8c0ac55e--- /dev/null+++ b/skills/firebase-firestore/rules/firebase-firestore.md@@ -0,0 +1,185 @@+# Firebase Firestore Correction Rules++## SDK Version ([email protected]+)++Use the modular API (v9+), not the namespaced API:++```typescript+// CORRECT - Modular API+import { collection, doc, getDoc, getDocs, addDoc, setDoc, updateDoc, deleteDoc } from 'firebase/firestore';+import { db } from './firebase';++const docRef = doc(db, 'users', 'user-123');+const docSnap = await getDoc(docRef);++// WRONG - Namespaced API (deprecated)+import firebase from 'firebase/app';+const docSnap = await firebase.firestore().collection('users').doc('user-123').get();+```++## Query Patterns++### Inequality Filters++Only one field can have inequality operators (`<`, `<=`, `>`, `>=`, `!=`):++```typescript+// CORRECT - Single inequality field+query(collection(db, 'posts'),+ where('category', '==', 'tech'),+ where('date', '>=', startDate)+);++// WRONG - Multiple inequality fields+query(collection(db, 'posts'),+ where('date', '>=', startDate),+ where('likes', '>', 100) // ERROR+);+```++### OrderBy with Inequality++Must `orderBy` the inequality field first:++```typescript+// CORRECT+query(collection(db, 'posts'),+ where('date', '>=', startDate),+ orderBy('date'), // Must come first+ orderBy('likes')+);++// WRONG+query(collection(db, 'posts'),+ where('date', '>=', startDate),+ orderBy('likes') // ERROR: must orderBy('date') first+);+```++## Real-Time Listeners++Always unsubscribe from listeners:++```typescript+// CORRECT - With cleanup+useEffect(() => {+ const unsubscribe = onSnapshot(doc(db, 'users', userId), (doc) => {+ setUser(doc.data());+ });+ return () => unsubscribe(); // Cleanup on unmount+}, [userId]);++// WRONG - Memory leak+useEffect(() => {+ onSnapshot(doc(db, 'users', userId), (doc) => {+ setUser(doc.data());+ });+ // No cleanup!+}, [userId]);+```++## Timestamps++Use `serverTimestamp()` for consistent timestamps:++```typescript+import { serverTimestamp } from 'firebase/firestore';++// CORRECT+await addDoc(collection(db, 'posts'), {+ title: 'My Post',+ createdAt: serverTimestamp(),+});++// WRONG - Client time can be inaccurate+await addDoc(collection(db, 'posts'), {+ title: 'My Post',+ createdAt: new Date(),+});+```++## Batch Operations++Batches are limited to 500 operations:++```typescript+// CORRECT - Split large batches+const items = [...]; // 1000 items+const batchSize = 500;++for (let i = 0; i < items.length; i += batchSize) {+ const batch = writeBatch(db);+ items.slice(i, i + batchSize).forEach(item => {+ batch.set(doc(collection(db, 'items')), item);+ });+ await batch.commit();+}++// WRONG - Exceeds limit+const batch = writeBatch(db);+items.forEach(item => batch.set(...)); // 1000+ items - will fail+await batch.commit();+```++## Transaction Rules++No side effects inside transactions (they may retry):++```typescript+// CORRECT - Side effects outside+await runTransaction(db, async (transaction) => {+ const doc = await transaction.get(docRef);+ transaction.update(docRef, { count: doc.data().count + 1 });+});+await sendNotification(); // Side effect outside++// WRONG - Side effect inside+await runTransaction(db, async (transaction) => {+ const doc = await transaction.get(docRef);+ transaction.update(docRef, { count: doc.data().count + 1 });+ await sendNotification(); // May run multiple times!+});+```++## Admin SDK Private Key++Handle escaped newlines in environment variables:++```typescript+// CORRECT+privateKey: process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n'),++// WRONG - Will fail with "invalid_grant" or "no credentials"+privateKey: process.env.FIREBASE_PRIVATE_KEY,+```++## Document References++Use `doc()` for references, `collection()` for queries:++```typescript+// CORRECT+const userRef = doc(db, 'users', 'user-123');+const usersCollection = collection(db, 'users');++// WRONG - Path confusion+const userRef = collection(db, 'users', 'user-123'); // This is a subcollection path!+```++## Null vs Undefined++Use `null` for missing optional fields, never `undefined`:++```typescript+// CORRECT+await setDoc(docRef, {+ name: 'John',+ bio: userBio || null,+});++// WRONG - Undefined causes issues+await setDoc(docRef, {+ name: 'John',+ bio: undefined, // May cause unexpected behavior+});+```diff --git a/skills/firebase-firestore/templates/firebase-admin.ts b/skills/firebase-firestore/templates/firebase-admin.tsnew file mode 100644index 00000000..f9246337--- /dev/null+++ b/skills/firebase-firestore/templates/firebase-admin.ts@@ -0,0 +1,26 @@+// src/lib/firebase-admin.ts+// Firebase Admin SDK configuration (server-side only)++import { initializeApp, cert, getApps, App } from 'firebase-admin/app';+import { getFirestore, Firestore } from 'firebase-admin/firestore';++let app: App;+let adminDb: Firestore;++// Initialize only once (important for serverless environments)+if (!getApps().length) {+ app = initializeApp({+ credential: cert({+ projectId: process.env.FIREBASE_PROJECT_ID,+ clientEmail: process.env.FIREBASE_CLIENT_EMAIL,+ // CRITICAL: Replace escaped newlines in private key+ privateKey: process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n'),+ }),+ });+} else {+ app = getApps()[0];+}++adminDb = getFirestore(app);++export { app, adminDb };diff --git a/skills/firebase-firestore/templates/firebase-client.ts b/skills/firebase-firestore/templates/firebase-client.tsnew file mode 100644index 00000000..2f2b30c4--- /dev/null+++ b/skills/firebase-firestore/templates/firebase-client.ts@@ -0,0 +1,40 @@+// src/lib/firebase.ts+// Firebase Client SDK configuration (web/mobile)++import { initializeApp, getApps, FirebaseApp } from 'firebase/app';+import {+ getFirestore,+ initializeFirestore,+ persistentLocalCache,+ persistentMultipleTabManager,+ Firestore,+} from 'firebase/firestore';++const firebaseConfig = {+ apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,+ authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,+ projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,+ storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,+ messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,+ appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,+};++// Initialize Firebase (singleton pattern)+let app: FirebaseApp;+let db: Firestore;++if (!getApps().length) {+ app = initializeApp(firebaseConfig);++ // Initialize Firestore with offline persistence (multi-tab support)+ db = initializeFirestore(app, {+ localCache: persistentLocalCache({+ tabManager: persistentMultipleTabManager(),+ }),+ });+} else {+ app = getApps()[0];+ db = getFirestore(app);+}++export { app, db };diff --git a/skills/firebase-firestore/templates/firestore.indexes.json b/skills/firebase-firestore/templates/firestore.indexes.jsonnew file mode 100644index 00000000..d18acb2c--- /dev/null+++ b/skills/firebase-firestore/templates/firestore.indexes.json@@ -0,0 +1,38 @@+{+ "indexes": [+ {+ "collectionGroup": "posts",+ "queryScope": "COLLECTION",+ "fields": [+ { "fieldPath": "published", "order": "ASCENDING" },+ { "fieldPath": "createdAt", "order": "DESCENDING" }+ ]+ },+ {+ "collectionGroup": "posts",+ "queryScope": "COLLECTION",+ "fields": [+ { "fieldPath": "authorId", "order": "ASCENDING" },+ { "fieldPath": "createdAt", "order": "DESCENDING" }+ ]+ },+ {+ "collectionGroup": "posts",+ "queryScope": "COLLECTION",+ "fields": [+ { "fieldPath": "category", "order": "ASCENDING" },+ { "fieldPath": "published", "order": "ASCENDING" },+ { "fieldPath": "createdAt", "order": "DESCENDING" }+ ]+ },+ {+ "collectionGroup": "comments",+ "queryScope": "COLLECTION_GROUP",+ "fields": [+ { "fieldPath": "authorId", "order": "ASCENDING" },+ { "fieldPath": "createdAt", "order": "DESCENDING" }+ ]+ }+ ],+ "fieldOverrides": []+}diff --git a/skills/firebase-firestore/templates/firestore.rules b/skills/firebase-firestore/templates/firestore.rulesnew file mode 100644index 00000000..d69bbcb1--- /dev/null+++ b/skills/firebase-firestore/templates/firestore.rules@@ -0,0 +1,114 @@+rules_version = '2';++service cloud.firestore {+ match /databases/{database}/documents {++ // ============================================+ // HELPER FUNCTIONS+ // ============================================++ // Check if user is authenticated+ function isAuthenticated() {+ return request.auth != null;+ }++ // Check if user owns the resource+ function isOwner(userId) {+ return request.auth.uid == userId;+ }++ // Check if user has admin custom claim+ function isAdmin() {+ return request.auth.token.admin == true;+ }++ // Validate required fields exist+ function hasRequiredFields(fields) {+ return request.resource.data.keys().hasAll(fields);+ }++ // Validate field is a string+ function isString(field) {+ return request.resource.data[field] is string;+ }++ // Validate field is a timestamp+ function isTimestamp(field) {+ return request.resource.data[field] is timestamp;+ }++ // ============================================+ // USERS COLLECTION+ // ============================================++ match /users/{userId} {+ // Anyone authenticated can read user profiles+ allow read: if isAuthenticated();++ // Users can only create their own profile+ allow create: if isAuthenticated()+ && isOwner(userId)+ && hasRequiredFields(['name', 'email', 'createdAt'])+ && isString('name')+ && isString('email');++ // Users can only update their own profile+ allow update: if isOwner(userId)+ && !request.resource.data.diff(resource.data).affectedKeys().hasAny(['email', 'createdAt']);++ // Users can only delete their own profile+ allow delete: if isOwner(userId);+ }++ // ============================================+ // POSTS COLLECTION+ // ============================================++ match /posts/{postId} {+ // Public posts readable by anyone, private posts only by author+ allow read: if resource.data.published == true+ || (isAuthenticated() && isOwner(resource.data.authorId));++ // Authenticated users can create posts (must be their own)+ allow create: if isAuthenticated()+ && request.resource.data.authorId == request.auth.uid+ && hasRequiredFields(['title', 'content', 'authorId', 'createdAt']);++ // Only author can update/delete+ allow update, delete: if isAuthenticated()+ && isOwner(resource.data.authorId);++ // Comments subcollection+ match /comments/{commentId} {+ // Anyone can read comments on published posts+ allow read: if get(/databases/$(database)/documents/posts/$(postId)).data.published == true+ || isAuthenticated();++ // Authenticated users can create comments+ allow create: if isAuthenticated()+ && request.resource.data.authorId == request.auth.uid;++ // Only comment author can update/delete+ allow update, delete: if isAuthenticated()+ && isOwner(resource.data.authorId);+ }+ }++ // ============================================+ // ADMIN-ONLY COLLECTION+ // ============================================++ match /admin/{document=**} {+ allow read, write: if isAdmin();+ }++ // ============================================+ // DEFAULT DENY+ // ============================================++ // Deny all other access by default+ match /{document=**} {+ allow read, write: if false;+ }+ }+}diff --git a/skills/firebase-storage/README.md b/skills/firebase-storage/README.mdnew file mode 100644index 00000000..9a7c1c87--- /dev/null+++ b/skills/firebase-storage/README.md@@ -0,0 +1,77 @@+# Firebase Cloud Storage Skill++Production-tested skill for implementing file uploads, downloads, and storage management with Firebase Cloud Storage.++## Auto-Trigger Keywords++This skill activates when Claude detects these keywords:++### Technology Keywords+- firebase storage, firebase cloud storage+- firebase file upload, firebase upload+- firebase file download, firebase download+- firebase bucket, storage bucket+- firebase-admin storage+- firebase signed url++### Operation Keywords+- uploadBytes, uploadBytesResumable+- getDownloadURL, downloadURL+- uploadString, base64 upload+- listAll, list files+- deleteObject, delete file+- getMetadata, updateMetadata+- ref, storageRef+- firebase upload progress+- firebase resumable upload++### Error Keywords+- storage/unauthorized+- storage/object-not-found+- storage/quota-exceeded+- storage/canceled+- firebase storage cors+- firebase upload failed+- firebase download error+- storage permission denied++### Framework Keywords+- react firebase storage+- next.js firebase upload+- firebase image upload+- firebase file picker+- firebase storage rules+- firebase storage security++## What This Skill Covers++- Client SDK file uploads+- Upload progress tracking+- Resumable uploads for large files+- File downloads and URLs+- Metadata management+- Server-side operations (Admin SDK)+- Signed URLs for temporary access+- Security rules+- CORS configuration+- React upload components+- Error handling patterns++## When to Use This Skill++Use when:+- Uploading images or files to Firebase+- Implementing file pickers and upload components+- Generating download URLs+- Setting up storage security rules+- Configuring CORS for web uploads+- Managing file metadata+- Implementing profile picture uploads+- Handling large file uploads with progress++## Related Skills++- `firebase-firestore` - Firebase Firestore database+- `firebase-auth` - Firebase Authentication+- `cloudflare-r2` - Alternative: Cloudflare R2 storage+- `vercel-blob` - Alternative: Vercel Blob storagediff --git a/skills/firebase-storage/SKILL.md b/skills/firebase-storage/SKILL.mdnew file mode 100644index 00000000..f1b4944a--- /dev/null+++ b/skills/firebase-storage/SKILL.md@@ -0,0 +1,793 @@+---+name: firebase-storage+description: |+ Build with Firebase Cloud Storage - file uploads, downloads, and secure access. Use when: uploading images/files, generating download URLs, implementing file pickers, setting up storage security rules, or troubleshooting storage/unauthorized, cors errors, quota exceeded, or upload failed errors. Prevents 9 documented errors.+user-invocable: true+---++# Firebase Cloud Storage++**Status**: Production Ready+**Last Updated**: 2026-01-25+**Dependencies**: None (standalone skill)+**Latest Versions**: [email protected], [email protected]++---++## Quick Start (5 Minutes)++### 1. Initialize Firebase Storage (Client)++```typescript+// src/lib/firebase.ts+import { initializeApp } from 'firebase/app';+import { getStorage } from 'firebase/storage';++const firebaseConfig = {+ apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,+ authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,+ projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,+ storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,+ // ... other config+};++const app = initializeApp(firebaseConfig);+export const storage = getStorage(app);+```++### 2. Initialize Firebase Admin Storage (Server)++```typescript+// src/lib/firebase-admin.ts+import { initializeApp, cert, getApps } from 'firebase-admin/app';+import { getStorage } from 'firebase-admin/storage';++if (!getApps().length) {+ initializeApp({+ credential: cert({+ projectId: process.env.FIREBASE_PROJECT_ID,+ clientEmail: process.env.FIREBASE_CLIENT_EMAIL,+ privateKey: process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n'),+ }),+ storageBucket: process.env.FIREBASE_STORAGE_BUCKET,+ });+}++export const adminStorage = getStorage().bucket();+```++---++## File Upload (Client SDK)++### Basic Upload++```typescript+import { ref, uploadBytes, getDownloadURL } from 'firebase/storage';+import { storage } from './firebase';++async function uploadFile(file: File, path: string): Promise<string> {+ const storageRef = ref(storage, path);++ // Upload file+ const snapshot = await uploadBytes(storageRef, file);++ // Get download URL+ const downloadURL = await getDownloadURL(snapshot.ref);++ return downloadURL;+}++// Usage+const url = await uploadFile(file, `uploads/${userId}/${file.name}`);+```++### Upload with Progress++```typescript+import { ref, uploadBytesResumable, getDownloadURL, UploadTask } from 'firebase/storage';+import { storage } from './firebase';++function uploadFileWithProgress(+ file: File,+ path: string,+ onProgress: (progress: number) => void+): Promise<string> {+ return new Promise((resolve, reject) => {+ const storageRef = ref(storage, path);+ const uploadTask = uploadBytesResumable(storageRef, file);++ uploadTask.on(+ 'state_changed',+ (snapshot) => {+ const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;+ onProgress(progress);+ },+ (error) => {+ reject(error);+ },+ async () => {+ const downloadURL = await getDownloadURL(uploadTask.snapshot.ref);+ resolve(downloadURL);+ }+ );+ });+}++// Usage with React state+const [progress, setProgress] = useState(0);+const url = await uploadFileWithProgress(file, path, setProgress);+```++### Upload with Metadata++```typescript+import { ref, uploadBytes, getDownloadURL, UploadMetadata } from 'firebase/storage';+import { storage } from './firebase';++async function uploadWithMetadata(file: File, path: string) {+ const storageRef = ref(storage, path);++ const metadata: UploadMetadata = {+ contentType: file.type,+ customMetadata: {+ uploadedBy: userId,+ originalName: file.name,+ uploadTime: new Date().toISOString(),+ },+ };++ const snapshot = await uploadBytes(storageRef, file, metadata);+ const downloadURL = await getDownloadURL(snapshot.ref);++ return { downloadURL, metadata: snapshot.metadata };+}+```++### Upload from Data URL / Base64++```typescript+import { ref, uploadString, getDownloadURL } from 'firebase/storage';+import { storage } from './firebase';++// Upload base64 string+async function uploadBase64(base64String: string, path: string) {+ const storageRef = ref(storage, path);++ // For data URL (includes prefix like "data:image/png;base64,")+ const snapshot = await uploadString(storageRef, base64String, 'data_url');++ // For raw base64 (no prefix)+ // const snapshot = await uploadString(storageRef, base64String, 'base64');++ const downloadURL = await getDownloadURL(snapshot.ref);+ return downloadURL;+}+```++---++## File Download++### Get Download URL++```typescript+import { ref, getDownloadURL } from 'firebase/storage';+import { storage } from './firebase';++async function getFileURL(path: string): Promise<string> {+ const storageRef = ref(storage, path);+ const downloadURL = await getDownloadURL(storageRef);+ return downloadURL;+}+```++### Download File as Blob++```typescript+import { ref, getBlob } from 'firebase/storage';+import { storage } from './firebase';++async function downloadFile(path: string): Promise<Blob> {+ const storageRef = ref(storage, path);+ const blob = await getBlob(storageRef);+ return blob;+}++// Trigger browser download+async function downloadAndSave(path: string, filename: string) {+ const blob = await downloadFile(path);+ const url = URL.createObjectURL(blob);++ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ a.click();++ URL.revokeObjectURL(url);+}+```++### Get File Metadata++```typescript+import { ref, getMetadata } from 'firebase/storage';+import { storage } from './firebase';++async function getFileMetadata(path: string) {+ const storageRef = ref(storage, path);+ const metadata = await getMetadata(storageRef);++ return {+ name: metadata.name,+ size: metadata.size,+ contentType: metadata.contentType,+ created: metadata.timeCreated,+ updated: metadata.updated,+ customMetadata: metadata.customMetadata,+ };+}+```++---++## File Management++### Delete File++```typescript+import { ref, deleteObject } from 'firebase/storage';+import { storage } from './firebase';++async function deleteFile(path: string): Promise<void> {+ const storageRef = ref(storage, path);+ await deleteObject(storageRef);+}+```++### List Files in Directory++```typescript+import { ref, listAll, list, getDownloadURL } from 'firebase/storage';+import { storage } from './firebase';++// List all files in a directory+async function listAllFiles(directoryPath: string) {+ const storageRef = ref(storage, directoryPath);+ const result = await listAll(storageRef);++ const files = await Promise.all(+ result.items.map(async (itemRef) => ({+ name: itemRef.name,+ fullPath: itemRef.fullPath,+ downloadURL: await getDownloadURL(itemRef),+ }))+ );++ const folders = result.prefixes.map((folderRef) => ({+ name: folderRef.name,+ fullPath: folderRef.fullPath,+ }));++ return { files, folders };+}++// Paginated list (for large directories)+async function listFilesPaginated(directoryPath: string, pageSize = 100) {+ const storageRef = ref(storage, directoryPath);+ const result = await list(storageRef, { maxResults: pageSize });++ // Get next page+ if (result.nextPageToken) {+ const nextPage = await list(storageRef, {+ maxResults: pageSize,+ pageToken: result.nextPageToken,+ });+ }++ return result;+}+```++### Update Metadata++```typescript+import { ref, updateMetadata } from 'firebase/storage';+import { storage } from './firebase';++async function updateFileMetadata(path: string, newMetadata: object) {+ const storageRef = ref(storage, path);+ const updatedMetadata = await updateMetadata(storageRef, {+ customMetadata: newMetadata,+ });+ return updatedMetadata;+}+```++---++## Server-Side Operations (Admin SDK)++### Upload from Server++```typescript+import { adminStorage } from './firebase-admin';++async function uploadFromServer(+ buffer: Buffer,+ destination: string,+ contentType: string+) {+ const file = adminStorage.file(destination);++ await file.save(buffer, {+ contentType,+ metadata: {+ metadata: {+ uploadedBy: 'server',+ uploadTime: new Date().toISOString(),+ },+ },+ });++ // Make file publicly accessible (if needed)+ await file.makePublic();++ // Get public URL+ const publicUrl = `https://storage.googleapis.com/${adminStorage.name}/${destination}`;++ return publicUrl;+}+```++### Generate Signed URL++```typescript+import { adminStorage } from './firebase-admin';++async function generateSignedUrl(+ path: string,+ expiresInMinutes = 60+): Promise<string> {+ const file = adminStorage.file(path);++ const [signedUrl] = await file.getSignedUrl({+ action: 'read',+ expires: Date.now() + expiresInMinutes * 60 * 1000,+ });++ return signedUrl;+}++// For uploads (write access)+async function generateUploadUrl(path: string): Promise<string> {+ const file = adminStorage.file(path);++ const [signedUrl] = await file.getSignedUrl({+ action: 'write',+ expires: Date.now() + 15 * 60 * 1000, // 15 minutes+ contentType: 'application/octet-stream',+ });++ return signedUrl;+}+```++### Delete from Server++```typescript+import { adminStorage } from './firebase-admin';++async function deleteFromServer(path: string): Promise<void> {+ const file = adminStorage.file(path);+ await file.delete();+}++// Delete entire directory+async function deleteDirectory(directoryPath: string): Promise<void> {+ await adminStorage.deleteFiles({+ prefix: directoryPath,+ });+}+```++---++## Security Rules++### Basic Rules Structure++```javascript+// storage.rules+rules_version = '2';++service firebase.storage {+ match /b/{bucket}/o {++ // Helper functions+ function isAuthenticated() {+ return request.auth != null;+ }++ function isOwner(userId) {+ return request.auth.uid == userId;+ }++ function isValidImage() {+ return request.resource.contentType.matches('image/.*')+ && request.resource.size < 5 * 1024 * 1024; // 5MB+ }++ function isValidDocument() {+ return request.resource.contentType.matches('application/pdf')+ && request.resource.size < 10 * 1024 * 1024; // 10MB+ }++ // User uploads (private to user)+ match /users/{userId}/{allPaths=**} {+ allow read: if isOwner(userId);+ allow write: if isOwner(userId)+ && (isValidImage() || isValidDocument());+ }++ // Public uploads (anyone can read)+ match /public/{allPaths=**} {+ allow read: if true;+ allow write: if isAuthenticated() && isValidImage();+ }++ // Profile pictures+ match /profiles/{userId}/avatar.{ext} {+ allow read: if true;+ allow write: if isOwner(userId)+ && request.resource.contentType.matches('image/.*')+ && request.resource.size < 2 * 1024 * 1024; // 2MB+ }++ // Deny all other access+ match /{allPaths=**} {+ allow read, write: if false;+ }+ }+}+```++### Deploy Rules++```bash+firebase deploy --only storage+```++---++## CORS Configuration++### Configure CORS (Required for Web)++Create `cors.json`:++```json+[+ {+ "origin": ["https://your-domain.com", "http://localhost:3000"],+ "method": ["GET", "PUT", "POST", "DELETE"],+ "maxAgeSeconds": 3600+ }+]+```++Apply CORS configuration:++```bash+gsutil cors set cors.json gs://your-bucket-name.appspot.com+```++**CRITICAL:** Without CORS configuration, uploads from browsers will fail with CORS errors.++---++## React Components++### File Upload Component++```typescript+// components/FileUpload.tsx+'use client';++import { useState, useRef } from 'react';+import { ref, uploadBytesResumable, getDownloadURL } from 'firebase/storage';+import { storage } from '@/lib/firebase';++interface FileUploadProps {+ path: string;+ onUploadComplete: (url: string) => void;+ accept?: string;+ maxSize?: number; // in bytes+}++export function FileUpload({+ path,+ onUploadComplete,+ accept = 'image/*',+ maxSize = 5 * 1024 * 1024, // 5MB+}: FileUploadProps) {+ const [uploading, setUploading] = useState(false);+ const [progress, setProgress] = useState(0);+ const [error, setError] = useState<string | null>(null);+ const inputRef = useRef<HTMLInputElement>(null);++ const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {+ const file = e.target.files?.[0];+ if (!file) return;++ // Validate file size+ if (file.size > maxSize) {+ setError(`File size must be less than ${maxSize / 1024 / 1024}MB`);+ return;+ }++ setError(null);+ setUploading(true);+ setProgress(0);++ try {+ const storageRef = ref(storage, `${path}/${Date.now()}-${file.name}`);+ const uploadTask = uploadBytesResumable(storageRef, file);++ uploadTask.on(+ 'state_changed',+ (snapshot) => {+ const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;+ setProgress(progress);+ },+ (error) => {+ setError(error.message);+ setUploading(false);+ },+ async () => {+ const downloadURL = await getDownloadURL(uploadTask.snapshot.ref);+ onUploadComplete(downloadURL);+ setUploading(false);+ setProgress(100);+ }+ );+ } catch (err: any) {+ setError(err.message);+ setUploading(false);+ }+ };++ return (+ <div>+ <input+ ref={inputRef}+ type="file"+ accept={accept}+ onChange={handleFileChange}+ disabled={uploading}+ className="hidden"+ />+ <button+ onClick={() => inputRef.current?.click()}+ disabled={uploading}+ className="px-4 py-2 bg-blue-500 text-white rounded disabled:opacity-50"+ >+ {uploading ? `Uploading... ${Math.round(progress)}%` : 'Upload File'}+ </button>+ {error && <p className="text-red-500 mt-2">{error}</p>}+ </div>+ );+}+```++### Image Preview with Upload++```typescript+// components/ImageUpload.tsx+'use client';++import { useState } from 'react';+import { ref, uploadBytesResumable, getDownloadURL } from 'firebase/storage';+import { storage } from '@/lib/firebase';+import Image from 'next/image';++interface ImageUploadProps {+ currentImage?: string;+ path: string;+ onUploadComplete: (url: string) => void;+}++export function ImageUpload({+ currentImage,+ path,+ onUploadComplete,+}: ImageUploadProps) {+ const [preview, setPreview] = useState<string | null>(currentImage || null);+ const [uploading, setUploading] = useState(false);+ const [progress, setProgress] = useState(0);++ const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {+ const file = e.target.files?.[0];+ if (!file) return;++ // Show preview immediately+ const reader = new FileReader();+ reader.onloadend = () => {+ setPreview(reader.result as string);+ };+ reader.readAsDataURL(file);++ // Upload+ setUploading(true);+ const storageRef = ref(storage, `${path}/${Date.now()}-${file.name}`);+ const uploadTask = uploadBytesResumable(storageRef, file);++ uploadTask.on(+ 'state_changed',+ (snapshot) => {+ setProgress((snapshot.bytesTransferred / snapshot.totalBytes) * 100);+ },+ (error) => {+ console.error('Upload error:', error);+ setUploading(false);+ },+ async () => {+ const downloadURL = await getDownloadURL(uploadTask.snapshot.ref);+ onUploadComplete(downloadURL);+ setUploading(false);+ }+ );+ };++ return (+ <div className="relative w-32 h-32">+ {preview ? (+ <Image+ src={preview}+ alt="Preview"+ fill+ className="object-cover rounded-full"+ />+ ) : (+ <div className="w-full h-full bg-gray-200 rounded-full flex items-center justify-center">+ <span className="text-gray-500">No image</span>+ </div>+ )}++ <label className="absolute bottom-0 right-0 bg-blue-500 text-white p-2 rounded-full cursor-pointer">+ <input+ type="file"+ accept="image/*"+ onChange={handleFileChange}+ disabled={uploading}+ className="hidden"+ />+ {uploading ? `${Math.round(progress)}%` : '+'}+ </label>+ </div>+ );+}+```++---++## Error Handling++### Common Storage Errors++| Error Code | Description | Solution |+|------------|-------------|----------|+| `storage/unauthorized` | User not allowed to access | Check security rules, ensure user authenticated |+| `storage/canceled` | Upload/download canceled | Handle gracefully, allow retry |+| `storage/unknown` | Unknown error | Check network, retry with backoff |+| `storage/object-not-found` | File doesn't exist | Verify path, handle missing files |+| `storage/bucket-not-found` | Bucket doesn't exist | Check storageBucket config |+| `storage/quota-exceeded` | Storage quota exceeded | Upgrade plan or delete files |+| `storage/unauthenticated` | User not authenticated | Sign in user first |+| `storage/invalid-checksum` | File corrupted during upload | Retry upload |+| `storage/retry-limit-exceeded` | Too many retries | Check network, try later |++### Error Handler Utility++```typescript+export function getStorageErrorMessage(error: any): string {+ const messages: Record<string, string> = {+ 'storage/unauthorized': 'You do not have permission to access this file',+ 'storage/canceled': 'Upload was canceled',+ 'storage/object-not-found': 'File not found',+ 'storage/quota-exceeded': 'Storage quota exceeded',+ 'storage/unauthenticated': 'Please sign in to upload files',+ 'storage/invalid-checksum': 'Upload failed. Please try again',+ 'storage/retry-limit-exceeded': 'Upload failed after multiple retries',+ };++ return messages[error.code] || 'An unexpected error occurred';+}+```++---++## Known Issues Prevention++This skill prevents **9** documented Firebase Storage errors:++| Issue # | Error/Issue | Description | How to Avoid | Source |+|---------|-------------|-------------|--------------|--------|+| **#1** | `storage/unauthorized` | Security rules blocking access | Test rules, ensure user authenticated | Common |+| **#2** | CORS errors | Browser blocked cross-origin request | Configure CORS with `gsutil cors set` | [Docs](https://firebase.google.com/docs/storage/web/download-files#cors_configuration) |+| **#3** | Large file timeout | Upload times out | Use `uploadBytesResumable` for large files | Common |+| **#4** | Memory issues | Loading large file into memory | Stream large files, use signed URLs | Common |+| **#5** | Missing content type | File served with wrong MIME type | Always set `contentType` in metadata | Common |+| **#6** | URL expiration | Download URL stops working | Regenerate URLs, use signed URLs for temp access | Common |+| **#7** | `storage/quota-exceeded` | Free tier limit reached | Monitor usage, upgrade plan | Common |+| **#8** | Private key newline issue | Admin SDK fails to initialize | Use `.replace(/\\n/g, '\n')` | Common |+| **#9** | Duplicate uploads | Same file uploaded multiple times | Add timestamp/UUID to filename | Best practice |++---++## Best Practices++### Always Do++1. **Validate file type and size** before upload+2. **Use `uploadBytesResumable`** for large files (supports pause/resume)+3. **Set content type** in metadata+4. **Use unique filenames** (add timestamp or UUID)+5. **Handle upload errors** gracefully with retry+6. **Unsubscribe from upload tasks** on component unmount+7. **Configure CORS** for web applications+8. **Use security rules** to protect files+9. **Generate signed URLs** for temporary access++### Never Do++1. **Never upload without authentication** (unless truly public)+2. **Never trust client-provided file extension** (check content type)+3. **Never store sensitive data** without encryption+4. **Never expose Admin SDK** in client code+5. **Never allow unlimited file sizes** (DoS risk)++---++## Firebase CLI Commands++```bash+# Initialize Storage+firebase init storage++# Deploy security rules+firebase deploy --only storage++# Start emulator+firebase emulators:start --only storage+```++---++## Package Versions (Verified 2026-01-25)++```json+{+ "dependencies": {+ "firebase": "^12.8.0"+ },+ "devDependencies": {+ "firebase-admin": "^13.6.0"+ }+}+```++---++## Official Documentation++- **Storage Overview**: https://firebase.google.com/docs/storage+- **Web Get Started**: https://firebase.google.com/docs/storage/web/start+- **Upload Files**: https://firebase.google.com/docs/storage/web/upload-files+- **Download Files**: https://firebase.google.com/docs/storage/web/download-files+- **Security Rules**: https://firebase.google.com/docs/storage/security+- **Admin SDK**: https://firebase.google.com/docs/storage/admin/start++---++**Last verified**: 2026-01-25 | **Skill version**: 1.0.0diff --git a/skills/firebase-storage/rules/firebase-storage.md b/skills/firebase-storage/rules/firebase-storage.mdnew file mode 100644index 00000000..361b714f--- /dev/null+++ b/skills/firebase-storage/rules/firebase-storage.md@@ -0,0 +1,180 @@+# Firebase Storage Correction Rules++## SDK Version ([email protected]+)++Use the modular API (v9+), not the namespaced API:++```typescript+// CORRECT - Modular API+import { ref, uploadBytes, getDownloadURL } from 'firebase/storage';+import { storage } from './firebase';++const storageRef = ref(storage, 'path/to/file');+await uploadBytes(storageRef, file);++// WRONG - Namespaced API (deprecated)+import firebase from 'firebase/app';+const storageRef = firebase.storage().ref('path/to/file');+await storageRef.put(file);+```++## Upload with Progress++Use `uploadBytesResumable` for progress tracking:++```typescript+// CORRECT - Resumable upload with progress+import { uploadBytesResumable } from 'firebase/storage';++const uploadTask = uploadBytesResumable(storageRef, file);+uploadTask.on('state_changed', (snapshot) => {+ const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;+});++// WRONG - No progress tracking+import { uploadBytes } from 'firebase/storage';+await uploadBytes(storageRef, file); // Can't track progress+```++## Always Set Content Type++```typescript+// CORRECT - Explicit content type+await uploadBytes(storageRef, file, {+ contentType: file.type,+});++// WRONG - Content type may be wrong+await uploadBytes(storageRef, file); // May serve with incorrect MIME+```++## Unique Filenames++```typescript+// CORRECT - Unique filename prevents collisions+const filename = `${Date.now()}-${file.name}`;+const storageRef = ref(storage, `uploads/${filename}`);++// WRONG - May overwrite existing files+const storageRef = ref(storage, `uploads/${file.name}`);+```++## Handle Upload Errors++```typescript+// CORRECT - Full error handling+uploadTask.on('state_changed',+ (snapshot) => { /* progress */ },+ (error) => {+ // Handle errors+ switch (error.code) {+ case 'storage/unauthorized':+ console.error('Not authorized');+ break;+ case 'storage/canceled':+ console.error('Upload canceled');+ break;+ default:+ console.error('Upload failed:', error);+ }+ },+ () => { /* complete */ }+);++// WRONG - No error handling+uploadTask.on('state_changed', (snapshot) => { /* progress only */ });+```++## Cancel Upload on Unmount++```typescript+// CORRECT - Cancel on unmount+useEffect(() => {+ const uploadTask = uploadBytesResumable(storageRef, file);+ // ... setup listeners++ return () => {+ uploadTask.cancel(); // Clean up on unmount+ };+}, []);++// WRONG - Upload continues after unmount+useEffect(() => {+ uploadBytesResumable(storageRef, file);+ // No cleanup!+}, []);+```++## CORS Configuration++```bash+# MUST configure CORS for web uploads+gsutil cors set cors.json gs://your-bucket.appspot.com++# WRONG - Skipping CORS results in browser errors+# No cors.json = CORS errors in browser+```++## Validate Before Upload++```typescript+// CORRECT - Validate client-side (defense in depth)+const MAX_SIZE = 5 * 1024 * 1024; // 5MB+const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp'];++if (file.size > MAX_SIZE) {+ throw new Error('File too large');+}+if (!ALLOWED_TYPES.includes(file.type)) {+ throw new Error('Invalid file type');+}++// Still validate in security rules too!++// WRONG - Trust client blindly+await uploadBytes(storageRef, file); // No validation+```++## Download URL Caching++```typescript+// CORRECT - Download URLs don't expire (but can be revoked)+const downloadURL = await getDownloadURL(storageRef);+// Store this URL - it's permanent unless security rules change++// For temporary access, use signed URLs (Admin SDK)+const [signedUrl] = await adminStorage.file(path).getSignedUrl({+ action: 'read',+ expires: Date.now() + 60 * 60 * 1000, // 1 hour+});+```++## Security Rules - Size Limits++```javascript+// CORRECT - Enforce size limits in rules+match /uploads/{fileName} {+ allow write: if request.resource.size < 5 * 1024 * 1024; // 5MB+}++// WRONG - No size limit (DoS vulnerability)+match /uploads/{fileName} {+ allow write: if true;+}+```++## Admin SDK Storage Bucket++```typescript+// CORRECT - Specify bucket in config+initializeApp({+ credential: cert(serviceAccount),+ storageBucket: 'your-project.appspot.com', // Required!+});++// WRONG - Missing bucket+initializeApp({+ credential: cert(serviceAccount),+ // storageBucket missing - getStorage().bucket() will fail+});+```diff --git a/skills/firebase-storage/templates/cors.json b/skills/firebase-storage/templates/cors.jsonnew file mode 100644index 00000000..3d37a79d--- /dev/null+++ b/skills/firebase-storage/templates/cors.json@@ -0,0 +1,19 @@+[+ {+ "origin": [+ "https://your-domain.com",+ "https://www.your-domain.com",+ "http://localhost:3000",+ "http://localhost:5173"+ ],+ "method": ["GET", "PUT", "POST", "DELETE", "HEAD"],+ "maxAgeSeconds": 3600,+ "responseHeader": [+ "Content-Type",+ "Content-Length",+ "Content-Encoding",+ "Content-Disposition",+ "Cache-Control"+ ]+ }+]diff --git a/skills/firebase-storage/templates/storage.rules b/skills/firebase-storage/templates/storage.rulesnew file mode 100644index 00000000..a7c368c6--- /dev/null+++ b/skills/firebase-storage/templates/storage.rules@@ -0,0 +1,111 @@+rules_version = '2';++service firebase.storage {+ match /b/{bucket}/o {++ // ============================================+ // HELPER FUNCTIONS+ // ============================================++ // Check if user is authenticated+ function isAuthenticated() {+ return request.auth != null;+ }++ // Check if user owns the resource+ function isOwner(userId) {+ return request.auth.uid == userId;+ }++ // Validate image file+ function isValidImage() {+ return request.resource.contentType.matches('image/(png|jpeg|gif|webp)')+ && request.resource.size < 5 * 1024 * 1024; // 5MB max+ }++ // Validate document file+ function isValidDocument() {+ return request.resource.contentType.matches('application/(pdf|msword|vnd.openxmlformats-officedocument.*)')+ && request.resource.size < 10 * 1024 * 1024; // 10MB max+ }++ // Validate any allowed file type+ function isValidFile() {+ return request.resource.size < 25 * 1024 * 1024; // 25MB max+ }++ // ============================================+ // USER PRIVATE FILES+ // ============================================++ // User's private files - only owner can access+ match /users/{userId}/private/{allPaths=**} {+ allow read: if isOwner(userId);+ allow write: if isOwner(userId) && isValidFile();+ }++ // ============================================+ // USER PUBLIC FILES+ // ============================================++ // User's public files - anyone can read, owner can write+ match /users/{userId}/public/{allPaths=**} {+ allow read: if true;+ allow write: if isOwner(userId) && isValidFile();+ }++ // ============================================+ // PROFILE PICTURES+ // ============================================++ // Profile avatars - public read, owner write+ match /profiles/{userId}/avatar.{ext} {+ allow read: if true;+ allow write: if isOwner(userId)+ && request.resource.contentType.matches('image/(png|jpeg|gif|webp)')+ && request.resource.size < 2 * 1024 * 1024; // 2MB max+ }++ // ============================================+ // PUBLIC UPLOADS+ // ============================================++ // Public images - authenticated users can upload+ match /public/images/{fileName} {+ allow read: if true;+ allow create: if isAuthenticated() && isValidImage();+ allow delete: if false; // Only admin can delete public images+ }++ // ============================================+ // SHARED CONTENT+ // ============================================++ // Shared files with explicit permissions stored in Firestore+ // (You'd check Firestore for permission in a Cloud Function)+ match /shared/{fileId} {+ allow read: if isAuthenticated();+ allow write: if isAuthenticated() && isValidFile();+ }++ // ============================================+ // TEMP UPLOADS+ // ============================================++ // Temporary uploads (should be cleaned up by Cloud Function)+ match /temp/{userId}/{fileName} {+ allow read: if isOwner(userId);+ allow create: if isOwner(userId) && isValidFile();+ allow delete: if isOwner(userId);+ }++ // ============================================+ // DEFAULT DENY+ // ============================================++ // Deny all other access by default+ match /{allPaths=**} {+ allow read, write: if false;+ }+ }+}