diff --git a/transformations/README.md b/transformations/README.md new file mode 100644 index 00000000..d9b1bae1 --- /dev/null +++ b/transformations/README.md @@ -0,0 +1,52 @@ +# Skills Transformations + +This directory contains transformed versions of the skills repository, tailored for specific platforms or use cases. + +## Intended Structure + +Each transformation should live in its own subdirectory under `transformations/`. + +```text +transformations/ +├── README.md # This file +└── [transformation-name]/ + ├── generator/ # Scripts and guides for generation + │ ├── generate_android_skills.js + │ └── generate-android-studio-bundle.md + └── skills/ # The generated content + ├── firebase-basics + └── ... +``` + +### Components + +- **`generator/`**: Contains the scripts used to perform the transformation and any guides or prompts used to polish the output. +- **`skills/`**: Contains the actual generated skills. + +## How to Install a Transformation + +To install a specific transformation using the `skills` CLI, use the GitHub URL pointing to the generated skills directory: + +```bash +npx skills add https://github.com/firebase/agent-skills/tree/main/transformations/[transformation-name]/skills +``` + +For example, to install the Android Studio bundle: + +```bash +npx skills add https://github.com/firebase/agent-skills/tree/main/transformations/android-studio/skills +``` + +To add a new transformation, follow these steps: + +1. **Create a new directory** under `transformations/` named after your platform or use case (e.g., `transformations/vscode`). +2. **Create a `generator/` directory** inside your new directory. +3. **Add your transformation script** to the `generator/` directory. This script should read from the root `skills/` directory and write to `transformations/[transformation-name]/skills/`. +4. **Add a guide or prompt** (e.g., `README.md` or `guide.md`) in the `generator/` directory explaining how to run the transformation and any manual cleanup required. +5. **Update the root documentation** if necessary to point to the new transformation. + +### Best Practices + +- **Automate as much as possible**: Use scripts to filter files and clean up links. +- **Use LLMs for semantic cleanup**: If regex is insufficient to fix grammar after link removal, provide a prompt for an LLM to do the final polish. +- **Keep source of truth in root `skills/`**: All transformations should be derivable from the core content in the root `skills/` directory. diff --git a/transformations/android-studio/generator/generate-android-studio-bundle.md b/transformations/android-studio/generator/generate-android-studio-bundle.md new file mode 100644 index 00000000..4a3a8279 --- /dev/null +++ b/transformations/android-studio/generator/generate-android-studio-bundle.md @@ -0,0 +1,46 @@ +# Generating Android Studio Skills + +This guide covers the process of generating a limited version of Firebase skills for Android Studio. The generated content lives in the `transformations/android-studio/skills/` directory on the `main` branch. + +## Instructions for the Operator (Human or AI) + +Follow these steps to regenerate the bundle: + +### 1. Run the Generation Script +Run the following command from the root of the repository: +```bash +node transformations/android-studio/generator/generate_android_skills.js +``` +This will create or update the directory `transformations/android-studio/skills/` with the filtered skills. + +### 2. Clean Up Content with LLM +Use the following prompt with an LLM to clean up the markdown files in `transformations/android-studio/skills/` to remove dangling references and fix grammar. + +#### Prompt for LLM Cleanup +```text +You are an AI assistant helping to create a limited version of Firebase skills for Android Studio. +Your task is to clean up the provided markdown file to make it focused on Android and remove broken links or dangling text left by a filtering process. + +Instructions: +1. Remove any remaining links to files that have been deleted (iOS, Web, Flutter specific files). +2. Remove lines, bullet points, or sections that are exclusively about iOS, Web, or Flutter if they are left empty or dangling after link removal. +3. Rewrite sentences that list multiple platforms to only include Android (and shared platforms like Unity if relevant), ensuring correct grammar. +4. Do NOT remove content that is generic or applicable to all platforms unless it is part of a broken list. +5. Ensure the remaining text is grammatically correct and flows naturally. + +Here is the file content: +[Insert file content here] +``` + +Apply this to all `.md` files in `transformations/android-studio/skills/` that need cleanup (especially `SKILL.md` files). + +### 3. Commit and Push +Commit the changes to your working branch and push them. +```bash +git add transformations/android-studio/skills/ +git commit -m "Update Android Studio skills" +git push +``` + +--- +Note: The script `generate_android_skills.js` and this guide live in `transformations/android-studio/generator/`. The generated content lives in `transformations/android-studio/skills/`. diff --git a/transformations/android-studio/generator/generate_android_skills.js b/transformations/android-studio/generator/generate_android_skills.js new file mode 100644 index 00000000..1139ed50 --- /dev/null +++ b/transformations/android-studio/generator/generate_android_skills.js @@ -0,0 +1,127 @@ +const fs = require('fs'); +const path = require('path'); + +const SOURCE_DIR = path.join(__dirname, '../../../skills'); +const TARGET_DIR = path.join(__dirname, '../skills'); + +const EXCLUDED_SKILLS = [ + 'developing-genkit-dart', + 'developing-genkit-go', + 'developing-genkit-js', + 'developing-genkit-python', + 'xcode-project-setup', + 'firebase-hosting-basics', + 'firebase-app-hosting-basics' +]; + +const EXCLUDED_FILE_PATTERNS = [ + /ios/i, + /web/i, + /flutter/i +]; + +function deleteFolderRecursive(directoryPath) { + if (fs.existsSync(directoryPath)) { + fs.readdirSync(directoryPath).forEach((file, index) => { + const curPath = path.join(directoryPath, file); + if (fs.lstatSync(curPath).isDirectory()) { + deleteFolderRecursive(curPath); + } else { + fs.unlinkSync(curPath); + } + }); + fs.rmdirSync(directoryPath); + } +} + +function copyRecursive(src, dest) { + const exists = fs.existsSync(src); + const stats = exists && fs.statSync(src); + const isDirectory = exists && stats.isDirectory(); + + if (isDirectory) { + if (!fs.existsSync(dest)) { + fs.mkdirSync(dest); + } + fs.readdirSync(src).forEach((childItemName) => { + copyRecursive(path.join(src, childItemName), path.join(dest, childItemName)); + }); + } else { + // Check if file should be excluded + const basename = path.basename(src); + const shouldExclude = EXCLUDED_FILE_PATTERNS.some(pattern => pattern.test(basename)); + + if (!shouldExclude) { + fs.copyFileSync(src, dest); + } + } +} + +function cleanLinks(filePath) { + if (!fs.existsSync(filePath)) return; + let content = fs.readFileSync(filePath, 'utf8'); + + const linkRegex = /\[([^\]]+)\]\(([^)]+)\)/g; + + content = content.replace(linkRegex, (match, label, href) => { + const shouldExclude = EXCLUDED_FILE_PATTERNS.some(pattern => pattern.test(href)); + if (shouldExclude) { + return ''; + } + return match; + }); + + // Clean up double commas, trailing commas in lists + content = content.replace(/,\s*,/g, ','); + content = content.replace(/,\s*or\s*,/g, ' or '); + content = content.replace(/,\s*\]/g, ']'); + content = content.replace(/\[\s*,/g, '['); + + // Clean up empty list items or broken sentences + content = content.replace(/Read\s*,/g, 'Read'); + content = content.replace(/,\s*or\s*$/gm, ''); + content = content.replace(/,\s*$/gm, ''); + content = content.replace(/^\s*-\s*\*\*.*?\*\*:\s*See\s*$/gm, ''); + content = content.replace(/^\s*-\s*\*\*.*?\*\*:\s*$/gm, ''); + content = content.replace(/^\s*[*+-]\s*\*\*(iOS|Web|Flutter)\*\*:\s*$/gmi, ''); + + fs.writeFileSync(filePath, content, 'utf8'); +} + +function processFiles(dir) { + fs.readdirSync(dir).forEach((file) => { + const fullPath = path.join(dir, file); + if (fs.lstatSync(fullPath).isDirectory()) { + processFiles(fullPath); + } else if (path.extname(fullPath) === '.md') { + cleanLinks(fullPath); + } + }); +} + +function main() { + console.log('Generating Android-only skills...'); + + // Clear target dir + deleteFolderRecursive(TARGET_DIR); + fs.mkdirSync(TARGET_DIR, { recursive: true }); + + // Copy skills + fs.readdirSync(SOURCE_DIR).forEach((skill) => { + if (EXCLUDED_SKILLS.includes(skill)) { + console.log(`Skipping skill: ${skill}`); + return; + } + + console.log(`Copying skill: ${skill}`); + copyRecursive(path.join(SOURCE_DIR, skill), path.join(TARGET_DIR, skill)); + }); + + // Process files to clean links + console.log('Cleaning links...'); + processFiles(TARGET_DIR); + + console.log('Done!'); +} + +main(); diff --git a/transformations/android-studio/skills/firebase-ai-logic-basics/SKILL.md b/transformations/android-studio/skills/firebase-ai-logic-basics/SKILL.md new file mode 100644 index 00000000..803dc678 --- /dev/null +++ b/transformations/android-studio/skills/firebase-ai-logic-basics/SKILL.md @@ -0,0 +1,123 @@ +--- +name: firebase-ai-logic-basics +description: Official skill for integrating Firebase AI Logic (Gemini API) into web applications. Covers setup, multimodal inference, structured output, and security. +version: 1.0.1 +--- + +# Firebase AI Logic Basics + +## Overview + +Firebase AI Logic is a product of Firebase that allows developers to add gen AI to their mobile and web apps using client-side SDKs. You can call Gemini models directly from your app without managing a dedicated backend. Firebase AI Logic, which was previously known as "Vertex AI for Firebase", represents the evolution of Google's AI integration platform for mobile and web developers. + +It supports the two Gemini API providers: +- **Gemini Developer API**: It has a free tier ideal for prototyping, and pay-as-you-go for production +- **Vertex AI Gemini API**: Ideal for scale with enterprise-grade production readiness, requires Blaze plan + +Use the Gemini Developer API as a default, and only Vertex AI Gemini API if the application requires it. + +## Setup & Initialization + +### Prerequisites + +- Before starting, ensure you have **Node.js 16+** and npm installed. Install them if they aren’t already available. +- Identify the platform the user is interested in building on prior to starting: Android, iOS, Flutter or Web. +- If their platform is unsupported, Direct the user to Firebase Docs to learn how to set up AI Logic for their application (share this link with the user https://firebase.google.com/docs/ai-logic/get-started) + +### Installation + +The library is part of the standard Firebase Web SDK. + +`npm install -g firebase@latest` + +If you're in a firebase directory (with a firebase.json) the currently selected project will be marked with "current" using this command: + +`npx -y firebase-tools@latest projects:list` + +Ensure there's at least one app associated with the current project + +`npx -y firebase-tools@latest apps:list` + +Initialize AI logic SDK with the init command + +`npx -y firebase-tools@latest init ailogic` + +This will automatically enable the Gemini Developer API in the Firebase console. + +More info in [Firebase AI Logic Getting Started](https://firebase.google.com/docs/ai-logic/get-started.md.txt) + +## Core Capabilities + +### Text-Only Generation + +### Multimodal (Text + Images/Audio/Video/PDF input) + +Firebase AI Logic allows Gemini models to analyze image files directly from your app. This enables features like creating captions, answering questions about images, detecting objects, and categorizing images. Beyond images, Gemini can analyze other media types like audio, video, and PDFs by passing them as inline data with their MIME type. For files larger than 20 megabytes (which can cause HTTP 413 errors as inline data), store them in Cloud Storage for Firebase and pass their URLs to the Gemini Developer API. + +### Chat Session (Multi-turn) + +Maintain history automatically using `startChat`. + +### Streaming Responses + +To improve the user experience by showing partial results as they arrive (like a typing effect), use `generateContentStream` instead of `generateContent` for faster display of results. + +### Generate Images with Nano Banana + +- Start with Gemini for most use cases, and choose Imagen for specialized tasks where image quality and specific styles are critical. (Example: gemini-2.5-flash-image) +- Requires an upgraded Blaze pay-as-you-go billing plan. + +### Search Grounding with the built in googleSearch tool + +## Supported Platforms and Frameworks + +Supported Platforms and Frameworks include Kotlin and Java for Android, Swift for iOS, JavaScript for web apps, Dart for Flutter, and C Sharp for Unity. + +## Advanced Features + +### Structured Output (JSON) + +Enforce a specific JSON schema for the response. + +### On-Device AI (Hybrid) + +Hybrid on-device inference for web apps, where the Firebase Javascript SDK automatically checks for Gemini Nano's availability (after installation) and switches between on-device or cloud-hosted prompt execution. This requires specific steps to enable model usage in the Chrome browser, more info in the [hybrid-on-device-inference documentation](https://firebase.google.com/docs/ai-logic/hybrid-on-device-inference.md.txt). + +## Security & Production + +### App Check + +> [!WARNING] +> **Critical Safety Requirement:** In order to use AI Logic safely, you MUST set up App Check on your app. This prevents unauthorized clients from using your API quota and accessing your backend resources. + +See for setup instructions. + +### Remote Config + +Consider that you do not need to hardcode model names (e.g., `gemini-flash-lite-latest`). Use Firebase Remote Config to update model versions dynamically without deploying new client code. See [Changing model names remotely](https://firebase.google.com/docs/ai-logic/change-model-name-remotely.md.txt) + + +> [!WARNING] +> **CRITICAL: Backend Provisioning Required** +> For all platforms (Flutter, Android, iOS, Web), you MUST run `npx firebase-tools init ailogic` to provision the service. `flutterfire configure` ONLY handles client configuration and does NOT enable the AI service, leading to `PERMISSION_DENIED` errors. +## Initialization Code References + +| Language, Framework, Platform | Gemini API provider | Context URL | +| :---- | :---- | :---- | +| Web Modular API | Gemini Developer API (Developer API) | firebase://docs/ai-logic/get-started | +| iOS (Swift) | Gemini Developer API | | +| Flutter (Dart) | Gemini Developer API | | + +**Always use the most recent version of Gemini (gemini-flash-latest) unless another model is requested by the docs or the user. DO NOT USE gemini-1.5-flash. ** + +## References + + + + + + +[Android (Kotlin) SDK usage patterns](references/usage_patterns_android.md) + + + diff --git a/transformations/android-studio/skills/firebase-ai-logic-basics/references/usage_patterns_android.md b/transformations/android-studio/skills/firebase-ai-logic-basics/references/usage_patterns_android.md new file mode 100644 index 00000000..58828e73 --- /dev/null +++ b/transformations/android-studio/skills/firebase-ai-logic-basics/references/usage_patterns_android.md @@ -0,0 +1,152 @@ +# Firebase AI Logic on Android (Kotlin) + +First, ensure you have initialized the Firebase App (see `firebase-basics` skill). Then, initialize +the AI Logic service as below +### 0. Enable Firebase AI Logic via CLI + +Before adding dependencies in your app, make sure you enable the AI Logic service in your Firebase Project using the Firebase CLI: + +```bash +npx -y firebase-tools@latest init +# When prompted, select 'AI logic' to enable the Gemini API in your project. +``` + + --- + +### 1. Add Dependencies + +In your module-level `build.gradle.kts` (usually `app/build.gradle.kts`), add the dependency for Firebase AI: + +```kotlin +dependencies { + // [AGENT] Fetch the latest available BoM version from https://firebase.google.com/support/release-notes/android before adding this + implementation(platform("com.google.firebase:firebase-bom:")) + + // Add the dependency for the Firebase AI library + implementation("com.google.firebase:firebase-ai") +} +``` + +--- + +### 2. Initialize and Generate Content + +In your Activity or Fragment, initialize the `FirebaseAI` service and generate content using a Gemini model: + +```kotlin +import com.google.firebase.ai.FirebaseAI +import com.google.firebase.ai.ktx.ai +import com.google.firebase.ktx.Firebase + +class MainActivity : AppCompatActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + + // Initialize Firebase AI + val ai = Firebase.ai + + // Use a model (e.g., gemini-2.5-flash-lite) + val model = ai.generativeModel("gemini-2.5-flash-lite") + + // Generate content + lifecycleScope.launch { + try { + val response = model.generateContent("Write a story about a magic backpack.") + Log.d(TAG, "Response: ${response.text}") + } catch (e: Exception) { + Log.e(TAG, "Error generating content", e) + } + } + } +} +``` + +#### Jetpack Compose (Modern) + +Initialize inside a `ComponentActivity` and use `setContent`: + +```kotlin +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.lifecycle.lifecycleScope +import com.google.firebase.Firebase +import com.google.firebase.ai.ai +import kotlinx.coroutines.launch + +class MainActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val ai = Firebase.ai + val model = ai.generativeModel("gemini-2.5-flash-lite") + + lifecycleScope.launch { + val response = model.generateContent("Hello Gemini!") + setContent { + MaterialTheme { + Text("AI Response: ${response.text}") + } + } + } + } +} +``` + +--- + +### 3. Multimodal Input (Text and Images) + +Pass bitmap data along with text prompts: + +```kotlin +val image1: Bitmap = ... // Load your bitmap +val image2: Bitmap = ... + +val response = model.generateContent( + content("Analyze these images for me") { + image(image1) + image(image2) + text("Compare these two items.") + } +) +Log.d(TAG, response.text) +``` + +--- + +### 4. Chat Session (Multi-turn) + +Maintain chat history automatically: + +```kotlin +val chat = model.startChat( + history = listOf( + content("user") { text("Hello, I am a software engineer.") } + content("model") { text("Hello! How can I help you today?") } + ) +) + +lifecycleScope.launch { + val response = chat.sendMessage("What should I learn next?") + Log.d(TAG, response.text) +} +``` + +--- + +### 5. Streaming Responses + +For faster display, stream the response: + +```kotlin +lifecycleScope.launch { + model.generateContentStream("Tell me a long story.") + .collect { chunk -> + print(chunk.text) // Update UI incrementally + } +} +``` diff --git a/transformations/android-studio/skills/firebase-auth-basics/SKILL.md b/transformations/android-studio/skills/firebase-auth-basics/SKILL.md new file mode 100644 index 00000000..576333ac --- /dev/null +++ b/transformations/android-studio/skills/firebase-auth-basics/SKILL.md @@ -0,0 +1,96 @@ +--- +name: firebase-auth-basics +description: Guide for setting up and using Firebase Authentication. Use this skill when the user's app requires user sign-in, user management, or secure data access using auth rules. +compatibility: This skill is best used with the Firebase CLI, but does not require it. Firebase CLI can be accessed through `npx -y firebase-tools@latest`. +--- + +## Prerequisites + +- **Firebase Project**: Created via `npx -y firebase-tools@latest projects:create` (see `firebase-basics`). +- **Firebase CLI**: Installed and logged in (see `firebase-basics`). + +## Core Concepts + +Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. + +### Users + +A user is an entity that can sign in to your app. Each user is identified by a unique ID (`uid`) which is guaranteed to be unique across all providers. +User properties include: +- `uid`: Unique identifier. +- `email`: User's email address (if available). +- `displayName`: User's display name (if available). +- `photoURL`: URL to user's photo (if available). +- `emailVerified`: Boolean indicating if the email is verified. + +### Identity Providers + +Firebase Auth supports multiple ways to sign in: +- **Email/Password**: Basic email and password authentication. +- **Federated Identity Providers**: Google, Facebook, Twitter, GitHub, Microsoft, Apple, etc. +- **Phone Number**: SMS-based authentication. +- **Anonymous**: Temporary guest accounts that can be linked to permanent accounts later. +- **Custom Auth**: Integrate with your existing auth system. + +Google Sign In is recommended as a good and secure default provider. + +### Tokens + +When a user signs in, they receive an ID Token (JWT). This token is used to identify the user when making requests to Firebase services (Realtime Database, Cloud Storage, Firestore) or your own backend. +- **ID Token**: Short-lived (1 hour), verifies identity. +- **Refresh Token**: Long-lived, used to get new ID tokens. + +## Workflow + +### 1. Provisioning + +#### Option 1. Enabling Authentication via CLI + +Only Google Sign In, anonymous auth, and email/password auth can be enabled via CLI. For other providers, use the Firebase Console. + +Configure Firebase Authentication in `firebase.json` by adding an 'auth' block: + +``` +{ + "auth": { + "providers": { + "anonymous": true + "emailPassword": true + "googleSignIn": { + "oAuthBrandDisplayName": "Your Brand Name" + "supportEmail": "support@example.com" + "authorizedRedirectUris": ["https://example.com"] + } + } + } +} +``` + +**CRITICAL**: After configuring `firebase.json`, you MUST deploy the auth configuration to the Firebase backend for the changes to take effect. This is essential for auth providers like Google Sign-In, email/password, etc. to auto-generate the necessary OAuth clients for your app platforms. Run: +```bash +npx -y firebase-tools@latest deploy --only auth +``` + +#### Option 2. Enabling Authentication in Console + +Enable other providers in the Firebase Console. + +1. Go to the https://console.firebase.google.com/project/_/authentication/providers +2. Select your project. +3. Enable the desired Sign-in providers (e.g., Email/Password, Google). + +### 2. Client Setup & Usage + +**Web** +See . + +**Flutter** +See . +**Android (Kotlin)** +See [references/client_sdk_android.md](references/client_sdk_android.md). + +### 3. Security Rules + +Secure your data using `request.auth` in Firestore/Storage rules. + +See [references/security_rules.md](references/security_rules.md). diff --git a/transformations/android-studio/skills/firebase-auth-basics/references/client_sdk_android.md b/transformations/android-studio/skills/firebase-auth-basics/references/client_sdk_android.md new file mode 100644 index 00000000..a6dc882a --- /dev/null +++ b/transformations/android-studio/skills/firebase-auth-basics/references/client_sdk_android.md @@ -0,0 +1,157 @@ +# Firebase Authentication on Android (Kotlin) + +This guide walks you through using Firebase Authentication in your Android app using Kotlin DSL (`build.gradle.kts`) and Kotlin code. + +### 1, Enable Authentication via CLI + +Before adding dependencies in your app, make sure you enable the Auth service in your Firebase Project using the Firebase CLI: + +```bash +npx -y firebase-tools@latest init auth +``` + + --- + +### 2. Add Dependencies + +In your module-level `build.gradle.kts` (usually `app/build.gradle.kts`), add the dependency for Firebase Authentication: + +```kotlin +dependencies { + // [AGENT] Fetch the latest available BoM version from https://firebase.google.com/support/release-notes/android before adding this + implementation(platform("com.google.firebase:firebase-bom:")) + + // Add the dependency for the Firebase Authentication library + // When using the BoM, you don't specify versions in Firebase library dependencies + implementation("com.google.firebase:firebase-auth") +} +``` + +--- + +### 3. Initialize FirebaseAuth + +In your Activity or Fragment, initialize the `FirebaseAuth` instance: + +```kotlin +import com.google.firebase.auth.FirebaseAuth +import com.google.firebase.auth.ktx.auth +import com.google.firebase.ktx.Firebase + +class MainActivity : AppCompatActivity() { + + private lateinit var auth: FirebaseAuth + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val auth = Firebase.auth + + setContent { + MaterialTheme { + Text("Auth initialized!") + } + } + } +} +``` + +#### Jetpack Compose (Modern) + +Initialize inside a `ComponentActivity` using `setContent`: + +```kotlin +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import com.google.firebase.Firebase +import com.google.firebase.auth.auth + +class MainActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val auth = Firebase.auth + + setContent { + MaterialTheme { + Text("Auth initialized!") + } + } + } +} +``` + +--- + +### 4. Check Current Auth State + +You should check if a user is already signed in when your activity starts: + +```kotlin +public override fun onStart() { + super.onStart() + // Check if user is signed in (non-null) and update UI accordingly. + val currentUser = auth.currentUser + if (currentUser != null) { + // User is signed in, navigate to main screen or update UI + } else { + // No user is signed in, prompt for login + } +} +``` + +--- + +### 5. Sign Up New Users (Email/Password) + +Use `createUserWithEmailAndPassword` to register new users: + +```kotlin +fun signUpUser(email: String, password: String) { + auth.createUserWithEmailAndPassword(email, password) + .addOnCompleteListener(this) { task -> + if (task.isSuccessful) { + // Sign up success, update UI with the signed-in user's information + val user = auth.currentUser + // Navigate to main screen + } else { + // If sign up fails, display a message to the user. + Toast.makeText(baseContext, "Authentication failed.", Toast.LENGTH_SHORT).show() + } + } +} +``` + +--- + +### 6. Sign In Existing Users (Email/Password) + +Use `signInWithEmailAndPassword` to log in existing users: + +```kotlin +fun signInUser(email: String, password: String) { + auth.signInWithEmailAndPassword(email, password) + .addOnCompleteListener(this) { task -> + if (task.isSuccessful) { + // Sign in success, update UI with the signed-in user's information + val user = auth.currentUser + // Navigate to main screen + } else { + // If sign in fails, display a message to the user. + Toast.makeText(baseContext, "Authentication failed.", Toast.LENGTH_SHORT).show() + } + } +} +``` + +--- + +### 7. Sign Out + +To sign out a user, call `signOut()` on the `FirebaseAuth` instance: + +```kotlin +auth.signOut() +// Navigate to login screen +``` diff --git a/transformations/android-studio/skills/firebase-auth-basics/references/security_rules.md b/transformations/android-studio/skills/firebase-auth-basics/references/security_rules.md new file mode 100644 index 00000000..c2b76edf --- /dev/null +++ b/transformations/android-studio/skills/firebase-auth-basics/references/security_rules.md @@ -0,0 +1,38 @@ +# Authentication in Security Rules + +Firebase Security Rules work with Firebase Authentication to provide rule-based access control. For better advice on writing safe security rules +enable the `firebase-firestore-basics` or `firebase-storage-basics` skills. + +The `request.auth` variable contains authentication information for the user requesting data. + +## Basic Checks + +### Check if user is signed in +``` +allow read, write: if request.auth != null; +``` + +### Check if user owns the data +Access data only if the document ID matches the user's UID. +``` +allow read, write: if request.auth != null && request.auth.uid == userId; +``` +(Where `userId` is a path variable, e.g., `match /users/{userId}`) + +### Check if user owns the document (field-based) +Access data only if the document has a `owner_uid` field matching the user's UID. +``` +allow read, write: if request.auth != null && request.auth.uid == resource.data.owner_uid; +``` + +## Token Properties +`request.auth.token` contains standard JWT claims and custom claims. + +- `request.auth.token.email`: The user's email address. +- `request.auth.token.email_verified`: If the email is verified. +- `request.auth.token.name`: The user's display name. + +### Example: Email Verification Check +``` +allow create: if request.auth.token.email_verified == true; +``` diff --git a/transformations/android-studio/skills/firebase-basics/SKILL.md b/transformations/android-studio/skills/firebase-basics/SKILL.md new file mode 100644 index 00000000..074e2d4a --- /dev/null +++ b/transformations/android-studio/skills/firebase-basics/SKILL.md @@ -0,0 +1,106 @@ +--- +name: firebase-basics +description: >- + Provides foundational setup, authentication, and project management workflows + for Firebase using the Firebase CLI. Use when checking Firebase CLI version + (must use 'npx -y firebase-tools@latest --version'), initializing a Firebase + environment, authenticating, setting active projects, or setting up `google-services.json` + or `GoogleService-Info.plist` files. +--- + +# Prerequisites + +Complete these setup steps before proceeding: + +1. **Local Environment Setup:** Verify the environment is properly set up so we + can use Firebase tools: + + - Run `npx -y firebase-tools@latest --version` to check if the Firebase + CLI is installed. + - Verify if the Firebase MCP server is installed using your existing + tools. + - **CRITICAL**: Before configuring any extensions or agent environments + below, you MUST read + [references/local-env-setup.md](references/local-env-setup.md). + - **DO NOT SKIP** this step: if 'firebase-basics' is the only + Firebase skill available to you, you must follow the reference for your + agent environment to set up the full suite of Firebase skills: + - **Gemini CLI**: Review + [references/setup/gemini_cli.md](references/setup/gemini_cli.md) + - **Antigravity**: Review + [references/setup/antigravity.md](references/setup/antigravity.md) + - **Android Studio**: Review + [references/setup/android_studio.md](references/setup/android_studio.md) + - **Claude Code**: Review + [references/setup/claude_code.md](references/setup/claude_code.md) + - **Cursor**: Review + [references/setup/cursor.md](references/setup/cursor.md) + - **GitHub Copilot**: Review + [references/setup/github_copilot.md](references/setup/github_copilot.md) + - **Other Agents**: Review + [references/setup/other_agents.md](references/setup/other_agents.md) + +2. **Authentication:** Ensure you are logged in to Firebase so that commands + have the correct permissions. Run `npx -y firebase-tools@latest login`. For + environments without a browser (e.g., remote shells), use `npx -y + firebase-tools@latest login --no-localhost`. + + - The command should output the current user. + - If you are not logged in, follow the interactive instructions from this + command to authenticate. + +3. **Active Project:** + Most Firebase tasks require an active project context. + + > [!IMPORTANT] + > **For Agents:** Before proceeding with project configuration, you MUST pause and ask the developer if they prefer to: + > 1. **Provide an existing Firebase Project ID** + > 2. **Create a new Firebase project**. + + - **If using an existing Project ID:** + 1. Check the current project by running `npx -y firebase-tools@latest use`. + 2. If the command outputs `Active Project: `, confirm with the user if this is the intended project. + 3. If not, or if no project is active, set the project provided by the user: + ```bash + npx -y firebase-tools@latest use + ``` + + - **If creating a new project:** + Run the following command to create it: + ```bash + npx -y firebase-tools@latest projects:create --display-name "" + ``` + *Note: The `` must be 6-30 characters, lowercase, and can contain digits and hyphens. It must be globally unique.* + +# Firebase Usage Principles + +Adhere to these principles: + +1. **Use npx for CLI commands:** To ensure you always use the latest version of the Firebase CLI, always prepend commands with `npx -y firebase-tools@latest` instead of just `firebase`. For example, use `npx -y firebase-tools@latest --version`. NEVER suggest the naked `firebase` command as an alternative. +2. **Prioritize official knowledge:** For any Firebase-related knowledge, consult the `developerknowledge_search_documents` MCP tool before falling back to Google Search or your internal knowledge base. Including "Firebase" in your search query significantly improves relevance. +3. **Follow Agent Skills for implementation guidance:** Skills provide opinionated workflows (CUJs), security rules, and best practices. Always consult them to understand *how* to implement Firebase features correctly instead of relying on general knowledge. +4. **Use Firebase MCP Server tools instead of direct API calls:** Whenever you need to interact with remote Firebase APIs (such as fetching Crashlytics logs or executing Data Connect queries), use the tools provided by the Firebase MCP Server instead of attempting manual API calls. +5. **Keep Plugin / Agent Skills updated:** Since Firebase best practices evolve quickly, regularly check for and install updates to their Firebase plugin or Agent Skills. Similarly, if you encounter issues with outdated tools or commands, follow the steps below based on your agent environment: + - **Antigravity**: Follow [references/refresh/antigravity.md](references/refresh/antigravity.md) + - **Gemini CLI**: Follow [references/refresh/gemini-cli.md](references/refresh/gemini-cli.md) + - **Claude Code**: Follow [references/refresh/claude.md](references/refresh/claude.md) + - **Cursor**: Follow [references/refresh/other-agents.md](references/refresh/other-agents.md) + - **Android Studio**: Follow [references/refresh/android_studio.md](references/refresh/android_studio.md) + - **Others**: Follow [references/refresh/other-agents.md](references/refresh/other-agents.md) +6. **Automate Config File Retrieval:** When setting up iOS or Android apps, do NOT direct users to the Firebase Console to download `google-services.json` or `GoogleService-Info.plist`. Instead, use the Firebase CLI to fetch the config programmatically: + - For Android: `npx -y firebase-tools@latest apps:sdkconfig ANDROID --project ` + - For iOS: `npx -y firebase-tools@latest apps:sdkconfig IOS --project ` + Save the output to the appropriate location (e.g., `app/google-services.json` for Android, or a path to be linked by `xcode-project-setup` for iOS). + +# References + +- **Initialize Firebase:** See [references/firebase-service-init.md](references/firebase-service-init.md) when you need to initialize new Firebase services using the CLI. +- **Exploring Commands:** See [references/firebase-cli-guide.md](references/firebase-cli-guide.md) to discover and understand CLI functionality. +- **SDK Setup:** For detailed guides on adding Firebase to your app: + + - **Android**: See [references/android_setup.md](references/android_setup.md) + +# Common Issues + +- **Login Issues:** If the browser fails to open during the login step, use + `npx -y firebase-tools@latest login --no-localhost` instead. diff --git a/transformations/android-studio/skills/firebase-basics/references/android_setup.md b/transformations/android-studio/skills/firebase-basics/references/android_setup.md new file mode 100644 index 00000000..a2162143 --- /dev/null +++ b/transformations/android-studio/skills/firebase-basics/references/android_setup.md @@ -0,0 +1,34 @@ +# 🛠️ Firebase Android Setup Guide + +--- +## 📋 Prerequisites +Before running these commands, ensure you are authenticated: +`npx -y firebase-tools@latest login` (or `npx -y firebase-tools@latest login --no-localhost` on remote servers) +--- + +## 0. Create an Android application +if you haven't already created an android application, create one. + +## 1. Create a Firebase Project +If you haven't already created a project, create a new cloud project with a unique ID: +`npx -y firebase-tools@latest projects:create --display-name ''` +*Example:* +`npx -y firebase-tools@latest projects:create my-cool-app-20260330 --display-name 'MyCoolApp'` +### 2. Register Your Android App +Link your Android app module (package name) to your project. Notice that the display name is passed as a positional argument at the end: +`npx -y firebase-tools@latest apps:create ANDROID '' --package-name '' --project ` +*Example:* +`npx -y firebase-tools@latest apps:create ANDROID 'MyApplication' --package-name 'com.example.myapplication' --project my-cool-app-20260330` +### 3. Download `google-services.json` +Fetch the configuration file using the App ID (which is printed in the output of the previous command): +`npx -y firebase-tools@latest apps:sdkconfig ANDROID --project ` +*Example output extraction to file:* +` # (Output must be saved as app/google-services.json)` +--- +## ✅ Verification Plan +### Manual Verification +Validate that the project was created and registered successfully: +`npx -y firebase-tools@latest projects:list` +`npx -y firebase-tools@latest apps:list --project ` + +--- diff --git a/transformations/android-studio/skills/firebase-basics/references/firebase-cli-guide.md b/transformations/android-studio/skills/firebase-basics/references/firebase-cli-guide.md new file mode 100644 index 00000000..36a4480a --- /dev/null +++ b/transformations/android-studio/skills/firebase-basics/references/firebase-cli-guide.md @@ -0,0 +1,16 @@ +# Exploring Commands + +The Firebase CLI documents itself. Use help commands to discover functionality. + +- **Global Help**: List all available commands and categories. + ```bash + npx -y firebase-tools@latest --help + ``` + +- **Command Help**: Get detailed usage for a specific command. + ```bash + npx -y firebase-tools@latest [command] --help + # Example: + npx -y firebase-tools@latest deploy --help + npx -y firebase-tools@latest firestore:indexes --help + ``` diff --git a/transformations/android-studio/skills/firebase-basics/references/firebase-service-init.md b/transformations/android-studio/skills/firebase-basics/references/firebase-service-init.md new file mode 100644 index 00000000..13800aae --- /dev/null +++ b/transformations/android-studio/skills/firebase-basics/references/firebase-service-init.md @@ -0,0 +1,18 @@ +# Initialization + +Before initializing, check if you are already in a Firebase project directory by looking for `firebase.json`. + +1. **Project Directory:** + Navigate to the root directory of the codebase. + *(Only if starting a completely new project from scratch without an existing codebase, create a directory first: `mkdir my-project && cd my-project`)* + +2. **Initialize Services:** + Run the initialization command: + ```bash + npx -y firebase-tools@latest init + ``` + +The CLI will guide you through: +- Selecting features (Firestore, Functions, Hosting, etc.). +- Associating with an existing project or creating a new one. +- Configuring files (e.g. `firebase.json`, `.firebaserc`). diff --git a/transformations/android-studio/skills/firebase-basics/references/local-env-setup.md b/transformations/android-studio/skills/firebase-basics/references/local-env-setup.md new file mode 100644 index 00000000..bce7b1b1 --- /dev/null +++ b/transformations/android-studio/skills/firebase-basics/references/local-env-setup.md @@ -0,0 +1,56 @@ +# Firebase Local Environment Setup + +This skill documents the bare minimum setup required for a full Firebase experience for the agent. Before starting to use any Firebase features, you MUST verify that each of the following steps has been completed. + +## 1. Verify Node.js +- **Action**: Run `node --version`. +- **Handling**: Ensure Node.js is installed and the version is `>= 20`. If Node.js is missing or `< v20`, install it based on the operating system: + + **Recommended: Use a Node Version Manager** + This avoids permission issues when installing global packages. + + **For macOS or Linux:** + 1. Guide the user to the [official nvm repository](https://github.com/nvm-sh/nvm#installing-and-updating). + 2. Request the user to manually install `nvm` and reply when finished. **Stop and wait** for the user's confirmation. + 3. Make `nvm` available in the current terminal session by sourcing the appropriate profile: + ```bash + # For Bash + source ~/.bash_profile + source ~/.bashrc + + # For Zsh + source ~/.zprofile + source ~/.zshrc + ``` + 4. Install Node.js: + ```bash + nvm install 24 + nvm use 24 + ``` + + **For Windows:** + 1. Guide the user to download and install [nvm-windows](https://github.com/coreybutler/nvm-windows/releases). + 2. Request the user to manually install `nvm-windows` and Node.js, and reply when finished. **Stop and wait** for the user's confirmation. + 3. After the user confirms, verify Node.js is available: + ```bash + node --version + ``` + + **Alternative: Official Installer** + 1. Guide the user to download and install the LTS version from [nodejs.org](https://nodejs.org/en/download). + 2. Request the user to manually install Node.js and reply when finished. **Stop and wait** for the user's confirmation. + +## 2. Verify Firebase CLI +- **Command**: `npx -y firebase-tools@latest --version` +- **Expected**: Successfully outputs a version string. + +## 3. Verify Firebase Authentication +You must be authenticated to manage Firebase projects. +- **Action**: Run `npx -y firebase-tools@latest login`. +- **Handling**: If the environment is remote or restricted (no browser access), run `npx -y firebase-tools@latest login --no-localhost` instead. + +## 4. Install Agent Skills and MCP Server +To fully manage Firebase, the agent needs specific skills and the Firebase MCP server installed. Refer to the main `SKILL.md` for direct links to the installation instructions specific to your agent environment. + +--- +**CRITICAL AGENT RULE:** Do NOT proceed with any other Firebase tasks until EVERY step above has been successfully verified and completed. diff --git a/transformations/android-studio/skills/firebase-basics/references/refresh/android_studio.md b/transformations/android-studio/skills/firebase-basics/references/refresh/android_studio.md new file mode 100644 index 00000000..48ec4f95 --- /dev/null +++ b/transformations/android-studio/skills/firebase-basics/references/refresh/android_studio.md @@ -0,0 +1,27 @@ +# Refresh Android Studio Local Environment + +Follow these steps to refresh Gemini in Android Studio's local environment, ensuring that agent skills are fully up-to-date. + +Gemini in Android Studio expects skills to be located at `~/.agents/skills`. + +1. **List Available Skills:** Identify all Firebase skills available in the repository: + ```bash + npx -y skills add firebase/agent-skills --list + ``` + +2. **Check Currently Installed Skills:** Check the contents of the skills directory to see what is currently installed: + ```bash + ls -la ~/.agents/skills + ``` + +3. **Add Missing Skills:** Use the `skills` CLI to add skills. If the CLI supports an `android_studio` agent identifier, you can run: + ```bash + npx -y skills add firebase/agent-skills --agent android_studio --skill "*" --yes + ``` + If the `skills` CLI does not support Android Studio directly, you can manually copy or symlink the desired skills from your local clone of `firebase/agent-skills` to `~/.agents/skills`. + +4. **Update Existing Skills:** To update skills, you can try: + ```bash + npx -y skills update --agent android_studio --yes + ``` + If manual installation was used, pull the latest changes from the `firebase/agent-skills` repository and copy the updated files to `~/.agents/skills`. diff --git a/transformations/android-studio/skills/firebase-basics/references/refresh/antigravity.md b/transformations/android-studio/skills/firebase-basics/references/refresh/antigravity.md new file mode 100644 index 00000000..6f5ee325 --- /dev/null +++ b/transformations/android-studio/skills/firebase-basics/references/refresh/antigravity.md @@ -0,0 +1,46 @@ +# Refresh Antigravity Local Environment + +Follow these steps to refresh Antigravity's local environment, ensuring that their agent skills and plugins are fully up-to-date. + +Antigravity relies on `npx skills`. Updates should prioritize the global level; if skills are installed at the project level, omit the `--global` flag. + +1. **List Available Skills:** Identify all Firebase skills available in the repository: + ```bash + npx -y skills add firebase/agent-skills --list + ``` + +2. **Check Currently Installed Skills:** Determine which skills are already installed and linked at both project and global levels: + ```bash + # Check project-level skills + npx -y skills list --agent antigravity + + # Check global-level skills + npx -y skills list --agent antigravity --global + ``` + *Note: If a skill shows `Agents: not linked` in the output, it is installed but not currently available to Antigravity.* + +3. **Add Missing or Unlinked Skills:** Compare the results from Step 1 and Step 2. For each missing or unlinked skill, follow the appropriate conditional instruction below: + + - **IF any Firebase skills were found at the PROJECT level in Step 2:** Add the missing skill to the project level: + ```bash + npx -y skills add firebase/agent-skills --agent antigravity --skill "" --yes + ``` + + - **IF any Firebase skills were found at the GLOBAL level in Step 2:** Add the missing skill to the global level: + ```bash + npx -y skills add firebase/agent-skills --agent antigravity --skill "" --global --yes + ``` + + - **IF NO Firebase skills were found in Step 2:** Add each missing skill to the global level: + ```bash + npx -y skills add firebase/agent-skills --agent antigravity --skill "" --global --yes + ``` + +4. **Update Existing Skills:** Update all currently installed skills to their latest versions: + ```bash + # Update project-level skills + npx -y skills update --agent antigravity --yes + + # Update global-level skills + npx -y skills update --agent antigravity --global --yes + ``` diff --git a/transformations/android-studio/skills/firebase-basics/references/refresh/claude.md b/transformations/android-studio/skills/firebase-basics/references/refresh/claude.md new file mode 100644 index 00000000..772314e3 --- /dev/null +++ b/transformations/android-studio/skills/firebase-basics/references/refresh/claude.md @@ -0,0 +1,10 @@ +# Refresh Claude Code Local Environment + +Follow these steps to refresh Claude Code's local environment, ensuring that their agent skills and plugins are fully up-to-date. + +Use Claude Code's native plugin manager instead of `npx`. + +1. **Update the Plugin:** Run the specific CLI command to update the Firebase plugin: + ```bash + claude plugin update firebase@firebase + ``` \ No newline at end of file diff --git a/transformations/android-studio/skills/firebase-basics/references/refresh/gemini-cli.md b/transformations/android-studio/skills/firebase-basics/references/refresh/gemini-cli.md new file mode 100644 index 00000000..6cc14677 --- /dev/null +++ b/transformations/android-studio/skills/firebase-basics/references/refresh/gemini-cli.md @@ -0,0 +1,11 @@ +# Refresh Gemini CLI Local Environment + +Follow these steps to refresh Gemini CLI's local environment, ensuring that their agent skills and plugins are fully up-to-date. + +Use the native Gemini CLI extension manager instead of `npx`. + +1. **Update the Extension:** Run the specific CLI command to update: + ```bash + gemini extensions update firebase + ``` + *Note: If the extension is named differently, replace `firebase` with the correct name from `gemini extensions list`.* diff --git a/transformations/android-studio/skills/firebase-basics/references/refresh/other-agents.md b/transformations/android-studio/skills/firebase-basics/references/refresh/other-agents.md new file mode 100644 index 00000000..f624c968 --- /dev/null +++ b/transformations/android-studio/skills/firebase-basics/references/refresh/other-agents.md @@ -0,0 +1,48 @@ +# Refresh Other Local Environment + +Follow these steps to refresh the local environment of other agents, ensuring that their agent skills and plugins are fully up-to-date. + +Other agents rely on `npx skills`. Updates should prioritize the global level; if skills are installed at the project level, omit the `--global` flag. + +Replace `` with the actual agent name, which can be found in the [skills repository README](https://github.com/vercel-labs/skills/blob/main/README.md). + +1. **List Available Skills:** Identify all Firebase skills available in the repository: + ```bash + npx -y skills add firebase/agent-skills --list + ``` + +2. **Check Currently Installed Skills:** Determine which skills are already installed and linked for the agent at both project and global levels: + ```bash + # Check project-level skills + npx -y skills list --agent + + # Check global-level skills + npx -y skills list --agent --global + ``` + *Note: If a skill shows `Agents: not linked` in the output, it is installed but not currently available to the agent.* + +3. **Add Missing or Unlinked Skills:** Compare the results from Step 1 and Step 2. For each missing or unlinked skill, follow the appropriate conditional instruction below: + + - **IF any Firebase skills were found at the PROJECT level in Step 2:** Add the missing skill to the project level: + ```bash + npx -y skills add firebase/agent-skills --agent --skill "" --yes + ``` + + - **IF any Firebase skills were found at the GLOBAL level in Step 2:** Add the missing skill to the global level: + ```bash + npx -y skills add firebase/agent-skills --agent --skill "" --global --yes + ``` + + - **IF NO Firebase skills were found in Step 2:** Add each missing skill to the global level: + ```bash + npx -y skills add firebase/agent-skills --agent --skill "" --global --yes + ``` + +4. **Update Existing Skills:** Update all currently installed skills to their latest versions: + ```bash + # Update project-level skills + npx -y skills update --agent --yes + + # Update global-level skills + npx -y skills update --agent --global --yes + ``` diff --git a/transformations/android-studio/skills/firebase-basics/references/setup/android_studio.md b/transformations/android-studio/skills/firebase-basics/references/setup/android_studio.md new file mode 100644 index 00000000..aaed6c53 --- /dev/null +++ b/transformations/android-studio/skills/firebase-basics/references/setup/android_studio.md @@ -0,0 +1,19 @@ +# Android Studio Setup + +This guide explains how to set up Firebase agent skills for Gemini in Android Studio. + +## Skills Installation + +Gemini in Android Studio expects skills to be located at `~/.agents/skills`. + +To install all Firebase skills, run the following command in your terminal: + +```bash +npx -y skills add firebase/agent-skills --skill "*" --yes +``` + +Ensure that the skills are installed or linked to the `~/.agents/skills` directory. + +## MCP Setup + +MCP setup is currently skipped for Android Studio as it only supports SSE transport, while the Firebase CLI MCP server uses stdio. Direct integration is not supported without an SSE-to-stdio proxy. diff --git a/transformations/android-studio/skills/firebase-basics/references/setup/antigravity.md b/transformations/android-studio/skills/firebase-basics/references/setup/antigravity.md new file mode 100644 index 00000000..e9c9976f --- /dev/null +++ b/transformations/android-studio/skills/firebase-basics/references/setup/antigravity.md @@ -0,0 +1,63 @@ +# Antigravity Setup + +To get the most out of Firebase in Antigravity, follow these steps to install the agent skills and the MCP server. + +### 1. Install and Verify Firebase Skills +Check if the skills are already installed before proceeding: + +1. **Check Local skills**: Run `ls -d .agent/skills/firebase-basics` or `ls -d .agents/skills/firebase-basics`. If the directory exists, the skills are already installed locally. +2. **Check Global skills**: If not found locally, check the global installation by running: + ```bash + npx skills list --global --agent antigravity + ``` + If the output includes `firebase-basics`, the skills are already installed globally. +3. **Install Skills**: If both checks fail, run the following command to install the Firebase agent skills: + ```bash + npx skills add firebase/agent-skills --agent antigravity --skill "*" + ``` + *Note: Omit `--yes` and `--global` to choose the installation location manually. If prompted interactively in the terminal, ensure you send the appropriate user choices via standard input to complete the installation.* +4. **Verify Installation**: Re-run the checks in steps 1 or 2 to confirm that `firebase-basics` is now available. + +### 2. Configure and Verify Firebase MCP Server +The MCP server allows Antigravity to interact directly with Firebase projects. This is considered the **mandatory extension configuration** required for full functionality. + +1. **Locate `mcp_config.json`**: Find the configuration file for your operating system: + - macOS / Linux: `~/.gemini/antigravity/mcp_config.json` + - Windows: `%USERPROFILE%\\.gemini\\antigravity\\mcp_config.json` + + *Note: If the `.gemini/antigravity/` directory or `mcp_config.json` file does not exist, create them and initialize the file with `{ "mcpServers": {} }` before proceeding.* +2. **Check Existing Configuration**: Open `mcp_config.json` and check the `mcpServers` section for a `firebase` entry. + - It is already configured if the `command` is `"firebase"` OR if the `command` is `"npx"` with `"firebase-tools"` and `"mcp"` in the `args`. + - **Important**: If a valid `firebase` entry is found, the MCP server is already configured. **Skip step 3** and proceed directly to step 4. + + **Example valid configurations**: + ```json + "firebase": { + "command": "npx" + "args": ["-y", "firebase-tools@latest", "mcp"] + } + ``` + OR + ```json + "firebase": { + "command": "firebase" + "args": ["mcp"] + } + ``` +3. **Add or Update Configuration**: If the `firebase` block is missing or incorrect, add it to the `mcpServers` object: + ```json + "firebase": { + "command": "npx" + "args": [ + "-y" + "firebase-tools@latest" + "mcp" + ] + } + ``` + *CRITICAL: Merge this configuration into the existing `mcp_config.json` file. You MUST preserve any other existing servers inside the `mcpServers` object.* +4. **Verify Configuration**: Save the file and confirm the `firebase` block is present and properly formatted JSON. + +### 3. Restart and Verify Connection +1. **Restart Antigravity**: Instruct the user to restart the Antigravity application. **Stop and wait** for their confirmation before proceeding. +2. **Confirm Connection**: Check the MCP server list in the Antigravity UI to confirm that the Firebase MCP server is connected. diff --git a/transformations/android-studio/skills/firebase-basics/references/setup/claude_code.md b/transformations/android-studio/skills/firebase-basics/references/setup/claude_code.md new file mode 100644 index 00000000..fe8eba61 --- /dev/null +++ b/transformations/android-studio/skills/firebase-basics/references/setup/claude_code.md @@ -0,0 +1,30 @@ +# Claude Code Setup + +To get the most out of Firebase in Claude Code, follow these steps to install the agent skills and the MCP server. + +## Recommended Method: Using Plugins + +The recommended method is using the plugin marketplace to install both the agent skills and the MCP functionality. + +### 1. Install and Verify Plugins + +Check if the plugins are already installed before proceeding: + +1. **Check Existing Skills**: Run `npx skills list --agent claude-code` to check for local skills. Run `npx skills list --global --agent claude-code` to check for global skills. Note whether the output includes `firebase-basics`. +2. **Check Existing MCP Configuration**: Run `claude mcp list -s user` and `claude mcp list -s project`. Note whether the output of either command includes `firebase`. +3. **Determine Installation Path**: + - If **both** skills and MCP configuration are found, the plugin is fully installed. **Stop here and skip all remaining setup steps in this document.** + - If **neither** are found, proceed to step 4. + - If **only one** is found (e.g., skills are installed but MCP is missing, or vice versa), **stop and prompt the user**. Explain the mixed state and ask if they want to proceed with installing the Firebase plugin before continuing to step 4. +4. **Add Marketplace**: Run the following command to add the marketplace (this uses the default User scope): + ```bash + claude plugin marketplace add firebase/agent-skills + ``` +5. **Install Plugins**: Run the following command to install the plugin: + ```bash + claude plugin install firebase@firebase + ``` +6. **Verify Installation**: Re-run the checks in steps 1 and 2 to confirm the skills and the MCP server are now available. + +### 2. Restart and Verify Connection +1. **Restart Claude Code**: Instruct the user to restart Claude Code. **Stop and wait** for their confirmation before proceeding. diff --git a/transformations/android-studio/skills/firebase-basics/references/setup/cursor.md b/transformations/android-studio/skills/firebase-basics/references/setup/cursor.md new file mode 100644 index 00000000..1c94c39e --- /dev/null +++ b/transformations/android-studio/skills/firebase-basics/references/setup/cursor.md @@ -0,0 +1,63 @@ +# Cursor Setup + +To get the most out of Firebase in Cursor, follow these steps to install the agent skills and the MCP server. + +### 1. Install and Verify Firebase Skills +Check if the skills are already installed before proceeding: + +1. **Check Local skills**: Run `npx skills list --agent cursor`. If the output includes `firebase-basics`, the skills are already installed locally. +2. **Check Global skills**: If not found locally, check the global installation by running: + ```bash + npx skills list --global --agent cursor + ``` + If the output includes `firebase-basics`, the skills are already installed globally. +3. **Install Skills**: If both checks fail, run the following command to install the Firebase agent skills: + ```bash + npx skills add firebase/agent-skills --agent cursor --skill "*" + ``` + *Note: Omit `--yes` and `--global` to choose the installation location manually. If prompted interactively in the terminal, ensure you send the appropriate user choices via standard input to complete the installation.* +4. **Verify Installation**: Re-run the checks in steps 1 or 2 to confirm that `firebase-basics` is now available. + +### 2. Configure and Verify Firebase MCP Server +The MCP server allows Cursor to interact directly with Firebase projects. + +1. **Locate `mcp.json`**: Find the configuration file for your operating system: + - Global: `~/.cursor/mcp.json` + - Project: `.cursor/mcp.json` + + *Note: If the directory or `mcp.json` file does not exist, create them and initialize the file with `{ "mcpServers": {} }` before proceeding.* +2. **Check Existing Configuration**: Open `mcp.json` and check the `mcpServers` section for a `firebase` entry. + - It is already configured if the `command` is `"firebase"` OR if the `command` is `"npx"` with `"firebase-tools"` and `"mcp"` in the `args`. + - **Important**: If a valid `firebase` entry is found, the MCP server is already configured. **Skip step 3** and proceed directly to step 4. + + **Example valid configurations**: + ```json + "firebase": { + "command": "npx" + "args": ["-y", "firebase-tools@latest", "mcp"] + } + ``` + OR + ```json + "firebase": { + "command": "firebase" + "args": ["mcp"] + } + ``` +3. **Add or Update Configuration**: If the `firebase` block is missing or incorrect, add it to the `mcpServers` object: + ```json + "firebase": { + "command": "npx" + "args": [ + "-y" + "firebase-tools@latest" + "mcp" + ] + } + ``` + *CRITICAL: Merge this configuration into the existing `mcp.json` file. You MUST preserve any other existing servers inside the `mcpServers` object.* +4. **Verify Configuration**: Save the file and confirm the `firebase` block is present and properly formatted JSON. + +### 3. Restart and Verify Connection +1. **Restart Cursor**: Instruct the user to restart the Cursor application. **Stop and wait** for their confirmation before proceeding. +2. **Confirm Connection**: Check the MCP server list in the Cursor UI to confirm that the Firebase MCP server is connected. diff --git a/transformations/android-studio/skills/firebase-basics/references/setup/gemini_cli.md b/transformations/android-studio/skills/firebase-basics/references/setup/gemini_cli.md new file mode 100644 index 00000000..ebadeaa9 --- /dev/null +++ b/transformations/android-studio/skills/firebase-basics/references/setup/gemini_cli.md @@ -0,0 +1,39 @@ +# Gemini CLI Setup + +To get the most out of Firebase in the Gemini CLI, follow these steps to install the agent extension and the MCP server. + +## Recommended: Installing Extensions + +The best way to get both the agent skills and the MCP server is via the Gemini extension. + +### 1. Install and Verify Firebase Extension +Check if the extension is already installed before proceeding: + +1. **Check Existing Extensions**: Run `gemini extensions list`. If the output includes `firebase`, the extension is already installed. +2. **Install Extension**: If not found, run the following command to install the Firebase agent skills and MCP server: + ```bash + gemini extensions install https://github.com/firebase/agent-skills + ``` +3. **Verify Installation**: Run the following checks to confirm installation: + - `gemini mcp list` -> Output should include `firebase-tools`. + - `gemini skills list` -> Output should include `firebase-basic`. + +### 2. Restart and Verify Connection +1. **Restart Gemini CLI**: Instruct the user to restart the Gemini CLI if any new installation occurred. **Stop and wait** for their confirmation before proceeding. + +--- + +## Alternative: Manual MCP Configuration (Project Scope) + +If the user only wants to use the MCP server for the current project: + +### 1. Configure and Verify Firebase MCP Server +1. **Check Existing Configuration**: Run `gemini mcp list`. If the output includes `firebase-tools`, the MCP server is already configured. +2. **Add the MCP Server**: If not found, run the following command to configure the Firebase MCP Server: + ```bash + gemini mcp add -e IS_GEMINI_CLI_EXTENSION=true firebase npx -y firebase-tools@latest mcp + ``` +3. **Verify Configuration**: Re-run `gemini mcp list` to confirm `firebase-tools` is connected. + +### 2. Restart and Verify Connection +1. **Restart Gemini CLI**: Instruct the user to restart the Gemini CLI. **Stop and wait** for their confirmation before proceeding. diff --git a/transformations/android-studio/skills/firebase-basics/references/setup/github_copilot.md b/transformations/android-studio/skills/firebase-basics/references/setup/github_copilot.md new file mode 100644 index 00000000..7aead169 --- /dev/null +++ b/transformations/android-studio/skills/firebase-basics/references/setup/github_copilot.md @@ -0,0 +1,70 @@ +# GitHub Copilot Setup + +To get the most out of Firebase with GitHub Copilot in VS Code, follow these steps to install the agent skills and the MCP server. + +## Recommended: Global Setup + +The agent skills and MCP server should be installed globally for consistent access across projects. + +### 1. Install and Verify Firebase Skills +Check if the skills are already installed before proceeding: + +1. **Check Local skills**: Run `npx skills list --agent github-copilot`. If the output includes `firebase-basics`, the skills are already installed locally. +2. **Check Global skills**: If not found locally, check the global installation by running: + ```bash + npx skills list --global --agent github-copilot + ``` + If the output includes `firebase-basics`, the skills are already installed globally. +3. **Install Skills**: If both checks fail, run the following command to install the Firebase agent skills: + ```bash + npx skills add firebase/agent-skills --agent github-copilot --skill "*" + ``` + *Note: Omit `--yes` and `--global` to choose the installation location manually. If prompted interactively in the terminal, ensure you send the appropriate user choices via standard input to complete the installation.* +4. **Verify Installation**: Re-run the checks in steps 1 or 2 to confirm that `firebase-basics` is now available. + +### 2. Configure and Verify Firebase MCP Server +The MCP server allows GitHub Copilot to interact directly with Firebase projects. + +1. **Locate `mcp.json`**: Find the configuration file for your environment: + - Workspace: `.vscode/mcp.json` + - Global: User Settings `mcp.json` file. + + *Note: If the `.vscode/` directory or `mcp.json` file does not exist, create them and initialize the file with `{ "mcp": { "servers": {} } }` before proceeding.* +2. **Check Existing Configuration**: Open the `mcp.json` file and check the `mcp.servers` object for a `firebase` entry. + - It is already configured if the `command` is `"firebase"` OR if the `command` is `"npx"` with `"firebase-tools"` and `"mcp"` in the `args`. + - **Important**: If a valid `firebase` entry is found, the MCP server is already configured. **Skip step 3** and proceed directly to step 4. + + **Example valid configurations**: + ```json + "firebase": { + "type": "stdio" + "command": "npx" + "args": ["-y", "firebase-tools@latest", "mcp"] + } + ``` + OR + ```json + "firebase": { + "type": "stdio" + "command": "firebase" + "args": ["mcp"] + } + ``` +3. **Add or Update Configuration**: If the `firebase` block is missing or incorrect, add it to the `mcp.servers` object: + ```json + "firebase": { + "type": "stdio" + "command": "npx" + "args": [ + "-y" + "firebase-tools@latest" + "mcp" + ] + } + ``` + *CRITICAL: Merge this configuration into the existing `mcp.json` file under the `mcp.servers` object. You MUST preserve any other existing servers inside `mcp.servers`.* +4. **Verify Configuration**: Save the file and confirm the `firebase` block is present and properly formatted JSON. + +### 3. Restart and Verify Connection +1. **Restart VS Code**: Instruct the user to restart VS Code. **Stop and wait** for their confirmation before proceeding. +2. **Confirm Connection**: Check the MCP server list in the VS Code Copilot UI to confirm that the Firebase MCP server is connected. diff --git a/transformations/android-studio/skills/firebase-basics/references/setup/other_agents.md b/transformations/android-studio/skills/firebase-basics/references/setup/other_agents.md new file mode 100644 index 00000000..f065e8c7 --- /dev/null +++ b/transformations/android-studio/skills/firebase-basics/references/setup/other_agents.md @@ -0,0 +1,65 @@ +# Other Agents Setup + +If you use another agent (like Windsurf, Cline, or Claude Desktop), follow these steps to install the agent skills and the MCP server. + +## Recommended: Global Setup + +The agent skills and MCP server should be installed globally for consistent access across projects. + +### 1. Install and Verify Firebase Skills +Check if the skills are already installed before proceeding: + +1. **Check Local skills**: Run `npx skills list --agent `. If the output includes `firebase-basics`, the skills are already installed locally. Replace `` with the actual agent name, which can be found [here](https://github.com/vercel-labs/skills/blob/main/README.md). +2. **Check Global skills**: If not found locally, check the global installation by running: + ```bash + npx skills list --global --agent + ``` + If the output includes `firebase-basics`, the skills are already installed globally. +3. **Install Skills**: If both checks fail, run the following command to install the Firebase agent skills: + ```bash + npx skills add firebase/agent-skills --agent --skill "*" + ``` + *Note: Omit `--yes` and `--global` to choose the installation location manually. If prompted interactively in the terminal, ensure you send the appropriate user choices via standard input to complete the installation.* +4. **Verify Installation**: Re-run the checks in steps 1 or 2 to confirm that `firebase-basics` is now available. + +### 2. Configure and Verify Firebase MCP Server +The MCP server allows the agent to interact directly with Firebase projects. + +1. **Locate MCP Configuration**: Find the configuration file for your agent (e.g., `~/.codeium/windsurf/mcp_config.json`, `cline_mcp_settings.json`, or `claude_desktop_config.json`). + + *Note: If the document or its containing directory does not exist, create them and initialize the file with `{ "mcpServers": {} }` before proceeding.* +2. **Check Existing Configuration**: Open the configuration file and check the `mcpServers` section for a `firebase` entry. + - It is already configured if the `command` is `"firebase"` OR if the `command` is `"npx"` with `"firebase-tools"` and `"mcp"` in the `args`. + - **Important**: If a valid `firebase` entry is found, the MCP server is already configured. **Skip step 3** and proceed directly to step 4. + + **Example valid configurations**: + ```json + "firebase": { + "command": "npx" + "args": ["-y", "firebase-tools@latest", "mcp"] + } + ``` + OR + ```json + "firebase": { + "command": "firebase" + "args": ["mcp"] + } + ``` +3. **Add or Update Configuration**: If the `firebase` block is missing or incorrect, add it to the `mcpServers` object: + ```json + "firebase": { + "command": "npx" + "args": [ + "-y" + "firebase-tools@latest" + "mcp" + ] + } + ``` + *CRITICAL: Merge this configuration into the existing file. You MUST preserve any other existing servers inside the `mcpServers` object.* +4. **Verify Configuration**: Save the file and confirm the `firebase` block is present and properly formatted JSON. + +### 3. Restart and Verify Connection +1. **Restart Agent**: Instruct the user to restart the agent application. **Stop and wait** for their confirmation before proceeding. +2. **Confirm Connection**: Check the MCP server list in the agent's UI to confirm that the Firebase MCP server is connected. diff --git a/transformations/android-studio/skills/firebase-crashlytics/SKILL.md b/transformations/android-studio/skills/firebase-crashlytics/SKILL.md new file mode 100644 index 00000000..6f58d8ee --- /dev/null +++ b/transformations/android-studio/skills/firebase-crashlytics/SKILL.md @@ -0,0 +1,32 @@ +--- +name: firebase-crashlytics +description: Comprehensive guide for Firebase Crashlytics, including provisioning and SDK usage. Use this skill when the user needs help setting up Crashlytics, adding crash reporting, or using the Crashlytics SDK in their application. +compatibility: This skill is best used with the Firebase CLI, but does not require it. Firebase CLI can be accessed through `npx -y firebase-tools@latest`. +--- + +# Crashlytics + +This skill provides a complete guide for getting started with Crashlytics on Android or iOS. Crash data collected from client applications can be read using the MCP server in the Firebase CLI. + +## Prerequisites + +Provisioning Crashlytics requires both a Firebase project and a Firebase app, either Android or iOS. To read the data collected by Crashlytics, install the MCP server in the Firebase CLI. See the `firebase-basics` skill for references. + +## SDK Setup + +To learn how to setup Crashlytics in your application code, choose your platform: + +* **Android**: [android_setup.md](references/android_setup.md) + +## SDK Usage + +The SDK provides a number of features to make crash reports more actionable. + +* Add custom keys +* Add custom logs +* Set user identifiers +* Report non-fatal exceptions + +To learn how to customize crash reports and add additional debugging data, consult the documentation for your platform. + +* **Android**: [Customize Crash Reports for Android](https://firebase.google.com/docs/crashlytics/android/customize-crash-reports.md) diff --git a/transformations/android-studio/skills/firebase-crashlytics/references/android_setup.md b/transformations/android-studio/skills/firebase-crashlytics/references/android_setup.md new file mode 100644 index 00000000..7eb8502c --- /dev/null +++ b/transformations/android-studio/skills/firebase-crashlytics/references/android_setup.md @@ -0,0 +1,122 @@ +# Firebase Crashlytics Android Setup Guide + +Important references: + +- Refer to the `firebase-basics` skills, particularly those for project and app setup, before proceeding. + +## Project and App Setup + +Before you begin, ensure you have the following. If a `google-services.json` file is present, then use that Firebase project and app. Otherwise you may need to create them. + +- **Firebase CLI**: Installed and logged in (see `firebase-basics`). +- **Firebase Project**: Created via `npx -y firebase-tools@latest projects:create` (see `firebase-basics`). +- **Firebase App**: Created via `npx -y firebase-tools@latest apps:create ` + +The `google-services.json` file must be present in the Android app's module directory. If missing, get the config using the Firebase CLI: `npx -y firebase-tools@latest apps:sdkconfig ANDROID `. + +## Add Dependencies to Gradle Build + +These changes are made to your Android project's Gradle files. + +### Project-level `build.gradle.kts` (`/build.gradle.kts`) + +Add the latest version of the Crashlytics Gradle plugin to the `plugins` block. Fetch the before adding this. + +```kotlin +plugins { + // ... other plugins + id("com.google.firebase.crashlytics") version "" apply false +} +``` + +### App-level `build.gradle.kts` (`//build.gradle.kts`) + +1. Add the Crashlytics plugin to the `plugins` block: + + ```kotlin + plugins { + // ... other plugins + id("com.google.firebase.crashlytics") + } + ``` + +2. Add the Firebase Crashlytics dependency to the `dependencies` block. It is recommended to use the Firebase Bill of Materials (BoM) to manage SDK versions. Fetch the before adding this. + + ```kotlin + dependencies { + // ... other dependencies + + // Import the Firebase BoM + implementation(platform("com.google.firebase:firebase-bom:")) + + // Add the dependencies for the Crashlytics and Analytics + implementation("com.google.firebase:firebase-crashlytics-ktx") + } + ``` + + +## Follow up Steps + +### Optional: Install the NDK SDK to capture native crashes + +If your app uses native code (C/C++), or includes a library with native code, you can configure Crashlytics to report native crashes. + +App-level `build.gradle.kts` (`//build.gradle.kts`) + +1. Add the `firebase-crashlytics-ndk` dependency: + + ```kotlin + dependencies { + // ... other dependencies + implementation("com.google.firebase:firebase-crashlytics-ndk:18.6.2") + } + ``` + +2. Enable the `nativeSymbolUpload` flag in your `buildTypes` configuration. This will automatically upload symbol files for your native code, which are required to symbolicate native crash reports. + + ```kotlin + android { + // ... other config + buildTypes { + getByName("release") { + // ... + firebaseCrashlytics { + nativeSymbolUploadEnabled = true + } + } + } + } + ``` + +After these changes, Crashlytics will automatically report crashes in your app's native code. + +### Required: Force a Test Crash + +To verify that Crashlytics is correctly installed, you need to force a test crash in the app. + +1. Add code to your main activity (e.g., in `onCreate`) to trigger a crash a few seconds after app startup: + + ```kotlin + import android.os.Handler + import android.os.Looper + + // ... in your Activity's onCreate method or similar startup logic + Handler(Looper.getMainLooper()).postDelayed({ + throw RuntimeException("Test Crash") // Force a crash after 3 seconds + }, 3000) + ``` + +2. Run your app on a device or emulator. The app should crash after a short delay. + +3. Restart the app. The Crashlytics SDK will send the crash report to Firebase on the next app launch. + +4. After a few minutes, the crash should be available in the Firebase console. Go to **DevOps & Engagement** > **Crashlytics** to view your dashboard and crash reports. + - If the Firebase MCP server is installed, use the `get_report` tool to check that a crash was received. + - As a fallback, visit the Crashlytics dashboard in the Firebase console to see the new crash report. + +5. After verifying that Firebase has received the crash report - either using the `get_report` tool or manually viewing it in the Firebase console - remove the code from step 1 that triggers the crash. This prevents the application from always crashing on start up after a delay. + +### Optional: Add custom debugging information + +Customize reports to help you better understand what's happening in your app and the circumstances around events reported to Crashlytics. See [Customize Crash Reports for Android](https://firebase.google.com/docs/crashlytics/android/customize-crash-reports.md). + diff --git a/transformations/android-studio/skills/firebase-data-connect-basics/SKILL.md b/transformations/android-studio/skills/firebase-data-connect-basics/SKILL.md new file mode 100644 index 00000000..478eacf9 --- /dev/null +++ b/transformations/android-studio/skills/firebase-data-connect-basics/SKILL.md @@ -0,0 +1,154 @@ +--- +name: firebase-data-connect +description: Builds and deploys Firebase SQL Connect (aka Firebase Data Connect) backends with PostgreSQL securely. Use when designing schemas with tables and relations, writing authorized queries and mutations, configuring real-time data updates, or generating type-safe SDKs. Use when you need a relational database with Firebase, or when the user mentions SQL Connect or Data Connect. +--- + +# Firebase SQL Connect + +Firebase SQL Connect is a relational database service using Cloud SQL for PostgreSQL with GraphQL schema, auto-generated queries/mutations, and type-safe SDKs. + +> [!NOTE] +> **Product Rename**: Firebase Data Connect was renamed to **Firebase SQL Connect**. All instructions, references, and examples in this skill repository referring to "Data Connect" or "Firebase Data Connect" apply to "SQL Connect" and "Firebase SQL Connect" as well. + +## Project Structure + +```text +dataconnect/ +├── dataconnect.yaml # Service configuration +├── schema/ +│ └── schema.gql # Data model (types with @table) +└── connector/ + ├── connector.yaml # Connector config + SDK generation + ├── queries.gql # Queries + └── mutations.gql # Mutations +``` + +## Key Tools for Validation + +Rely on these two mechanisms to ensure project correctness: +1. **Review GraphQL Schema**: Both user-defined and generated extensions (in `.dataconnect/schema/main/`). +2. **Validate Operations**: Run `npx -y firebase-tools@latest dataconnect:compile` against the schema. + +## Operation Strategies: GraphQL vs. Native SQL + +Always default to **Native GraphQL**. **Native SQL lacks type safety** and bypasses schema-enforced structures. Only use **Native SQL** when the user explicitly requests it or when the task requires advanced database features. + +| Strategy | When to use | Implementation | +|----------|-------------|----------------| +| **Native GraphQL** (Default) | Almost all use cases. Standard CRUD, basic filtering/sorting, simple relational joins. Requires full type safety. | Auto-generated fields (`movie_insert`, `movies`). Strong typing and schema enforcement. | +| **Native SQL** (Advanced) | PostgreSQL extensions (e.g., PostGIS), window functions (`RANK()`), complex aggregations, or highly tuned sub-queries. | Raw SQL string literals via `_select`, `_execute`, etc. Requires strict positional parameters (`$1`). No type safety. | + +## Development Workflow + +Follow this strict workflow to build your application. You **must** read the linked reference files for each step to understand the syntax and available features. + +### 1. Define Data Model (`schema/schema.gql`) +Define your GraphQL types, tables, and relationships (which map to a Postgres schema). +> **Read [reference/schema.md](reference/schema.md)** for: +> * `@table`, `@col`, `@default` +> * Relationships (`@ref`, one-to-many, many-to-many) +> * Data types (UUID, Vector, JSON, etc.) + +### 2. Define Authorized Operations (`connector/queries.gql`, `connector/mutations.gql`) +Write the queries and mutations your client will use, including authorization logic. SQL Connect is secure by default. +> **Read [reference/operations.md](reference/operations.md)** for: +> * **Queries**: Filtering (`where`), Ordering (`orderBy`), Pagination (`limit`/`offset`). +> * **Mutations**: Create (`_insert`), Update (`_update`), Delete (`_delete`). +> * **Upserts**: Use `_upsert` to "insert or update" records (CRITICAL for user profiles). +> * **Transactions**: Use `@transaction` for multi-step atomic operations. Use `_expr: "response."` to pass data between steps. +> +> **Read [reference/security.md](reference/security.md)** for authorization: +> * `@auth(level: ...)` for PUBLIC, USER, or NO_ACCESS. +> * `@check` and `@redact` for row-level security and validation. +> +> **Read [reference/realtime.md](reference/realtime.md)** for real-time subscriptions: +> * `@refresh` directive for time-based polling and event-driven updates. +> * CEL conditions to scope refresh triggers precisely. +> +> **Read [reference/native_sql.md](reference/native_sql.md)** for Native SQL operations: +> * Embedding raw SQL with `_select`, `_selectFirst`, `_execute` +> * Strict rules for positional parameters (`$1`, `$2`), quoting, and CTEs +> * Advanced PostgreSQL features (PostGIS, Window Functions) + +### 3. Use type-safe SDK in your apps +Generate type-safe code for your client platform. + +Configure SDK generation in `connector.yaml`: + +```yaml +connectorId: my-connector +generate: + javascriptSdk: + outputDir: "../web-app/src/lib/dataconnect" + package: "@movie-app/dataconnect" + kotlinSdk: + outputDir: "../android-app/app/src/main/kotlin/com/example/dataconnect" + package: "com.example.dataconnect" + swiftSdk: + outputDir: "../ios-app/DataConnect" +``` + +Generate SDKs: +```bash +npx -y firebase-tools@latest dataconnect:sdk:generate +``` + +For platform-specific instructions on how to use the generated SDKs, read: +* **Web (TypeScript)**: +* **Android (Kotlin)**: [reference/sdk_android.md](reference/sdk_android.md) +* **iOS (Swift)**: +* **Admin (Node.js)**: [reference/sdk_admin_node.md](reference/sdk_admin_node.md) +* **Flutter (Dart)**: + + + +--- + +## Feature Capability Map + +If you need to implement a specific feature, consult the mapped reference file: + +| Feature | Reference File | Key Concepts | +| :--- | :--- | :--- | +| **Data Modeling** | [reference/schema.md](reference/schema.md) | `@table`, `@unique`, `@index`, Relations | +| **Vector Search** | [reference/advanced.md](reference/advanced.md) | `Vector`, `@col(dataType: "vector")` | +| **Full-Text Search** | [reference/advanced.md](reference/advanced.md) | `@searchable` | +| **Upserting Data** | [reference/operations.md](reference/operations.md) | `_upsert` mutations | +| **Complex Filters** | [reference/operations.md](reference/operations.md) | `_or`, `_and`, `_not`, `eq`, `contains` | +| **Transactions** | [reference/operations.md](reference/operations.md) | `@transaction`, `response` binding | +| **Environment Config** | [reference/config.md](reference/config.md) | `dataconnect.yaml`, `connector.yaml` | +| **Realtime Subscriptions** | [reference/realtime.md](reference/realtime.md) | `@refresh`, `subscribe()`, auto-refresh | +| **Starter Templates** | [templates.md](templates.md) | CRUD, user-owned resources, many-to-many, SDK init | + +--- + +## Deployment & CLI + +> **Read [reference/config.md](reference/config.md)** for deep dive on configuration. + +Follow these patterns based on your current task: + +### How to initialize SQL Connect in a Firebase project + +1. Understand the app idea. Ask clarification questions if unclear. +2. Run `npx -y firebase-tools@latest init dataconnect`. +3. Validate that the app template and generated SDK are setup. + +### How to build apps using SQL Connect locally + +1. Start the emulator: `npx -y firebase-tools@latest emulators:start --only dataconnect`. +2. Write schema and operations. +3. Run `npx -y firebase-tools@latest dataconnect:compile` or `npx -y firebase-tools@latest dataconnect:sdk:generate` to + validate them. +4. Use the operations in your app and build it. + +### How to deploy SQL Connect to Cloud SQL + +1. Run `npx -y firebase-tools@latest deploy --only dataconnect`. + +## Examples + +For complete, working code examples of schemas and operations, see +**[examples.md](examples.md)**. + +For ready-to-use starter templates (CRUD, user-owned resources, many-to-many, YAML configs, SDK init), see **[templates.md](templates.md)**. diff --git a/transformations/android-studio/skills/firebase-data-connect-basics/examples.md b/transformations/android-studio/skills/firebase-data-connect-basics/examples.md new file mode 100644 index 00000000..c6c62811 --- /dev/null +++ b/transformations/android-studio/skills/firebase-data-connect-basics/examples.md @@ -0,0 +1,629 @@ +# Examples + +Complete, working examples for common SQL Connect use cases. + +--- + +## Movie Review App + +A complete schema for a movie database with reviews, actors, and user authentication. + +### Schema + +```graphql +# schema.gql + +# Users +type User @table(key: "uid") { + uid: String! @default(expr: "auth.uid") + email: String! @unique + displayName: String + createdAt: Timestamp! @default(expr: "request.time") +} + +# Movies +type Movie @table { + id: UUID! @default(expr: "uuidV4()") + title: String! + releaseYear: Int + genre: String @index + rating: Float + description: String + posterUrl: String + createdAt: Timestamp! @default(expr: "request.time") +} + +# Movie metadata (one-to-one) +type MovieMetadata @table { + movie: Movie! @unique + director: String + runtime: Int + budget: Int64 +} + +# Actors +type Actor @table { + id: UUID! @default(expr: "uuidV4()") + name: String! + birthDate: Date +} + +# Movie-Actor relationship (many-to-many) +type MovieActor @table(key: ["movie", "actor"]) { + movie: Movie! + actor: Actor! + role: String! # "lead" or "supporting" + character: String +} + +# Reviews (user-owned) +type Review @table @unique(fields: ["movie", "user"]) { + id: UUID! @default(expr: "uuidV4()") + movie: Movie! + user: User! + rating: Int! + text: String + createdAt: Timestamp! @default(expr: "request.time") +} +``` + +### Queries + +```graphql +# queries.gql + +# Public: List movies with filtering +query ListMovies($genre: String, $minRating: Float, $limit: Int) + @auth(level: PUBLIC) { + movies( + where: { + genre: { eq: $genre } + rating: { ge: $minRating } + } + orderBy: [{ rating: DESC }] + limit: $limit + ) { + id title genre rating releaseYear posterUrl + } +} + +# Public: Get movie with full details +query GetMovie($id: UUID!) @auth(level: PUBLIC) { + movie(id: $id) { + id title genre rating releaseYear description + metadata: movieMetadata_on_movie { director runtime } + actors: actors_via_MovieActor { name } + reviews: reviews_on_movie(orderBy: [{ createdAt: DESC }], limit: 10) { + rating text createdAt + user { displayName } + } + } +} + +# User: Get my reviews +query MyReviews @auth(level: USER) { + reviews(where: { user: { uid: { eq_expr: "auth.uid" }}}) { + id rating text createdAt + movie { id title posterUrl } + } +} +``` + +### Mutations + +```graphql +# mutations.gql + +# User: Create/update profile on first login +mutation UpsertUser($email: String!, $displayName: String) @auth(level: USER) { + user_upsert(data: { + uid_expr: "auth.uid" + email: $email + displayName: $displayName + }) +} + +# User: Add review (one per movie per user) +mutation AddReview($movieId: UUID!, $rating: Int!, $text: String) + @auth(level: USER) { + review_upsert(data: { + movie: { id: $movieId } + user: { uid_expr: "auth.uid" } + rating: $rating + text: $text + }) +} + +# User: Delete my review +mutation DeleteReview($id: UUID!) @auth(level: USER) { + review_delete( + first: { where: { + id: { eq: $id } + user: { uid: { eq_expr: "auth.uid" }} + }} + ) +} +``` + +### Realtime Queries + +```graphql +# queries.gql (realtime additions) + +# Auto-refresh: this single-entity lookup refreshes automatically +# when any mutation modifies this specific movie. No @refresh needed. +query GetMovie($id: UUID!) @auth(level: PUBLIC) { + movie(id: $id) { + id title genre rating releaseYear description + metadata: movieMetadata_on_movie { director runtime } + reviews: reviews_on_movie(orderBy: [{ createdAt: DESC }], limit: 10) { + rating text createdAt + user { displayName } + } + } +} + +# Event-driven: Simple refresh when any movie is added +query ListMoviesSimple @auth(level: PUBLIC) @refresh(onMutationExecuted: { operation: "AddMovie" }) { + movies { id title } +} + +# Counterpart mutation for ListMoviesSimple +mutation AddMovie($title: String!) @auth(level: USER) { + movie_insert(data: { title: $title }) +} + +# Event-driven: Refresh only when a movie of the same genre is added +# Demonstrates the use of 'condition' and 'mutation.variables' +query ListMoviesByGenre($genre: String!) @auth(level: PUBLIC) + @refresh(onMutationExecuted: { + operation: "AddMovieWithGenre" + condition: "mutation.variables.genre == request.variables.genre" + }) { + movies(where: { genre: { eq: $genre } }) { id title } +} + +# Counterpart mutation for ListMoviesByGenre +mutation AddMovieWithGenre($title: String!, $genre: String!) @auth(level: USER) { + movie_insert(data: { title: $title, genre: $genre }) +} + +# Event-driven: Refresh user profile when updated +# Demonstrates condition based on auth context +query MyProfile @auth(level: USER) + @refresh(onMutationExecuted: { + operation: "UpdateProfile" + condition: "mutation.auth.uid == request.auth.uid" + }) { + user(uid_expr: "auth.uid") { id name } +} + +# Counterpart mutation for MyProfile +mutation UpdateProfile($name: String!) @auth(level: USER) { + user_update(id_expr: "auth.uid", data: { name: $name }) +} + +# Time-based: live leaderboard refreshing every 30 seconds +query MovieLeaderboard + @auth(level: PUBLIC) + @refresh(every: { seconds: 30 }) { + movies(orderBy: [{ rating: DESC }], limit: 10) { + id title rating + } +} +``` + +```typescript +import { listMoviesRef, movieLeaderboardRef } from '@movie-app/dataconnect'; +import { subscribe } from 'firebase/data-connect'; + +// Subscribe to movie list — refreshes when AddReview mutation runs +const unsubMovies = subscribe(listMoviesRef({ genre: 'Action' }), { + onNext: (result) => updateMovieList(result.data.movies) + onError: (error) => console.error(error) +}); + +// Subscribe to leaderboard — refreshes every 30 seconds +const unsubLeaderboard = subscribe(movieLeaderboardRef(), { + onNext: (result) => updateLeaderboard(result.data.movies) + onError: (error) => console.error(error) +}); + +// Cleanup +// unsubMovies(); +// unsubLeaderboard(); +``` + +--- + +## E-Commerce Store + +Products, orders, and cart management with user authentication. + +### Schema + +```graphql +# schema.gql + +type User @table(key: "uid") { + uid: String! @default(expr: "auth.uid") + email: String! @unique + name: String + shippingAddress: String +} + +type Product @table { + id: UUID! @default(expr: "uuidV4()") + name: String! @index + description: String + price: Float! + stock: Int! @default(value: 0) + category: String @index + imageUrl: String +} + +type CartItem @table(key: ["user", "product"]) { + user: User! + product: Product! + quantity: Int! +} + +enum OrderStatus { + PENDING + PAID + SHIPPED + DELIVERED + CANCELLED +} + +type Order @table { + id: UUID! @default(expr: "uuidV4()") + user: User! + status: OrderStatus! @default(value: PENDING) + total: Float! + shippingAddress: String! + createdAt: Timestamp! @default(expr: "request.time") +} + +type OrderItem @table { + id: UUID! @default(expr: "uuidV4()") + order: Order! + product: Product! + quantity: Int! + priceAtPurchase: Float! +} +``` + +### Operations + +```graphql +# Public: Browse products +query ListProducts($category: String, $search: String) @auth(level: PUBLIC) { + products(where: { + category: { eq: $category } + name: { contains: $search } + stock: { gt: 0 } + }) { + id name price stock imageUrl + } +} + +# User: View cart +query MyCart @auth(level: USER) { + cartItems(where: { user: { uid: { eq_expr: "auth.uid" }}}) { + quantity + product { id name price imageUrl stock } + } +} + +# User: Add to cart +mutation AddToCart($productId: UUID!, $quantity: Int!) @auth(level: USER) { + cartItem_upsert(data: { + user: { uid_expr: "auth.uid" } + product: { id: $productId } + quantity: $quantity + }) +} + +# User: Checkout (transactional) +mutation Checkout($shippingAddress: String!) + @auth(level: USER) + @transaction { + # Query cart items + query @redact { + cartItems(where: { user: { uid: { eq_expr: "auth.uid" }}}) + @check(expr: "this.size() > 0", message: "Cart is empty") { + quantity + product { id price } + } + } + # Create order (in real app, calculate total from cart) + order_insert(data: { + user: { uid_expr: "auth.uid" } + shippingAddress: $shippingAddress + total: 0 # Calculate in app logic + }) +} +``` + +--- + +## Blog with Permissions + +Multi-author blog with role-based permissions. + +### Schema + +```graphql +# schema.gql + +type User @table(key: "uid") { + uid: String! @default(expr: "auth.uid") + email: String! @unique + name: String! + bio: String +} + +enum UserRole { + VIEWER + AUTHOR + EDITOR + ADMIN +} + +type BlogPermission @table(key: ["user"]) { + user: User! + role: UserRole! @default(value: VIEWER) +} + +enum PostStatus { + DRAFT + PUBLISHED + ARCHIVED +} + +type Post @table { + id: UUID! @default(expr: "uuidV4()") + author: User! + title: String! @searchable + content: String! @searchable + status: PostStatus! @default(value: DRAFT) + publishedAt: Timestamp + createdAt: Timestamp! @default(expr: "request.time") + updatedAt: Timestamp! @default(expr: "request.time") +} + +type Comment @table { + id: UUID! @default(expr: "uuidV4()") + post: Post! + author: User! + content: String! + createdAt: Timestamp! @default(expr: "request.time") +} +``` + +### Operations with Role Checks + +```graphql +# Public: Read published posts +query PublishedPosts @auth(level: PUBLIC) { + posts( + where: { status: { eq: PUBLISHED }} + orderBy: [{ publishedAt: DESC }] + ) { + id title content publishedAt + author { name } + } +} + +# Author+: Create post +mutation CreatePost($title: String!, $content: String!) + @auth(level: USER) + @transaction { + # Check user is at least AUTHOR + query @redact { + blogPermission(key: { user: { uid_expr: "auth.uid" }}) + @check(expr: "this != null", message: "No permission record") { + role @check(expr: "this in ['AUTHOR', 'EDITOR', 'ADMIN']", message: "Must be author+") + } + } + post_insert(data: { + author: { uid_expr: "auth.uid" } + title: $title + content: $content + }) +} + +# Editor+: Publish any post +mutation PublishPost($id: UUID!) + @auth(level: USER) + @transaction { + query @redact { + blogPermission(key: { user: { uid_expr: "auth.uid" }}) { + role @check(expr: "this in ['EDITOR', 'ADMIN']", message: "Must be editor+") + } + } + post_update(id: $id, data: { + status: PUBLISHED + publishedAt_expr: "request.time" + }) +} + +# Admin: Grant role +mutation GrantRole($userUid: String!, $role: UserRole!) + @auth(level: USER) + @transaction { + query @redact { + blogPermission(key: { user: { uid_expr: "auth.uid" }}) { + role @check(expr: "this == 'ADMIN'", message: "Must be admin") + } + } + blogPermission_upsert(data: { + user: { uid: $userUid } + role: $role + }) +} +``` + +--- + +## Native SQL Examples + +For scenarios where standard GraphQL cannot express the required database logic, use Native SQL. + +### Basic SELECT with field aliasing + +```graphql +query GetMoviesByGenre($genre: String!, $limit: Int!) @auth(level: PUBLIC) { + movies: _select( + sql: """ + SELECT id, title, release_year, rating + FROM movie + WHERE genre = $1 + ORDER BY release_year DESC + LIMIT $2 + """ + params: [$genre, $limit] + ) +} +``` + +### Basic UPDATE + +```graphql +mutation UpdateMovieRating($movieId: UUID!, $newRating: Float!) @auth(level: USER) { + _execute( + sql: """ + UPDATE movie + SET rating = $2 + WHERE id = $1 + """ + params: [$movieId, $newRating] + ) +} +``` + +### Advanced aggregation with RANK + +```graphql +query GetMoviesRankedByRating @auth(level: PUBLIC) { + _select( + sql: """ + SELECT + id + title + rating + RANK() OVER (ORDER BY rating DESC) as rank + FROM movie + WHERE rating IS NOT NULL + LIMIT 20 + """ + params: [] + ) +} +``` + +### UPDATE with RETURNING and Auth Context + +```graphql +mutation UpdateMyReviewText($movieId: UUID!, $newText: String!) @auth(level: USER) { + updatedReview: _executeReturningFirst( + sql: """ + UPDATE review + SET text = $2 + WHERE movie_id = $1 AND user_uid = $3 + RETURNING movie_id, user_uid, rating, text + """ + params: [$movieId, $newText, {_expr: "auth.uid"}] + ) +} +``` + +### Advanced CTE with upserts (atomic get-or-create) + +*Note: Data-modifying CTEs are only supported by `_execute`, not `_executeReturning`.* + +```graphql +mutation CreateMovieCTE($movieId: UUID!, $userUid: String!, $reviewId: UUID!) @auth(level: USER) { + _execute( + sql: """ + WITH + new_user AS ( + INSERT INTO "user" (uid, email, display_name) + VALUES ($2, 'auto@example.com', 'Auto-Generated User') + ON CONFLICT (uid) DO NOTHING + RETURNING uid + ) + movie AS ( + INSERT INTO movie (id, title, poster_url, release_year, genre) + VALUES ($1, 'Auto-Generated Movie', 'https://placeholder.com', 2025, 'Sci-Fi') + ON CONFLICT (id) DO NOTHING + RETURNING id + ) + INSERT INTO review (id, movie_id, user_uid, rating, text, created_at) + VALUES ( + $3 + $1 + $2 + 5 + 'Good!' + NOW() + ) + """ + params: [$movieId, $userUid, $reviewId] + ) +} +``` + +### Multi-statement Transactions + +Because `mutation` operations are single requests, you can chain multiple `_execute` commands within a `@transaction` to ensure they all succeed or fail together. + +```graphql +mutation SafeTransfer($from: UUID!, $to: UUID!, $amount: Float!) @auth(level: USER) @transaction { + deduct: _execute( + sql: "UPDATE account SET balance = balance - $2 WHERE id = $1" + params: [$from, $amount] + ) + add: _execute( + sql: "UPDATE account SET balance = balance + $2 WHERE id = $1" + params: [$to, $amount] + ) +} +``` + +### Use of extensions (e.g. PostGIS for geospatial data) + +*Prerequisite:* You must enable the extension on your underlying Cloud SQL instance by connecting to your database as the postgres user and running: +```sql +CREATE EXTENSION IF NOT EXISTS postgis; +``` + +```graphql +query GetNearbyActiveRestaurants($userLong: Float!, $userLat: Float!, $maxDistanceMeters: Float!) @auth(level: USER) { + nearby: _select( + sql: """ + SELECT + id + name + tags + ST_Distance( + ST_MakePoint((metadata->>'longitude')::float, (metadata->>'latitude')::float)::geography + ST_MakePoint($1, $2)::geography + ) as distance_meters + FROM restaurant + WHERE active = true + AND metadata ? 'longitude' AND metadata ? 'latitude' + AND ST_DWithin( + ST_MakePoint((metadata->>'longitude')::float, (metadata->>'latitude')::float)::geography + ST_MakePoint($1, $2)::geography + $3 + ) + ORDER BY distance_meters ASC + LIMIT 10 + """ + params: [$userLong, $userLat, $maxDistanceMeters] + ) +} +``` +*After running the query using a client SDK, the result will be in `data.nearby`.* diff --git a/transformations/android-studio/skills/firebase-data-connect-basics/reference/advanced.md b/transformations/android-studio/skills/firebase-data-connect-basics/reference/advanced.md new file mode 100644 index 00000000..307aeb84 --- /dev/null +++ b/transformations/android-studio/skills/firebase-data-connect-basics/reference/advanced.md @@ -0,0 +1,303 @@ +# Advanced Features Reference + +## Contents +- [Vector Similarity Search](#vector-similarity-search) +- [Full-Text Search](#full-text-search) +- [Cloud Functions Integration](#cloud-functions-integration) +- [Data Seeding & Bulk Operations](#data-seeding--bulk-operations) + +--- + +## Vector Similarity Search + +Semantic search using Vertex AI embeddings and PostgreSQL's `pgvector`. + +### Schema Setup + +```graphql +type Movie @table { + id: UUID! @default(expr: "uuidV4()") + title: String! + description: String + # Vector field for embeddings - size must match model output (768 for gecko) + descriptionEmbedding: Vector! @col(size: 768) +} +``` + +### Generate Embeddings in Mutations + +Use `_embed` server value to auto-generate embeddings via Vertex AI: + +```graphql +mutation CreateMovieWithEmbedding($title: String!, $description: String!) + @auth(level: USER) { + movie_insert(data: { + title: $title + description: $description + descriptionEmbedding_embed: { + model: "textembedding-gecko@003" + text: $description + } + }) +} +``` + +### Similarity Search Query + +SQL Connect generates `_similarity` fields for Vector columns: + +```graphql +query SearchMovies($query: String!) @auth(level: PUBLIC) { + movies_descriptionEmbedding_similarity( + compare_embed: { model: "textembedding-gecko@003", text: $query } + method: L2, # L2, COSINE, or INNER_PRODUCT + within: 2.0, # Max distance threshold + limit: 5 + ) { + id + title + description + _metadata { distance } # See how close each result is + } +} +``` + +### Similarity Parameters + +| Parameter | Description | +|-----------|-------------| +| `compare` | Raw Vector to compare against | +| `compare_embed` | Generate embedding from text via Vertex AI | +| `method` | Distance function: `L2`, `COSINE`, `INNER_PRODUCT` | +| `within` | Max distance (results further are excluded) | +| `where` | Additional filters | +| `limit` | Max results to return | + +### Custom Embeddings + +Pass pre-computed vectors directly: + +```graphql +mutation StoreCustomEmbedding($id: UUID!, $embedding: Vector!) @auth(level: USER) { + movie_update(id: $id, data: { descriptionEmbedding: $embedding }) +} + +query SearchWithCustomVector($vector: Vector!) @auth(level: PUBLIC) { + movies_descriptionEmbedding_similarity( + compare: $vector + method: COSINE + limit: 10 + ) { id title } +} +``` + +--- + +## Full-Text Search + +Fast keyword/phrase search using PostgreSQL's full-text capabilities. + +### Enable with @searchable + +```graphql +type Movie @table { + title: String! @searchable + description: String @searchable(language: "english") + genre: String @searchable +} +``` + +### Search Query + +SQL Connect generates `_search` fields: + +```graphql +query SearchMovies($query: String!) @auth(level: PUBLIC) { + movies_search( + query: $query + queryFormat: QUERY, # QUERY, PLAIN, PHRASE, or ADVANCED + limit: 20 + ) { + id title description + _metadata { relevance } # Relevance score + } +} +``` + +### Query Formats + +| Format | Description | +|--------|-------------| +| `QUERY` | Web-style (default): quotes, AND, OR supported | +| `PLAIN` | Match all words, any order | +| `PHRASE` | Match exact phrase | +| `ADVANCED` | Full tsquery syntax | + +### Tuning Results + +```graphql +query SearchWithThreshold($query: String!) @auth(level: PUBLIC) { + movies_search( + query: $query + relevanceThreshold: 0.05, # Min relevance score + where: { genre: { eq: "Action" }} + orderBy: [{ releaseYear: DESC }] + ) { id title } +} +``` + +### Supported Languages + +`english` (default), `french`, `german`, `spanish`, `italian`, `portuguese`, `dutch`, `danish`, `finnish`, `norwegian`, `swedish`, `russian`, `arabic`, `hindi`, `simple` + +--- + +## Cloud Functions Integration + +Trigger Cloud Functions when mutations execute. + +### Basic Trigger (Node.js) + +```typescript +import { onMutationExecuted } from "firebase-functions/dataconnect"; +import { logger } from "firebase-functions"; + +export const onUserCreate = onMutationExecuted( + { + service: "myService" + connector: "default" + operation: "CreateUser" + region: "us-central1" # Must match SQL Connect location + } + (event) => { + const variables = event.data.payload.variables; + const returnedData = event.data.payload.data; + + logger.info("User created:", returnedData); + // Send welcome email, sync to analytics, etc. + } +); +``` + +### Basic Trigger (Python) + +```python +from firebase_functions import dataconnect_fn, logger + +@dataconnect_fn.on_mutation_executed( + service="myService" + connector="default" + operation="CreateUser" +) +def on_user_create(event: dataconnect_fn.Event): + variables = event.data.payload.variables + returned_data = event.data.payload.data + logger.info("User created:", returned_data) +``` + +### Event Data + +```typescript +// event.authType: "app_user" | "unauthenticated" | "admin" +// event.authId: Firebase Auth UID (for app_user) +// event.data.payload.variables: mutation input variables +// event.data.payload.data: mutation response data +// event.data.payload.errors: any errors that occurred +``` + +### Filtering with Wildcards + +```typescript +// Trigger on all User* mutations +export const onUserMutation = onMutationExecuted( + { operation: "User*" } + (event) => { /* ... */ } +); + +// Capture operation name +export const onAnyMutation = onMutationExecuted( + { service: "myService", operation: "{operationName}" } + (event) => { + console.log("Operation:", event.params.operationName); + } +); +``` + +### Use Cases + +- **Data sync**: Replicate to Firestore, BigQuery, external APIs +- **Notifications**: Send emails, push notifications on events +- **Async workflows**: Image processing, data aggregation +- **Audit logging**: Track all data changes + +> ⚠️ **Avoid infinite loops**: Don't trigger mutations that would fire the same trigger. Use filters to exclude self-triggered events. + +--- + +## Data Seeding & Bulk Operations + +### Local Prototyping with _insertMany + +```graphql +mutation SeedMovies @transaction { + movie_insertMany(data: [ + { id: "uuid-1", title: "Movie 1", genre: "Action" } + { id: "uuid-2", title: "Movie 2", genre: "Drama" } + { id: "uuid-3", title: "Movie 3", genre: "Comedy" } + ]) +} +``` + +### Reset Data with _upsertMany + +```graphql +mutation ResetData { + movie_upsertMany(data: [ + { id: "uuid-1", title: "Movie 1", genre: "Action" } + { id: "uuid-2", title: "Movie 2", genre: "Drama" } + ]) +} +``` + +### Clear All Data + +```graphql +mutation ClearMovies { + movie_deleteMany(all: true) +} +``` + +### Production: Admin SDK Bulk Operations + +```typescript +import { initializeApp } from 'firebase-admin/app'; +import { getDataConnect } from 'firebase-admin/data-connect'; + +const app = initializeApp(); +const dc = getDataConnect({ location: "us-central1", serviceId: "my-service" }); + +const movies = [ + { id: "uuid-1", title: "Movie 1", genre: "Action" } + { id: "uuid-2", title: "Movie 2", genre: "Drama" } +]; + +// Bulk insert +await dc.insertMany("movie", movies); + +// Bulk upsert +await dc.upsertMany("movie", movies); + +// Single operations +await dc.insert("movie", movies[0]); +await dc.upsert("movie", movies[0]); +``` + +### Emulator Data Persistence + +```bash +# Export emulator data +npx -y firebase-tools@latest emulators:export ./seed-data + +# Start with saved data +npx -y firebase-tools@latest emulators:start --only dataconnect --import=./seed-data +``` diff --git a/transformations/android-studio/skills/firebase-data-connect-basics/reference/config.md b/transformations/android-studio/skills/firebase-data-connect-basics/reference/config.md new file mode 100644 index 00000000..765c416a --- /dev/null +++ b/transformations/android-studio/skills/firebase-data-connect-basics/reference/config.md @@ -0,0 +1,267 @@ +# Configuration Reference + +## Contents +- [Project Structure](#project-structure) +- [dataconnect.yaml](#dataconnectyaml) +- [connector.yaml](#connectoryaml) +- [Firebase CLI Commands](#firebase-cli-commands) +- [Emulator](#emulator) +- [Deployment](#deployment) + +--- + +## Project Structure + +``` +project-root/ +├── firebase.json # Firebase project config +└── dataconnect/ + ├── dataconnect.yaml # Service configuration + ├── schema/ + │ └── schema.gql # Data model (types, relationships) + └── connector/ + ├── connector.yaml # Connector config + SDK generation + ├── queries.gql # Query operations + └── mutations.gql # Mutation operations (optional separate file) +``` + +--- + +## dataconnect.yaml + +Main SQL Connect service configuration: + +```yaml +specVersion: "v1" +serviceId: "my-service" +location: "us-central1" +schemaValidation: "STRICT" # or "COMPATIBLE" +schema: + source: "./schema" + datasource: + postgresql: + database: "fdcdb" + cloudSql: + instanceId: "my-instance" +connectorDirs: ["./connector"] +``` + +| Field | Description | +|-------|-------------| +| `specVersion` | Always `"v1"` | +| `serviceId` | Unique identifier for the service | +| `location` | GCP region (us-central1, us-east4, europe-west1, etc.) | +| `schemaValidation` | Deployment mode: `"STRICT"` (must match exactly) or `"COMPATIBLE"` (backward compatible) | +| `schema.source` | Path to schema directory | +| `schema.datasource` | PostgreSQL connection config | +| `connectorDirs` | List of connector directories | + +### Cloud SQL Configuration + +```yaml +schema: + datasource: + postgresql: + database: "my-database" # Database name + cloudSql: + instanceId: "my-instance" # Cloud SQL instance ID +``` + +--- + +## connector.yaml + +Connector configuration and SDK generation: + +```yaml +connectorId: "default" +generate: + javascriptSdk: + outputDir: "../web/src/lib/dataconnect" + package: "@myapp/dataconnect" + kotlinSdk: + outputDir: "../android/app/src/main/kotlin/com/myapp/dataconnect" + package: "com.myapp.dataconnect" + swiftSdk: + outputDir: "../ios/MyApp/DataConnect" +``` + +### SDK Generation Options + +| SDK | Fields | +|-----|--------| +| `javascriptSdk` | `outputDir`, `package` | +| `kotlinSdk` | `outputDir`, `package` | +| `swiftSdk` | `outputDir` | +| `nodeAdminSdk` | `outputDir`, `package` (for Admin SDK) | + +--- + +## Firebase CLI Commands + +### Initialize SQL Connect + +```bash +# Interactive setup +npx -y firebase-tools@latest init dataconnect + +# Set project +npx -y firebase-tools@latest use +``` + +### Local Development + +```bash +# Start emulator +npx -y firebase-tools@latest emulators:start --only dataconnect + +# Start with database seed data +npx -y firebase-tools@latest emulators:start --only dataconnect --import=./seed-data + +# Generate SDKs +npx -y firebase-tools@latest dataconnect:sdk:generate + +# Watch for schema changes (auto-regenerate) +npx -y firebase-tools@latest dataconnect:sdk:generate --watch +``` + +### Schema Management + +```bash +# Compare local schema to production +npx -y firebase-tools@latest dataconnect:sql:diff + + +# Apply migration +npx -y firebase-tools@latest dataconnect:sql:migrate +``` + +### Deployment + +```bash +# Deploy SQL Connect service +npx -y firebase-tools@latest deploy --only dataconnect + +# Deploy specific connector +npx -y firebase-tools@latest deploy --only dataconnect:connector-id + +# Deploy with schema migration +npx -y firebase-tools@latest deploy --only dataconnect --force +``` + +--- + +## Emulator + +### Start Emulator + +```bash +npx -y firebase-tools@latest emulators:start --only dataconnect +``` + +Default ports: +- SQL Connect: `9399` +- PostgreSQL: `9939` (local PostgreSQL instance) + +### Emulator Configuration (firebase.json) + +```json +{ + "emulators": { + "dataconnect": { + "port": 9399 + } + } +} +``` + +### Connect from SDK + +```typescript +// Web +import { connectDataConnectEmulator } from 'firebase/data-connect'; +connectDataConnectEmulator(dc, 'localhost', 9399); + +// Android +connector.dataConnect.useEmulator("10.0.2.2", 9399) + +// iOS +connector.useEmulator(host: "localhost", port: 9399) + + +``` + +### Seed Data + +Create seed data files and import: + +```bash +# Export current emulator data +npx -y firebase-tools@latest emulators:export ./seed-data + +# Start with seed data +npx -y firebase-tools@latest emulators:start --only dataconnect --import=./seed-data +``` + +--- + +## Deployment + +### Deploy Workflow + +1. **Test locally** with emulator +2. **Generate SQL diff**: `npx -y firebase-tools@latest dataconnect:sql:diff` +3. **Review migration**: Check breaking changes +4. **Deploy**: `npx -y firebase-tools@latest deploy --only dataconnect` + +### Schema Migrations + +SQL Connect auto-generates PostgreSQL migrations: + +```bash +# Preview migration +npx -y firebase-tools@latest dataconnect:sql:diff + +# Apply migration (interactive) +npx -y firebase-tools@latest dataconnect:sql:migrate + +# Force migration (non-interactive) +npx -y firebase-tools@latest dataconnect:sql:migrate --force +``` + +### Breaking Changes + +Some schema changes require special handling: +- Removing required fields +- Changing field types +- Removing tables + +Use `--force` flag to acknowledge breaking changes during deploy. + +### CI/CD Integration + +```yaml +# GitHub Actions example +- name: Deploy SQL Connect + run: | + npx -y firebase-tools@latest deploy --only dataconnect --token ${{ secrets.FIREBASE_TOKEN }} --force +``` + +--- + +## VS Code Extension + +Install "Firebase SQL Connect" extension for: +- Schema intellisense and validation +- GraphQL operation testing +- Emulator integration +- SDK generation on save + +### Extension Settings + +```json +{ + "firebase.dataConnect.autoGenerateSdk": true + "firebase.dataConnect.emulator.port": 9399 +} +``` diff --git a/transformations/android-studio/skills/firebase-data-connect-basics/reference/native_sql.md b/transformations/android-studio/skills/firebase-data-connect-basics/reference/native_sql.md new file mode 100644 index 00000000..1a78e644 --- /dev/null +++ b/transformations/android-studio/skills/firebase-data-connect-basics/reference/native_sql.md @@ -0,0 +1,122 @@ +# Native SQL Operations + +Always default to Native GraphQL. Use Native SQL **only** when you need database-specific features not available in GraphQL (e.g., PostGIS, Window Functions, Complex Aggregations, or specific DML CTEs). + +## Core Agent Constraints + +When generating Native SQL operations, you are bypassing GraphQL and talking directly to PostgreSQL. You **MUST** adhere to these strict constraints: + +1. **Operation Syntax Isolation:** Never mix Native SQL positional parameters (`$1`) with standard GraphQL named variables (`$id`). The `sql:` argument MUST be a hardcoded string literal block (`"""SELECT..."""`), not a GraphQL variable. +2. **Table & Column Mapping (Case Sensitivity):** + * **Default `snake_case` Conversion:** By default, SQL Connect converts `PascalCase` types and `camelCase` fields to `snake_case` in the database. + * *Schema:* `type UserProfile { releaseYear: Int }` -> *Native SQL:* `SELECT release_year FROM user_profile` + * **Explicit Overrides (Requires Double Quotes):** If the schema uses `@table(name: "ExactName")` or `@col(name: "ExactCol")`, you **MUST wrap the identifier in double quotes** if it contains capital letters (e.g., `SELECT * FROM "ExactName"`). Without quotes, Postgres folds it to lowercase and fails validation. + +## Syntax rules & limitations + +Native SQL enforces strict parsing rules to ensure security and prevent SQL injection: + +* **String Literals Only:** The `sql` argument must be a hardcoded string literal block (`"""SELECT..."""`) directly in the `.gql` file. It **cannot** be a GraphQL variable. +* **Validation:** Do **NOT** use DDL in any operations (modify the `schema.gql` file instead for table/column changes). Furthermore, `query` operations cannot contain DML and must start with `SELECT`, `TABLE`, or `WITH`. +* **Parameters:** Use strict positional parameters (`$1`, `$2`) that match the `params` array order. Named parameters (`$id`, `:name`) are **forbidden**. +* **Comments:** Use block comments (`/* ... */`). Line comments (`--`) are **forbidden** because they can truncate subsequent clauses during query compilation. If you comment out a line containing a parameter (e.g., `/* WHERE id = $1 */`), you must also remove that parameter from the `params` list, or it will fail with `unused parameter: $1`. +* **Strings:** Extended string literals (`E'...'`) and dollar-quoted strings (`$$...$$`) are supported. +* **Context Maps (`_expr`):** Variables **cannot** be used inside `_expr` fields; to ensure security, `_expr` must be a static string (e.g., `{_expr: "auth.uid"}`, not `{_expr: $uidVar}`). + +## Native SQL Root Fields + +Operations are executed using the permissions granted to the SQL Connect service account. You can alias the root field (e.g., `movies: _select`) to make the client response cleaner (`data.movies` instead of `data._select`). + +> **Note on `Any` Return Types:** Because Native SQL completely bypasses GraphQL's strong typing, queries like `_select` and `_executeReturning` return the generic `Any` scalar type. The generated client SDKs (TypeScript, Swift, Kotlin, Dart) will type this as `any` (or equivalent). **AGENT INSTRUCTION**: When you generate client-side code that consumes these operations, you MUST manually cast or validate the shape of the data, as the typical type safety of SQL Connect will not be present. + +Use these root fields in `query` or `mutation` operations: + +### Query Fields (Read-Only) + +* `_select`: Executes a SQL query returning zero or more rows. Returns `[Any]`. + ```graphql + query GetMovies($genre: String!) @auth(level: PUBLIC) { + movies: _select( + sql: "SELECT id, title FROM movie WHERE genre = $1" + params: [$genre] + ) + } + ``` +* `_selectFirst`: Executes a SQL query expected to return zero or one row. Returns `Any` or `null`. + ```graphql + query GetTotalReviews @auth(level: PUBLIC) { + stats: _selectFirst( + sql: "SELECT COUNT(*) as total_reviews FROM review" + ) # params can be omitted if empty + } + ``` + +### Mutation Fields (DML) + +* `_execute`: Executes DML (`INSERT`, `UPDATE`, `DELETE`). Returns `Int` (number of rows affected). + * *Note 1:* `RETURNING` clauses are ignored in the result. + * *Note 2:* Only `_execute` supports Data-Modifying Common Table Expressions (e.g., `WITH new_row AS (INSERT...)`). + ```graphql + mutation UpdateRating($id: UUID!, $rating: Float!) @auth(level: USER) { + _execute( + sql: "UPDATE movie SET rating = $2 WHERE id = $1" + params: [$id, $rating] + ) + } + ``` +* `_executeReturning`: Executes DML with a `RETURNING` clause. Returns `[Any]`. Data-Modifying CTEs are **not** supported. + ```graphql + mutation DeleteUserReviews($uid: String!) @auth(level: USER) { + deletedReviews: _executeReturning( + sql: "DELETE FROM review WHERE user_id = $1 RETURNING id, rating" + params: [{_expr: "auth.uid"}] + ) + } + ``` +* `_executeReturningFirst`: Executes DML with `RETURNING`, expecting zero or one row. Returns `Any` or `null`. Data-Modifying CTEs are **not** supported. + ```graphql + mutation UpdateMyReview($movieId: UUID!, $text: String!) @auth(level: USER) { + updatedReview: _executeReturningFirst( + sql: """ + UPDATE review SET text = $2 + WHERE movie_id = $1 AND user_id = $3 + RETURNING id, text + """ + params: [$movieId, $text, {_expr: "auth.uid"}] + ) + } + ``` + +### PostgreSQL Extensions + +Native SQL allows you to directly query and utilize PostgreSQL extensions, such as `PostGIS`, without needing to map complex geometry types into your GraphQL schema or alter your underlying tables (e.g., using JSON operators to extract values and pass them into `ST_MakePoint`). + +*Note: You must enable the extension on your underlying Cloud SQL instance by connecting as the `postgres` user and running `CREATE EXTENSION IF NOT EXISTS ...;`* + +*(See `examples.md` for a full `GetNearbyActiveRestaurants` implementation).* + +## ⚠️ Security: Stored Procedures & Dynamic SQL + +SQL Connect parameterizes inputs at the GraphQL boundary automatically. However, if your Native SQL calls **custom PL/pgSQL stored procedures**, you must manually prevent 2nd-order SQL injection: + +* **NEVER** concatenate user input into an `EXECUTE` string (`EXECUTE 'UPDATE ' || table || ' SET x=' || val;`). +* **DO** use the `USING` clause to bind data values safely. +* **DO** use `format('%I')` for safe database identifier injection. +* **DO** validate dynamic table/column names against a strict hardcoded allowlist. + +**Secure PL/pgSQL Pattern:** +```sql +CREATE OR REPLACE PROCEDURE secure_update(target_table TEXT, new_value TEXT, row_id INT) +LANGUAGE plpgsql AS $$ +BEGIN + -- 1. Strict Allowlist for Identifiers + IF target_table NOT IN ('orders', 'users', 'inventory') THEN + RAISE EXCEPTION 'Invalid table name'; + END IF; + + -- 2. format(%I) for Identifiers, USING for Data + EXECUTE format('UPDATE %I SET status = $1 WHERE id = $2', target_table) + USING new_value, row_id; +END; +$$; +``` diff --git a/transformations/android-studio/skills/firebase-data-connect-basics/reference/operations.md b/transformations/android-studio/skills/firebase-data-connect-basics/reference/operations.md new file mode 100644 index 00000000..c0c12ca1 --- /dev/null +++ b/transformations/android-studio/skills/firebase-data-connect-basics/reference/operations.md @@ -0,0 +1,376 @@ +# Operations Reference + +## Contents +- [Generated Fields](#generated-fields) +- [Queries](#queries) +- [Mutations](#mutations) +- [Key Scalars](#key-scalars) +- [Multi-Step Operations](#multi-step-operations) + +--- + +## Generated Fields + +SQL Connect auto-generates fields for each `@table` type: + +| Generated Field | Purpose | Example | +|-----------------|---------|---------| +| `movie(id: UUID, key: Key, first: Row)` | Get single record | `movie(id: $id)` or `movie(first: {where: ...})` | +| `movies(where: ..., orderBy: ..., limit: ..., offset: ..., distinct: ..., having: ...)` | List/filter records | `movies(where: {...})` | +| `movie_insert(data: ...)` | Create record | Returns key | +| `movie_insertMany(data: [...])` | Bulk create | Returns keys | +| `movie_update(id: ..., data: ...)` | Update by ID | Returns key or null | +| `movie_updateMany(where: ..., data: ...)` | Bulk update | Returns count | +| `movie_upsert(data: ...)` | Insert or update | Returns key | +| `movie_delete(id: ...)` | Delete by ID | Returns key or null | +| `movie_deleteMany(where: ...)` | Bulk delete | Returns count | + +### Relation Fields +For a `Post` with `author: User!`: +- `post.author` - Navigate to related User +- `user.posts_on_author` - Reverse: all Posts by User + +For many-to-many via `MovieActor`: +- `movie.actors_via_MovieActor` - Get all actors +- `actor.movies_via_MovieActor` - Get all movies + +--- + +## Referencing Generated GraphQL Schema + +**Do not guess** available queries or mutations. Review the generated schema files instead of trying to deduce them from the data model. + +1. **Location**: `.dataconnect/schema/main/` (relative to project root). +2. **Action**: Scan this directory for generated files (`query.gql`, `mutation.gql`, `relation.gql`, `input.gql`) to understand the exact shape of the API and auto-generated types. +3. **Validation**: Always run `firebase dataconnect:compile` to verify operations against the full schema. + +--- + +## Queries + +### Basic Query + +```graphql +query GetMovie($id: UUID!) @auth(level: PUBLIC) { + movie(id: $id) { + id title genre releaseYear + } +} +``` + +### List with Filtering + +```graphql +query ListMovies($genre: String, $minRating: Int) @auth(level: PUBLIC) { + movies( + where: { + genre: { eq: $genre } + rating: { ge: $minRating } + } + orderBy: [{ releaseYear: DESC }, { title: ASC }] + limit: 20 + offset: 0 + ) { + id title genre rating + } +} +``` + +### Filter Operators + +| Operator | Description | Example | +|----------|-------------|---------| +| `eq` | Equals | `{ title: { eq: "Matrix" }}` | +| `ne` | Not equals | `{ status: { ne: "deleted" }}` | +| `gt`, `ge` | Greater than (or equal) | `{ rating: { ge: 4 }}` | +| `lt`, `le` | Less than (or equal) | `{ releaseYear: { lt: 2000 }}` | +| `in` | In list | `{ genre: { in: ["Action", "Drama"] }}` | +| `nin` | Not in list | `{ status: { nin: ["deleted", "hidden"] }}` | +| `isNull` | Is null check | `{ description: { isNull: true }}` | +| `contains` | String contains | `{ title: { contains: "war" }}` | +| `startsWith` | String starts with | `{ title: { startsWith: "The" }}` | +| `endsWith` | String ends with | `{ email: { endsWith: "@gmail.com" }}` | +| `includes` | Array includes | `{ tags: { includes: "sci-fi" }}` | + +### Expression Operators (Compare with Server Values) + +Use `_expr` suffix to compare with server-side values: + +```graphql +query MyPosts @auth(level: USER) { + posts(where: { authorUid: { eq_expr: "auth.uid" }}) { + id title + } +} + +query RecentPosts @auth(level: PUBLIC) { + posts(where: { publishedAt: { lt_expr: "request.time" }}) { + id title + } +} +``` + +### Logical Operators + +```graphql +query ComplexFilter($genre: String, $minRating: Int) @auth(level: PUBLIC) { + movies(where: { + _or: [ + { genre: { eq: $genre }} + { rating: { ge: $minRating }} + ] + _and: [ + { releaseYear: { ge: 2000 }} + { status: { ne: "hidden" }} + ] + _not: { genre: { eq: "Horror" }} + }) { id title } +} +``` + +### Relational Queries + +```graphql +# Navigate relationships +query MovieWithDetails($id: UUID!) @auth(level: PUBLIC) { + movie(id: $id) { + title + # One-to-one + metadata: movieMetadata_on_movie { director } + # One-to-many + reviews: reviews_on_movie { rating user { name }} + # Many-to-many + actors: actors_via_MovieActor { name } + } +} + +# Filter by related data +query MoviesByDirector($director: String!) @auth(level: PUBLIC) { + movies(where: { + movieMetadata_on_movie: { director: { eq: $director }} + }) { id title } +} + +# Filter by null relationship (e.g., top-level categories with no parent) +# Use the generated foreign key field (e.g., parentId) +query TopLevelCategories @auth(level: PUBLIC) { + categories(where: { parentId: { eq: null } }) { + id + name + } +} +``` + +### Aliases + +```graphql +query CompareRatings($genre: String!) @auth(level: PUBLIC) { + highRated: movies(where: { genre: { eq: $genre }, rating: { ge: 8 }}) { + title rating + } + lowRated: movies(where: { genre: { eq: $genre }, rating: { lt: 5 }}) { + title rating + } +} +``` + +--- + +## Mutations + +### Create + +```graphql +mutation CreateMovie($title: String!, $genre: String) @auth(level: USER) { + movie_insert(data: { + title: $title + genre: $genre + }) +} +``` + +### Create with Server Values + +```graphql +mutation CreatePost($title: String!, $content: String!) @auth(level: USER) { + post_insert(data: { + authorUid_expr: "auth.uid", # Current user + id_expr: "uuidV4()", # Auto-generate UUID + createdAt_expr: "request.time", # Server timestamp + title: $title + content: $content + }) +} +``` + +### Update + +```graphql +mutation UpdateMovie($id: UUID!, $title: String, $genre: String) @auth(level: USER) { + movie_update( + id: $id + data: { + title: $title + genre: $genre + updatedAt_expr: "request.time" + } + ) +} +``` + +### Update Operators + +```graphql +mutation IncrementViews($id: UUID!) @auth(level: PUBLIC) { + movie_update(id: $id, data: { + viewCount_update: { inc: 1 } + }) +} + +mutation AddTag($id: UUID!, $tag: String!) @auth(level: USER) { + movie_update(id: $id, data: { + tags_update: { add: [$tag] } # add, remove, append, prepend + }) +} +``` + +| Operator | Types | Description | +|----------|-------|-------------| +| `inc` | Int, Float, Date, Timestamp | Increment value | +| `dec` | Int, Float, Date, Timestamp | Decrement value | +| `add` | Lists | Add items if not present | +| `remove` | Lists | Remove all matching items | +| `append` | Lists | Append to end | +| `prepend` | Lists | Prepend to start | + +### Upsert + +```graphql +mutation UpsertUser($email: String!, $name: String!) @auth(level: USER) { + user_upsert(data: { + uid_expr: "auth.uid" + email: $email + name: $name + }) +} +``` + +### Delete + +```graphql +mutation DeleteMovie($id: UUID!) @auth(level: USER) { + movie_delete(id: $id) +} + +mutation DeleteOldDrafts @auth(level: USER) { + post_deleteMany(where: { + status: { eq: "draft" } + createdAt: { lt_time: { now: true, sub: { days: 30 }}} + }) +} +``` + +### Filtered Updates/Deletes (User-Owned) + +```graphql +mutation UpdateMyPost($id: UUID!, $content: String!) @auth(level: USER) { + post_update( + first: { where: { + id: { eq: $id } + authorUid: { eq_expr: "auth.uid" } # Only own posts + }} + data: { content: $content } + ) +} +``` + +--- + +## Key Scalars + +Key scalars (`Movie_Key`, `User_Key`) are auto-generated types representing primary keys: + +```graphql +# Using key scalar +query GetMovie($key: Movie_Key!) @auth(level: PUBLIC) { + movie(key: $key) { title } +} + +# Variable format +# { "key": { "id": "uuid-here" } } + +# Composite key +# { "key": { "movieId": "...", "userId": "..." } } +``` + +Key scalars are returned by mutations: + +```graphql +mutation CreateAndFetch($title: String!) @auth(level: USER) { + key: movie_insert(data: { title: $title }) + # Returns: { "key": { "id": "generated-uuid" } } +} +``` + +--- + +## Multi-Step Operations + +### @transaction + +Ensures atomicity - all steps succeed or all rollback: + +```graphql +mutation CreateUserWithProfile($name: String!, $bio: String!) + @auth(level: USER) + @transaction { + # Step 1: Create user + user_insert(data: { + uid_expr: "auth.uid" + name: $name + }) + # Step 2: Create profile (uses response from step 1) + userProfile_insert(data: { + userId_expr: "response.user_insert.uid" + bio: $bio + }) +} +``` + +### Using response Binding + +Access results from previous steps: + +```graphql +mutation CreateTodoWithItem($listName: String!, $itemText: String!) + @auth(level: USER) + @transaction { + todoList_insert(data: { + id_expr: "uuidV4()" + name: $listName + }) + todoItem_insert(data: { + listId_expr: "response.todoList_insert.id", # From previous step + text: $itemText + }) +} +``` + +### Embedded Queries + +Run queries within mutations for validation: + +```graphql +mutation AddToPublicList($listId: UUID!, $item: String!) + @auth(level: USER) + @transaction { + # Step 1: Verify list exists and is public + query @redact { + todoList(id: $listId) @check(expr: "this != null", message: "List not found") { + isPublic @check(expr: "this == true", message: "List is not public") + } + } + # Step 2: Add item + todoItem_insert(data: { listId: $listId, text: $item }) +} +``` diff --git a/transformations/android-studio/skills/firebase-data-connect-basics/reference/realtime.md b/transformations/android-studio/skills/firebase-data-connect-basics/reference/realtime.md new file mode 100644 index 00000000..de3fd54e --- /dev/null +++ b/transformations/android-studio/skills/firebase-data-connect-basics/reference/realtime.md @@ -0,0 +1,179 @@ +# Realtime Reference + +## Contents +- [When to Use What](#when-to-use-what) +- [The @refresh Directive](#the-refresh-directive) +- [CEL Bindings in Conditions](#cel-bindings-in-conditions) +- [Implicit Entity Refresh signals](#implicit-entity-refresh-signals) + +--- + +## When to Use What + +SQL Connect provides three mechanisms for live data updates. Pick the right one based on what you're querying: + +| Scenario | Mechanism | Directive Needed? | +|----------|-----------|-------------------| +| Single-entity lookup by ID (e.g., `movie(id: $id)`) | **Automatic refresh** | No — SQL Connect handles it | +| List query that should update when a specific mutation runs | **Event-driven refresh** | `@refresh(onMutationExecuted: ...)` | +| Any query that should poll at a fixed interval | **Time-based polling** | `@refresh(every: ...)` | + +List queries require explicit `@refresh` to tell SQL Connect which mutations affect the result set. + +Clients consume all three using `subscribe()` instead of `execute()`. See [sdks.md](sdks.md) for per-platform subscribe patterns. + +--- + +## The @refresh Directive + +`@refresh` is a **repeatable** directive applied to **queries**. It defines when connected subscribers should receive updated data. + +### Time-Based Polling (`every`) + +Keep the query fresh with a recommended refresh interval. Note that `every` and `mutation` signals can be used together; whichever signal arrives first will trigger the refresh. + +```graphql +query MovieLeaderboard + @auth(level: PUBLIC) + @refresh(every: { seconds: 30 }) { + movies(orderBy: [{ rating: DESC }], limit: 10) { + id title rating + } +} +``` + +**Constraints:** +- The `every` argument takes a duration object: `{ seconds: Int }` +- **Minimum**: `{ seconds: 10 }` — protects against excessive server load +- **Maximum**: `{ hours: 1 }` (3600 seconds) +- Values outside this range fail validation at deploy time + +Use time-based polling when freshness matters but you don't have a specific mutation to listen for (e.g., dashboards aggregating external data, stock tickers, activity feeds). + +### Explicit Mutation Signals (`onMutationExecuted`) + +Trigger a query refresh when a specific mutation executes. This is the most common pattern for keeping lists in sync. + +```graphql +# Example with condition (refreshes only when the condition is met) +query ChatRoom($roomId: UUID!) @auth(level: PUBLIC) + @refresh(onMutationExecuted: { + operation: "SendMessage" + condition: "mutation.variables.roomId == request.variables.roomId" + }) { + messages(where: {roomId: {eq: $roomId}}, orderBy: [{createTime: DESC}], limit: 50) { + author content createTime + } +} + +# Example without condition (refreshes on any execution of the named mutation) +query ListAllMessages + @auth(level: PUBLIC) + @refresh(onMutationExecuted: { + operation: "SendMessage" + }) { + messages { id content } +} +``` + +**Arguments:** +- **`operation`** (required): The name of the mutation operation to listen for. Must match the mutation's operation name exactly. +- **`condition`** (optional): A CEL expression that must evaluate to `true` for the refresh to fire. Without a condition, every execution of the named mutation triggers a refresh. + +It's highly recommended to define fine granular conditions. Inaccurate refresh policies could consume Postgres resources and make your app slower. + +Use conditions to scope refreshes precisely — a review list should only refresh when the mutation targets the same movie, not every review across the entire app. + +### Combining Multiple @refresh Directives + +Since `@refresh` is repeatable, you can combine strategies on a single query: + +```graphql +query ActiveOrders($userId: UUID!) + @auth(level: USER) + @refresh(onMutationExecuted: { + operation: "UpdateOrderStatus" + condition: "request.variables.userId == mutation.variables.userId" + }) + @refresh(every: { seconds: 60 }) { + orders(where: { user: { id: { eq: $userId }}, status: { ne: DELIVERED }}) { + id status total updatedAt + } +} +``` + +This query refreshes whenever an order status changes for this user, *and* polls every 60 seconds as a fallback to catch any updates that might not have a direct mutation trigger. + +--- + +## CEL Bindings in Conditions + +The `condition` expression in `onMutationExecuted` has access to two contexts: + +### `request` — The Query Subscription +The state of the query being subscribed to. + +| Binding | Description | +|---------|-------------| +| `request.variables` | Variables passed to the query (e.g., `request.variables.id`) | +| `request.auth.uid` | UID of the user who subscribed | +| `request.auth.token` | Full auth token claims of the subscriber | + +### `mutation` — The Triggering Event +The mutation that just executed. + +| Binding | Description | +|---------|-------------| +| `mutation.variables` | Variables passed to the mutation (e.g., `mutation.variables.movieId`) | +| `mutation.auth.uid` | UID of the user who executed the mutation | +| `mutation.auth.token` | Full auth token claims of the mutation executor | + +### Common Patterns + +```text +# Refresh only when the mutation targets the same entity +"request.variables.id == mutation.variables.id" + +# Refresh only when the same user who subscribed makes a change +"request.auth.uid == mutation.auth.uid" + +# Refresh when a specific field value matches a condition +"request.auth.uid == mutation.auth.uid && mutation.variables.status == 'PUBLISHED'" + +# Refresh when a specific flag is set in the mutation +"mutation.variables.isPublic == true" +``` + +--- + +## Implicit Entity Refresh signals + +For single-entity lookups by unique identifier, SQL Connect handles refreshes automatically — no `@refresh` directive needed. + +**What qualifies:** +- Queries fetching one entity by its primary key: `movie(id: $id)`, `user(key: { uid: $uid })` +- If a single-entity mutation modifies that specific entity, all active subscribers automatically receive the update. Supported operations include: + * `_insert(data)` or `_insertMany(data)` + * `_upsert(data)` or `_upsertMany(data)` + * `_update(id)` or `_update(key)` + * `_delete(id)` or `_delete(key)` +- **Note**: Bulk operations like `_updateMany` and `_deleteMany` do **not** trigger automatic entity refreshes. + +**What does NOT qualify:** +- List queries: `movies(where: {...})`, `users { id name }` — these require explicit `@refresh` +- Nested query with JOINs +- Aggregation +- Native SQL +- Customized Resolver (if supported) + +```graphql +# When subscribed to, this query auto-refreshes when movie data changes — no @refresh needed +query GetMovie($id: UUID!) @auth(level: PUBLIC) { + movie(id: $id) { + id title rating description + reviews_on_movie { rating text user { displayName } } + } +} +``` + +To consume automatic refreshes on the client, use `subscribe()` instead of `execute()` — the same client pattern works regardless of whether the refresh is automatic or directive-driven. diff --git a/transformations/android-studio/skills/firebase-data-connect-basics/reference/schema.md b/transformations/android-studio/skills/firebase-data-connect-basics/reference/schema.md new file mode 100644 index 00000000..0e2ff950 --- /dev/null +++ b/transformations/android-studio/skills/firebase-data-connect-basics/reference/schema.md @@ -0,0 +1,278 @@ +# Schema Reference + +## Contents +- [Defining Types](#defining-types) +- [Core Directives](#core-directives) +- [Relationships](#relationships) +- [Data Types](#data-types) +- [Enumerations](#enumerations) + +--- + +## Defining Types + +Types with `@table` map to PostgreSQL tables. SQL Connect auto-generates an implicit `id: UUID!` primary key. + +```graphql +type Movie @table { + # id: UUID! is auto-added + title: String! + releaseYear: Int + genre: String +} +``` + +### Customizing Tables + +```graphql +type Movie @table(name: "movies", key: "id", singular: "movie", plural: "movies") { + id: UUID! @col(name: "movie_id") @default(expr: "uuidV4()") + title: String! + releaseYear: Int @col(name: "release_year") + genre: String @col(dataType: "varchar(20)") +} +``` + +### User Table with Auth + +```graphql +type User @table(key: "uid") { + uid: String! @default(expr: "auth.uid") + email: String! @unique + displayName: String @col(dataType: "varchar(100)") + createdAt: Timestamp! @default(expr: "request.time") +} +``` + +--- + +## Core Directives + +### @table +Defines a database table. + +| Argument | Description | +|----------|-------------| +| `name` | PostgreSQL table name (snake_case default) | +| `key` | Primary key field(s), default `["id"]` | +| `singular` | Singular name for generated fields | +| `plural` | Plural name for generated fields | + +### @col +Customizes column mapping. + +| Argument | Description | +|----------|-------------| +| `name` | Column name in PostgreSQL | +| `dataType` | PostgreSQL type: `serial`, `varchar(n)`, `text`, etc. | +| `size` | Required for `Vector` type | + +### @default +Sets default value for inserts. + +| Argument | Description | +|----------|-------------| +| `value` | Literal value: `@default(value: "draft")` | +| `expr` | CEL expression: `@default(expr: "uuidV4()")`, `@default(expr: "auth.uid")`, `@default(expr: "request.time")` | +| `sql` | Raw SQL: `@default(sql: "now()")` | + +**Common expressions:** +- `uuidV4()` - Generate UUID +- `auth.uid` - Current user's Firebase Auth UID +- `request.time` - Server timestamp + +### @unique +Adds unique constraint. + +```graphql +type User @table { + email: String! @unique +} + +# Composite unique +type Review @table @unique(fields: ["movie", "user"]) { + movie: Movie! + user: User! + rating: Int +} +``` + +### @index +Creates database index for query performance. + +```graphql +type Movie @table @index(fields: ["genre", "releaseYear"], order: [ASC, DESC]) { + title: String! @index + genre: String + releaseYear: Int +} +``` + +| Argument | Description | +|----------|-------------| +| `fields` | Fields for composite index (on @table) | +| `order` | `[ASC]` or `[DESC]` for each field | +| `type` | `BTREE` (default), `GIN` (arrays), `HNSW`/`IVFFLAT` (vectors) | + +### @searchable +Enables full-text search on String fields. + +```graphql +type Post @table { + title: String! @searchable + body: String! @searchable(language: "english") +} + +# Usage +query SearchPosts($q: String!) @auth(level: PUBLIC) { + posts_search(query: $q) { id title body } +} +``` + +--- + +## Relationships + +### One-to-Many (Implicit Foreign Key) + +```graphql +type Post @table { + id: UUID! @default(expr: "uuidV4()") + author: User! # Creates authorId foreign key + title: String! +} + +type User @table { + id: UUID! @default(expr: "uuidV4()") + name: String! + # Auto-generated: posts_on_author: [Post!]! +} +``` + +### @ref Directive +Customizes foreign key reference. + +```graphql +type Post @table { + author: User! @ref(fields: "authorId", references: "id") + authorId: UUID! # Explicit FK field +} +``` + +| Argument | Description | +|----------|-------------| +| `fields` | Local FK field name(s) | +| `references` | Target field(s) in referenced table | +| `constraintName` | PostgreSQL constraint name | + +**Cascade behavior:** +- Required reference (`User!`): CASCADE DELETE (post deleted when user deleted) +- Optional reference (`User`): SET NULL (authorId set to null when user deleted) + +### One-to-One + +Use `@unique` on the reference field: + +```graphql +type User @table { id: UUID! name: String! } + +type UserProfile @table { + user: User! @unique # One profile per user + bio: String + avatarUrl: String +} + +# Query: user.userProfile_on_user +``` + +### Many-to-Many + +Use a join table with composite primary key: + +```graphql +type Movie @table { id: UUID! title: String! } +type Actor @table { id: UUID! name: String! } + +type MovieActor @table(key: ["movie", "actor"]) { + movie: Movie! + actor: Actor! + role: String! # Extra data on relationship +} + +# Generated fields: +# - movie.actors_via_MovieActor: [Actor!]! +# - actor.movies_via_MovieActor: [Movie!]! +# - movie.movieActors_on_movie: [MovieActor!]! +``` + +--- + +## Data Types + +| GraphQL Type | PostgreSQL Default | Other PostgreSQL Types | +|--------------|-------------------|----------------------| +| `String` | `text` | `varchar(n)`, `char(n)` | +| `Int` | `int4` | `int2`, `serial` | +| `Int64` | `bigint` | `bigserial`, `numeric` | +| `Float` | `float8` | `float4`, `numeric` | +| `Boolean` | `boolean` | | +| `UUID` | `uuid` | | +| `Date` | `date` | | +| `Timestamp` | `timestamptz` | Stored as UTC | +| `Any` | `jsonb` | | +| `Vector` | `vector` | Requires `@col(size: N)` | +| `[Type]` | Array | e.g., `[String]` → `text[]` | + +--- + +## Enumerations + +```graphql +enum Status { + DRAFT + PUBLISHED + ARCHIVED +} + +type Post @table { + status: Status! @default(value: DRAFT) + allowedStatuses: [Status!] +} +``` + +**Rules:** +- Enum names: PascalCase, no underscores +- Enum values: UPPER_SNAKE_CASE +- Values are ordered (for comparison operations) +- Changing order or removing values is a breaking change + +--- + +## Views (Advanced) + +Map custom SQL queries to GraphQL types: + +```graphql +type MovieStats @view(sql: """ + SELECT + movie_id + COUNT(*) as review_count + AVG(rating) as avg_rating + FROM review + GROUP BY movie_id +""") { + movie: Movie @unique + reviewCount: Int + avgRating: Float +} + +# Query movies with stats +query TopMovies @auth(level: PUBLIC) { + movies(orderBy: [{ rating: DESC }]) { + title + stats: movieStats_on_movie { + reviewCount avgRating + } + } +} +``` diff --git a/transformations/android-studio/skills/firebase-data-connect-basics/reference/sdk_admin_node.md b/transformations/android-studio/skills/firebase-data-connect-basics/reference/sdk_admin_node.md new file mode 100644 index 00000000..35bfeafc --- /dev/null +++ b/transformations/android-studio/skills/firebase-data-connect-basics/reference/sdk_admin_node.md @@ -0,0 +1,121 @@ +# Admin Node SDK + +Consult this file when writing server-side code (e.g., Cloud Functions) that needs elevated privileges or needs to impersonate specific users. + +### Best Practices for Agents +- **Understand Operation Storage**: SQL Connect queries and mutations are stored on the server like Cloud Functions. Clients do not submit the raw operations. Therefore, **whenever you update operations, you must regenerate the SDK and redeploy services** that use it. +- **Follow Least Privilege**: Admin SDKs have unrestricted access by default. Always use impersonation when possible to limit access. +- **Impersonation**: Use the `impersonate` parameter to run operations as a specific user or as an unauthenticated user. +- **Impersonation Variables**: If you call an operation with optional variables and want to pass impersonation options but without variables, you **MUST** pass `undefined` as the first argument (variables) to clearly indicate no variables are being provided. +- **Admin Operations**: If you create operations intended only for administration, define them with `@auth(level: NO_ACCESS)`. This ensures they can only be called via the Admin SDK with unrestricted access. +- **Resilient Enum Handling**: JavaScript/TypeScript does not enforce exhaustive checks on enums. Always add a `default` branch to `switch` statements or an `else` branch to handle unknown values gracefully when schemas evolve. + +### Configuration in `connector.yaml` + +To generate an Admin SDK, add the `adminNodeSdk` block to your `connector.yaml`: + +```yaml +connectorId: my-connector +generate: + adminNodeSdk: + outputDir: "./admin-sdk" + package: "@dataconnect/admin-generated" + packageJsonDir: "." # Directory containing package.json +``` + +### Generation + +Run the generation command: + +```bash +npx -y firebase-tools@latest dataconnect:sdk:generate +``` + +### Usage Examples + +#### 1. Impersonating an Unauthenticated User +Unauthenticated users can only run operations marked as `PUBLIC`. + +```typescript +import { initializeApp } from "firebase-admin/app"; +import { getDataConnect } from "firebase-admin/data-connect"; +import { connectorConfig, getSongs } from "@dataconnect/admin-generated"; + +const adminApp = initializeApp(); +const adminDc = getDataConnect(connectorConfig); + +const songs = await getSongs( + adminDc + { limit: 4 } + { impersonate: { unauthenticated: true } } +); +``` + +#### 2. Impersonating a Specific User (Cloud Functions) +When using callable Cloud Functions, the authentication token is automatically verified. + +```typescript +import { HttpsError, onCall } from "firebase-functions/https"; +import { getMyFavoriteSongs } from "@dataconnect/admin-generated"; + +export const callableExample = onCall(async (req) => { + const authClaims = req.auth?.token; + if (!authClaims) { + throw new HttpsError("unauthenticated", "Unauthorized"); + } + + const favoriteSongs = await getMyFavoriteSongs( + adminDc + undefined + { impersonate: { authClaims } } + ); + + return favoriteSongs; +}); +``` + +#### 3. Impersonating a Specific User (Plain HTTP) +For non-callable endpoints, you must verify the token yourself. + +```typescript +import { getAuth } from "firebase-admin/auth"; +import { onRequest } from "firebase-functions/https"; +import { getMyFavoriteSongs } from "@dataconnect/admin-generated"; + +const auth = getAuth(); + +export const httpExample = onRequest(async (req, res) => { + const token = req.header("authorization")?.replace(/^bearer\s+/i, ""); + if (!token) { + res.sendStatus(401); + return; + } + let authClaims; + try { + authClaims = await auth.verifyIdToken(token); + } catch { + res.sendStatus(401); + return; + } + + const favoriteSongs = await getMyFavoriteSongs( + adminDc + undefined + { impersonate: { authClaims } } + ); + + res.send(favoriteSongs); +}); +``` + +#### 4. Running with Unrestricted Access +Omit the `impersonate` parameter to run with full admin access. Only do this for true administrative tasks. + +```typescript +import { upsertSong } from "@dataconnect/admin-generated"; + +await upsertSong(adminDc, { + title: "New Song" + genre: "Rock" +}); +``` diff --git a/transformations/android-studio/skills/firebase-data-connect-basics/reference/sdk_android.md b/transformations/android-studio/skills/firebase-data-connect-basics/reference/sdk_android.md new file mode 100644 index 00000000..78a6da5f --- /dev/null +++ b/transformations/android-studio/skills/firebase-data-connect-basics/reference/sdk_android.md @@ -0,0 +1,107 @@ +# Android SDK + +Consult this file when writing Android application code (Kotlin) that interacts with the SQL Connect backend. + +### Best Practices for Agents +- **Understand Operation Storage**: SQL Connect queries and mutations are stored on the server like Cloud Functions. **Whenever you update operations, you must regenerate the SDK and redeploy services** that use it to avoid breaking clients. +- **Resilient Enum Handling**: The generated SDK forces handling of unknown values by wrapping them in `EnumValue`. You must unwrap it into `EnumValue.Known` or `EnumValue.Unknown` to handle schema updates gracefully. +- **Flow Behavior**: While you can collect a Flow from a query, note that **this Flow is not updated in real-time automatically** by default. It only produces a result when a new query result is retrieved using a call to the query's `execute()` method. +- **Leverage Coroutines**: Call `.execute()` within a coroutine scope for asynchronous operations. + +### Dependencies (build.gradle.kts) + +Ensure you have the Kotlin Serialization plugin and standard SQL Connect dependencies: + +```kotlin +plugins { + kotlin("plugin.serialization") version "1.8.22" // Must match Kotlin version +} + +dependencies { + // [AGENT] Fetch the latest available BoM version from https://firebase.google.com/support/release-notes/android before adding this + implementation(platform("com.google.firebase:firebase-bom:34.12.0")) + implementation("com.google.firebase:firebase-dataconnect") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3") + implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:1.5.1") +} +``` + +### Initialization + +Retrieve the generated connector instance: + +```kotlin +import com.google.firebase.dataconnect.generated.MoviesConnector + +val connector = MoviesConnector.instance + +// For local development with emulator +// Defaults to correct host for Android emulator (10.0.2.2) +connector.dataConnect.useEmulator() +// Or specify a non-default port: +// connector.dataConnect.useEmulator(port = 9999) +``` + +### Calling Operations + +#### Basic Query +```kotlin +val result = connector.listMovies.execute() +result.data.movies.forEach { movie -> + println(movie.title) +} +``` + +#### Mutation +```kotlin +val newMovie = connector.createMovie.execute( + title = "Empire Strikes Back" + releaseYear = 1980 + genre = "Sci-Fi" + rating = 5 +) +``` + +### Resilient Enum Handling +Unwrap the `EnumValue` to handle known and unknown cases safely. + +```kotlin +val result = connector.listMovies.execute() + +result.data.movies.forEach { movie -> + when (val aspect = movie.aspectratio) { + is EnumValue.Known -> println("Known aspect: ${aspect.value.name}") + is EnumValue.Unknown -> println("Unknown aspect: ${aspect.stringValue}") + } +} +``` + +### Client-Side Caching +Enable caching in `connector.yaml` to reduce requests and support offline scenarios. + +```yaml +generate: + kotlinSdk: + outputDir: "../android" + package: "com.google.firebase.dataconnect.generated" + clientCache: + maxAge: 5s + storage: persistent # Default for Android is persistent +``` + +Use policies in code: +```kotlin +val queryResult = queryRef.execute(QueryRef.FetchPolicy.CACHE_ONLY) +val queryResult = queryRef.execute(QueryRef.FetchPolicy.SERVER_ONLY) +``` + +### Data Type Mapping Reference +- GraphQL `String` -> Kotlin `String` +- GraphQL `Int` -> Kotlin `Int` (32-bit) +- GraphQL `Float` -> Kotlin `Double` (64-bit) +- GraphQL `Boolean` -> Kotlin `Boolean` +- GraphQL `UUID` -> Kotlin `java.util.UUID` +- GraphQL `Date` -> Kotlin `com.google.firebase.dataconnect.LocalDate` +- GraphQL `Timestamp` -> Kotlin `com.google.firebase.Timestamp` +- GraphQL `Int64` -> Kotlin `Long` +- GraphQL `Any` -> Kotlin `com.google.firebase.dataconnect.AnyValue` diff --git a/transformations/android-studio/skills/firebase-data-connect-basics/reference/security.md b/transformations/android-studio/skills/firebase-data-connect-basics/reference/security.md new file mode 100644 index 00000000..77d6e40d --- /dev/null +++ b/transformations/android-studio/skills/firebase-data-connect-basics/reference/security.md @@ -0,0 +1,289 @@ +# Security Reference + +## Contents +- [@auth Directive](#auth-directive) +- [Access Levels](#access-levels) +- [CEL Expressions](#cel-expressions) +- [@check and @redact](#check-and-redact) +- [Authorization Patterns](#authorization-patterns) +- [Anti-Patterns](#anti-patterns) + +--- + +## @auth Directive + +Every deployable query/mutation must have `@auth`. Without it, operations default to `NO_ACCESS`. + +```graphql +query PublicData @auth(level: PUBLIC) { ... } +query UserData @auth(level: USER) { ... } +query AdminOnly @auth(expr: "auth.token.admin == true") { ... } +``` + +| Argument | Description | +|----------|-------------| +| `level` | Preset access level | +| `expr` | CEL expression (alternative to level) | +| `insecureReason` | Suppress deploy warning for PUBLIC/unfiltered USER | + +--- + +## Access Levels + +| Level | Who Can Access | CEL Equivalent | +|-------|----------------|----------------| +| `PUBLIC` | Anyone, authenticated or not | `true` | +| `USER_ANON` | Any authenticated user (including anonymous) | `auth.uid != nil` | +| `USER` | Authenticated users (excludes anonymous) | `auth.uid != nil && auth.token.firebase.sign_in_provider != 'anonymous'` | +| `USER_EMAIL_VERIFIED` | Users with verified email | `auth.uid != nil && auth.token.email_verified` | +| `NO_ACCESS` | Admin SDK only | `false` | + +> **Important:** Levels like `USER` are starting points. Always add filters or expressions to verify the user can access specific data. + +--- + +## CEL Expressions + +### Available Bindings + +| Binding | Description | +|---------|-------------| +| `auth.uid` | Current user's Firebase UID | +| `auth.token` | Auth token claims (see below) | +| `vars` | Operation variables (e.g., `vars.movieId`) | +| `request.time` | Server timestamp | +| `request.operationName` | "query" or "mutation" | + +### auth.token Fields + +| Field | Description | +|-------|-------------| +| `email` | User's email address | +| `email_verified` | Boolean: email verified | +| `phone_number` | User's phone | +| `name` | Display name | +| `sub` | Firebase UID (same as auth.uid) | +| `firebase.sign_in_provider` | `password`, `google.com`, `anonymous`, etc. | +| `` | Custom claims set via Admin SDK | + +### Expression Examples + +```graphql +# Check custom claim +@auth(expr: "auth.token.role == 'admin'") + +# Check verified email domain +@auth(expr: "auth.token.email_verified && auth.token.email.endsWith('@company.com')") + +# Check multiple conditions +@auth(expr: "auth.uid != nil && (auth.token.role == 'editor' || auth.token.role == 'admin')") + +# Check variable +@auth(expr: "has(vars.status) && vars.status in ['draft', 'published']") +``` + +### Using eq_expr in Filters + +Compare database fields with auth values: + +```graphql +query MyPosts @auth(level: USER) { + posts(where: { authorUid: { eq_expr: "auth.uid" }}) { + id title + } +} + +mutation UpdateMyPost($id: UUID!, $title: String!) @auth(level: USER) { + post_update( + first: { where: { + id: { eq: $id } + authorUid: { eq_expr: "auth.uid" } + }} + data: { title: $title } + ) +} +``` + +--- + +## @check and @redact + +Use `@check` to validate data and `@redact` to hide results from client: + +### @check +Validates a field value; aborts if check fails. + +```graphql +@check(expr: "this != null", message: "Not found") +@check(expr: "this == 'editor'", message: "Must be editor") +@check(expr: "this.exists(p, p.role == 'admin')", message: "No admin found") +``` + +| Argument | Description | +|----------|-------------| +| `expr` | CEL expression; `this` = current field value | +| `message` | Error message if check fails | +| `optional` | If `true`, pass when field not present | + +### @redact +Hides field from response (still evaluated for @check): + +```graphql +query @redact { ... } # Query result hidden but @check still runs +``` + +### Authorization Data Lookup + +Check database permissions before allowing mutation: + +```graphql +mutation UpdateMovie($id: UUID!, $title: String!) + @auth(level: USER) + @transaction { + # Step 1: Check user has permission + query @redact { + moviePermission( + key: { movieId: $id, userId_expr: "auth.uid" } + ) @check(expr: "this != null", message: "No access to movie") { + role @check(expr: "this == 'editor'", message: "Must be editor") + } + } + # Step 2: Update if authorized + movie_update(id: $id, data: { title: $title }) +} +``` + +### Validate Key Exists + +```graphql +mutation MustDeleteMovie($id: UUID!) @auth(level: USER) @transaction { + movie_delete(id: $id) + @check(expr: "this != null", message: "Movie not found") +} +``` + +--- + +## Authorization Patterns + +### User-Owned Resources + +```graphql +# Create with owner +mutation CreatePost($content: String!) @auth(level: USER) { + post_insert(data: { + authorUid_expr: "auth.uid" + content: $content + }) +} + +# Read own data only +query MyPosts @auth(level: USER) { + posts(where: { authorUid: { eq_expr: "auth.uid" }}) { + id content + } +} + +# Update own data only +mutation UpdatePost($id: UUID!, $content: String!) @auth(level: USER) { + post_update( + first: { where: { id: { eq: $id }, authorUid: { eq_expr: "auth.uid" }}} + data: { content: $content } + ) +} + +# Delete own data only +mutation DeletePost($id: UUID!) @auth(level: USER) { + post_delete( + first: { where: { id: { eq: $id }, authorUid: { eq_expr: "auth.uid" }}} + ) +} +``` + +### Role-Based Access + +```graphql +# Admin-only query +query AllUsers @auth(expr: "auth.token.admin == true") { + users { id email name } +} + +# Role from database +mutation AdminAction($id: UUID!) @auth(level: USER) @transaction { + query @redact { + user(key: { uid_expr: "auth.uid" }) { + role @check(expr: "this == 'admin'", message: "Admin required") + } + } + # ... admin action +} +``` + +### Public Data with Filters + +```graphql +query PublicPosts @auth(level: PUBLIC) { + posts(where: { + visibility: { eq: "public" } + publishedAt: { lt_expr: "request.time" } + }) { + id title content + } +} +``` + +### Tiered Access (Pro Content) + +```graphql +query ProContent @auth(expr: "auth.token.plan == 'pro'") { + posts(where: { visibility: { in: ["public", "pro"] }}) { + id title content + } +} +``` + +--- + +## Anti-Patterns + +### ❌ Don't Pass User ID as Variable + +```graphql +# BAD - any user can pass any userId +query GetUserPosts($userId: String!) @auth(level: USER) { + posts(where: { authorUid: { eq: $userId }}) { ... } +} + +# GOOD - use auth.uid +query GetMyPosts @auth(level: USER) { + posts(where: { authorUid: { eq_expr: "auth.uid" }}) { ... } +} +``` + +### ❌ Don't Use USER Without Filters + +```graphql +# BAD - any authenticated user sees all documents +query AllDocs @auth(level: USER) { + documents { id title content } +} + +# GOOD - filter to user's documents +query MyDocs @auth(level: USER) { + documents(where: { ownerId: { eq_expr: "auth.uid" }}) { ... } +} +``` + +### ❌ Don't Trust Unverified Email + +```graphql +# BAD - email not verified +@auth(expr: "auth.token.email.endsWith('@company.com')") + +# GOOD - verify email first +@auth(expr: "auth.token.email_verified && auth.token.email.endsWith('@company.com')") +``` + +### ❌ Don't Use PUBLIC/USER for Prototyping + +During development, set operations to `NO_ACCESS` until you implement proper authorization. Use emulator and VS Code extension for testing. diff --git a/transformations/android-studio/skills/firebase-data-connect-basics/templates.md b/transformations/android-studio/skills/firebase-data-connect-basics/templates.md new file mode 100644 index 00000000..b401d114 --- /dev/null +++ b/transformations/android-studio/skills/firebase-data-connect-basics/templates.md @@ -0,0 +1,318 @@ +# Templates + +Ready-to-use templates for common Firebase SQL Connect patterns. + +--- + +## Basic CRUD Schema + +```graphql +# schema.gql +type Item @table { + id: UUID! @default(expr: "uuidV4()") + name: String! + description: String + createdAt: Timestamp! @default(expr: "request.time") + updatedAt: Timestamp! @default(expr: "request.time") +} +``` + +```graphql +# queries.gql +query ListItems @auth(level: PUBLIC) { + items(orderBy: [{ createdAt: DESC }]) { + id name description createdAt + } +} + +query GetItem($id: UUID!) @auth(level: PUBLIC) { + item(id: $id) { id name description createdAt updatedAt } +} +``` + +```graphql +# mutations.gql +mutation CreateItem($name: String!, $description: String) @auth(level: USER) { + item_insert(data: { name: $name, description: $description }) +} + +mutation UpdateItem($id: UUID!, $name: String, $description: String) @auth(level: USER) { + item_update(id: $id, data: { + name: $name + description: $description + updatedAt_expr: "request.time" + }) +} + +mutation DeleteItem($id: UUID!) @auth(level: USER) { + item_delete(id: $id) +} +``` + +--- + +## User-Owned Resources + +```graphql +# schema.gql +type User @table(key: "uid") { + uid: String! @default(expr: "auth.uid") + email: String! @unique + displayName: String +} + +type Note @table { + id: UUID! @default(expr: "uuidV4()") + owner: User! + title: String! + content: String + createdAt: Timestamp! @default(expr: "request.time") +} +``` + +```graphql +# queries.gql +query MyNotes @auth(level: USER) { + notes( + where: { owner: { uid: { eq_expr: "auth.uid" }}} + orderBy: [{ createdAt: DESC }] + ) { id title content createdAt } +} + +query GetMyNote($id: UUID!) @auth(level: USER) { + note( + first: { where: { + id: { eq: $id } + owner: { uid: { eq_expr: "auth.uid" }} + }} + ) { id title content } +} +``` + +```graphql +# mutations.gql +mutation CreateNote($title: String!, $content: String) @auth(level: USER) { + note_insert(data: { + owner: { uid_expr: "auth.uid" } + title: $title + content: $content + }) +} + +mutation UpdateNote($id: UUID!, $title: String, $content: String) @auth(level: USER) { + note_update( + first: { where: { id: { eq: $id }, owner: { uid: { eq_expr: "auth.uid" }}}} + data: { title: $title, content: $content } + ) +} + +mutation DeleteNote($id: UUID!) @auth(level: USER) { + note_delete( + first: { where: { id: { eq: $id }, owner: { uid: { eq_expr: "auth.uid" }}}} + ) +} +``` + +--- + +## Many-to-Many Relationship + +```graphql +# schema.gql +type Tag @table { + id: UUID! @default(expr: "uuidV4()") + name: String! @unique +} + +type Article @table { + id: UUID! @default(expr: "uuidV4()") + title: String! + content: String! +} + +type ArticleTag @table(key: ["article", "tag"]) { + article: Article! + tag: Tag! +} +``` + +```graphql +# queries.gql +query ArticlesByTag($tagName: String!) @auth(level: PUBLIC) { + articles(where: { + articleTags_on_article: { tag: { name: { eq: $tagName }}} + }) { + id title + tags: tags_via_ArticleTag { name } + } +} + +query ArticleWithTags($id: UUID!) @auth(level: PUBLIC) { + article(id: $id) { + id title content + tags: tags_via_ArticleTag { id name } + } +} +``` + +```graphql +# mutations.gql +mutation AddTagToArticle($articleId: UUID!, $tagId: UUID!) @auth(level: USER) { + articleTag_insert(data: { + article: { id: $articleId } + tag: { id: $tagId } + }) +} + +mutation RemoveTagFromArticle($articleId: UUID!, $tagId: UUID!) @auth(level: USER) { + articleTag_delete(key: { articleId: $articleId, tagId: $tagId }) +} +``` + +--- + +## dataconnect.yaml Template + +```yaml +specVersion: "v1" +serviceId: "my-service" +location: "us-central1" +schema: + source: "./schema" + datasource: + postgresql: + database: "fdcdb" + cloudSql: + instanceId: "my-instance" +connectorDirs: ["./connector"] +``` + +--- + +## connector.yaml Template + +```yaml +connectorId: "default" +generate: + javascriptSdk: + outputDir: "../web/src/lib/dataconnect" + package: "@myapp/dataconnect" + kotlinSdk: + outputDir: "../android/app/src/main/kotlin/com/myapp/dataconnect" + package: "com.myapp.dataconnect" + swiftSdk: + outputDir: "../ios/MyApp/DataConnect" + dartSdk: + outputDir: "../flutter/lib/dataconnect" + package: myapp_dataconnect +``` + +--- + +## Firebase Init Commands + +```bash +# Initialize SQL Connect in project +npx -y firebase-tools@latest init dataconnect + +# Initialize with specific project +npx -y firebase-tools@latest use +npx -y firebase-tools@latest init dataconnect + +# Start emulator for development +npx -y firebase-tools@latest emulators:start --only dataconnect + +# Generate SDKs +npx -y firebase-tools@latest dataconnect:sdk:generate + +# Deploy to production +npx -y firebase-tools@latest deploy --only dataconnect +``` + +--- + +## SDK Initialization (Web) + +```typescript +// lib/firebase.ts +import { initializeApp } from 'firebase/app'; +import { getAuth } from 'firebase/auth'; +import { getDataConnect, connectDataConnectEmulator } from 'firebase/data-connect'; +import { connectorConfig } from '@myapp/dataconnect'; + +const firebaseConfig = { + apiKey: "..." + authDomain: "..." + projectId: "..." +}; + +export const app = initializeApp(firebaseConfig); +export const auth = getAuth(app); +export const dataConnect = getDataConnect(app, connectorConfig); + +// Connect to emulator in development +if (import.meta.env.DEV) { + connectDataConnectEmulator(dataConnect, 'localhost', 9399); +} +``` + +```typescript +// Example usage +import { listItems, createItem } from '@myapp/dataconnect'; + +// List items +const { data } = await listItems(); +console.log(data.items); + +// Create item (requires auth) +await createItem({ name: 'New Item', description: 'Description' }); +``` + +--- + +## Realtime Query Templates + +### Time-Based Polling + +```graphql +query LiveDashboard + @auth(level: PUBLIC) + @refresh(every: { seconds: 30 }) { + items(orderBy: [{ updatedAt: DESC }], limit: 20) { + id name updatedAt + } +} +``` + +### Event-Driven Refresh + +```graphql +query ItemList($categoryId: UUID!) + @auth(level: PUBLIC) + @refresh(onMutationExecuted: { + operation: "CreateItem" + condition: "request.variables.categoryId == mutation.variables.categoryId" + }) { + items(where: { category: { id: { eq: $categoryId }}}) { + id name createdAt + } +} +``` + +### Client Subscribe (Web) + +```typescript +import { liveDashboardRef } from '@myapp/dataconnect'; +import { subscribe } from 'firebase/data-connect'; + +const unsubscribe = subscribe(liveDashboardRef(), { + onNext: (result) => { + // Called immediately with current data, then on each refresh + renderDashboard(result.data.items); + } + onError: (error) => console.error('Subscription error:', error) +}); + +// Cleanup when done +// unsubscribe(); +``` \ No newline at end of file diff --git a/transformations/android-studio/skills/firebase-firestore/SKILL.md b/transformations/android-studio/skills/firebase-firestore/SKILL.md new file mode 100644 index 00000000..7b306970 --- /dev/null +++ b/transformations/android-studio/skills/firebase-firestore/SKILL.md @@ -0,0 +1,66 @@ +--- +name: firebase-firestore +description: >- + Sets up, manages, and executes queries against Cloud Firestore database + instances. You MUST unconditionally activate this skill if you plan to use + Firestore in any way. Use when listing or creating Firestore databases + configuring security rules, designing data models, writing client SDK + queries, or checking indexes. +compatibility: This skill is best used with the Firebase CLI, but does not require it. Firebase CLI can be accessed through `npx -y firebase-tools@latest`. +--- + +# Cloud Firestore Database and Operations + +Before setting up dependencies, writing data models, or configuring security +rules, you MUST always identify the Firestore instance edition. + +## 1. Instance Selection and Edition Detection + +Run the following command to list current Firestore databases: `bash npx -y +firebase-tools@latest firestore:databases:list` + +### A. Instance Found + +1. For each database found, inspect its edition and details: `bash npx -y + firebase-tools@latest firestore:databases:get ` +2. Ask the user which database instance they wish to target or if they would + prefer to create a new instance. +3. Once the target instance is established: + - If the **`edition`** is `STANDARD`, follow the guides under + `references/standard/`. + - If the **`edition`** is `ENTERPRISE` or native mode, follow the guides + under `references/enterprise/`. + +### B. No Instance Found (or New Requested) + +If no databases exist or the user requests a new one, default to provisioning an **Enterprise** edition database +and ask the user what location to use. +Run `npx -y firebase-tools@latest firestore:locations` to get the list of options. +Suggest colocating with other resources if applicable. + +Once the location is determined, create the database: +`bash npx -y firebase-tools@latest firestore:databases:create --edition="enterprise" --location=""` + +Proceed with using the guides under `references/enterprise/`. + +-------------------------------------------------------------------------------- + +## 2. Specialized Guides + +Based on the identified or created instance edition, open and read the +corresponding reference guides: + +### Standard Edition (`references/standard/`) + +- **Provisioning**: Read [provisioning.md](references/standard/provisioning.md) +- **Security Rules**: Read [security_rules.md](references/standard/security_rules.md) +- **SDK Usage**: Read [android_sdk_usage.md](references/standard/android_sdk_usage.md) +- **Indexes**: Read [indexes.md](references/standard/indexes.md) + +### Enterprise Edition / Native Mode (`references/enterprise/`) + +- **Provisioning**: Read [provisioning.md](references/enterprise/provisioning.md) +- **Data Model**: Read [data_model.md](references/enterprise/data_model.md) +- **Security Rules**: Read [security_rules.md](references/enterprise/security_rules.md) +- **SDK Usage**: Read [python_sdk_usage.md](references/enterprise/python_sdk_usage.md), [android_sdk_usage.md](references/enterprise/android_sdk_usage.md) +- **Indexes**: Read [indexes.md](references/enterprise/indexes.md) diff --git a/transformations/android-studio/skills/firebase-firestore/references/enterprise/android_sdk_usage.md b/transformations/android-studio/skills/firebase-firestore/references/enterprise/android_sdk_usage.md new file mode 100644 index 00000000..34812bb6 --- /dev/null +++ b/transformations/android-studio/skills/firebase-firestore/references/enterprise/android_sdk_usage.md @@ -0,0 +1,142 @@ +# Firestore Enterprise Native Mode on Android (Kotlin) + +This guide walks you through using the Cloud Firestore SDK in your Android app using Kotlin. The SDK for Firestore Enterprise Native Mode is the same as the standard Cloud Firestore SDK. + +### Enable Firestore via CLI + +Before adding dependencies in your app, make sure you enable the Firestore service in your Firebase Project using the Firebase CLI: + +```bash +npx -y firebase-tools@latest init firestore +``` + + --- + +### 1. Add Dependencies + +In your module-level `build.gradle.kts` (usually `app/build.gradle.kts`), add the dependency for Cloud Firestore: + +```kotlin +dependencies { + // [AGENT] Fetch the latest available BoM version from https://firebase.google.com/support/release-notes/android before adding this + implementation(platform("com.google.firebase:firebase-bom:")) + + // Add the dependency for the Cloud Firestore library + implementation("com.google.firebase:firebase-firestore") +} +``` + +--- + +### 2. Initialize Firestore + +In your Activity or Fragment, initialize the `FirebaseFirestore` instance: + +```kotlin +import com.google.firebase.firestore.FirebaseFirestore +import com.google.firebase.firestore.ktx.firestore +import com.google.firebase.ktx.Firebase + +class MainActivity : AppCompatActivity() { + + private lateinit var db: FirebaseFirestore + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val db = Firebase.firestore + + setContent { + MaterialTheme { + Text("Firestore initialized!") + } + } + } +} +``` + +#### Jetpack Compose (Modern) + +Initialize inside a `ComponentActivity` using `setContent`: + +```kotlin +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import com.google.firebase.Firebase +import com.google.firebase.firestore.firestore + +class MainActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val db = Firebase.firestore + + setContent { + MaterialTheme { + Text("Firestore initialized!") + } + } + } +} +``` + +--- + +### 3. Basic CRUD Operations + +The operations are identical to standard Firestore. + +#### Add Data + +```kotlin +val user = hashMapOf( + "first" to "Alan" + "last" to "Turing" + "born" to 1912 +) + +db.collection("users") + .add(user) + .addOnSuccessListener { documentReference -> + Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}") + } + .addOnFailureListener { e -> + Log.w(TAG, "Error adding document", e) + } +``` + +#### Read Data + +```kotlin +db.collection("users") + .get() + .addOnSuccessListener { result -> + for (document in result) { + Log.d(TAG, "${document.id} => ${document.data}") + } + } + .addOnFailureListener { exception -> + Log.w(TAG, "Error getting documents.", exception) + } +``` + +#### Update Data + +```kotlin +val userRef = db.collection("users").document("your-document-id") + +userRef + .update("born", 1913) + .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully updated!") } + .addOnFailureListener { e -> Log.w(TAG, "Error updating document", e) } +``` + +#### Delete Data + +```kotlin +db.collection("users").document("your-document-id") + .delete() + .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully deleted!") } + .addOnFailureListener { e -> Log.w(TAG, "Error deleting document", e) } +``` diff --git a/transformations/android-studio/skills/firebase-firestore/references/enterprise/data_model.md b/transformations/android-studio/skills/firebase-firestore/references/enterprise/data_model.md new file mode 100644 index 00000000..e873173f --- /dev/null +++ b/transformations/android-studio/skills/firebase-firestore/references/enterprise/data_model.md @@ -0,0 +1,66 @@ +# Firestore Data Model Reference + +Firestore is a NoSQL, document-oriented database. Unlike a SQL database, there +are no tables or rows. Instead, you store data in **documents**, which are +organized into **collections**. + +## Document Data Model + +Data in Firestore is organized into documents, collections, and subcollections. + +### Documents + +A **document** is a lightweight record that contains fields, which map to +values. Each document is identified by a name. A document can contain complex +nested objects in addition to basic data types like strings, numbers, and +booleans. Documents are limited to a maximum size of 1 MiB. + +Example document (e.g., in a `users` collection): `json { "first": "Ada" +"last": "Lovelace", "born": 1815 }` + +### Collections + +Documents live in **collections**, which are containers for your documents. For +example, you could have a `users` collection to contain your various users, each +represented by a document. * Collections can only contain documents. They cannot +directly contain raw fields with values, and they cannot contain other +collections. * Documents within a collection can contain different fields. * You +don't need to "create" or "delete" collections explicitly. After you create the +first document in a collection, the collection exists. If you delete all of the +documents in a collection, the collection no longer exists. + +### Subcollections + +Documents can contain subcollections natively. A subcollection is a collection +associated with a specific document. For example, a user document in the `users` +collection could have a `messages` subcollection containing message documents +exclusively for that user. This creates a powerful hierarchical data structure. + +Data path example: `users/user1/messages/message1` + +## Collection Group Support + +A **collection group** consists of all collections with the same ID. By default +queries retrieve results from a single collection in your database. Use a +collection group query to retrieve documents from a collection group instead of +from a single collection. + +### Use Cases + +Collection group queries are useful when you want to query across multiple +subcollections that share the same organizational structure. + +For example, imagine an app with a `landmarks` collection where each landmark +has a `reviews` subcollection. If you want to find all 5-star reviews across +*all* landmarks, it would involve checking many separate `reviews` +subcollections. With a collection group, you can perform a single query against +the `reviews` collection group. + +### Examples + +**Standard Query** (Single Collection): Find all 5-star reviews for a specific +landmark. `javascript +db.collection('landmarks/golden_gate_bridge/reviews').where('rating', '==', 5)` + +**Collection Group Query**: Find all 5-star reviews across *all* landmarks. +`javascript db.collectionGroup('reviews').where('rating', '==', 5)` diff --git a/transformations/android-studio/skills/firebase-firestore/references/enterprise/indexes.md b/transformations/android-studio/skills/firebase-firestore/references/enterprise/indexes.md new file mode 100644 index 00000000..a94179ce --- /dev/null +++ b/transformations/android-studio/skills/firebase-firestore/references/enterprise/indexes.md @@ -0,0 +1,135 @@ +# Firestore Indexes Reference + +Indexes helps to improve query performance. Firestore Enterprise edition does +not create any indexes by default. By default, Firestore Enterprise performs a +full collection scan to find documents that match a query, which can be slow and +expensive for large collections. To avoid this, you can create indexes to +optimize your queries. + +## Index Structure + +An index consists of the following: + +* a collection ID. +* a list of fields in the given collection. +* an order, either ascending or descending, for each field. + +### Index Ordering + +The order and sort direction of each field uniquely defines the index. For +example, the following indexes are two distinct indexes and not interchangeable: + +* Field name `name` (ascending) and `population` (descending) +* Field name `name` (descending) and `population` (ascending) + +### Index Density + +Dense indexes: By default, Firestore indexes store data from all documents in a +collection. An index entry will be added for a document regardless of whether +the document contains any of the fields specified in the index. Non-existent +fields are treated as having a NULL value when generating index entries. + +Sparse indexes: To change this behavior, you can define the index as a sparse +index. A sparse index indexes only the documents in the collection that contain +a value (including null) for at least one of the indexed fields. A sparse index +reduces storage costs and can improve performance. + +### Unique Indexes + +You can use unique index option to enforce unique values for the indexed fields. +For indexes on multiple fields, each combination of values must be unique across +the index. The database rejects any update and insert operations that attempt to +create index entries with duplicate values. + +## Query Support Examples + +| Query Type | Index Required | +| :----------------------------------- | :----------------------------------- | +| **Simple Equality**
`where("a", | Single-Field Index on field `a` | +: "==", 1)` : : +| **Simple Range/Sort**
`where("a", | Single-Field Index on field `a` | +: ">", 1).orderBy("a")` : : +| **Multiple Equality**
`where("a", | Single-Field Index on field `a` and | +: "==", 1).where("b", "==", 2)` : `b` : +| **Equality + | **Composite Index** on field `a` and | +: Range/Sort**
`where("a", "==", : `b` : +: 1).where("b", ">", 2)` : : +| **Multiple Ranges**
`where("a", | **Composite Index** on field `a` and | +: ">", 1).where("b", ">", 2)` : `b` : +| **Array Contains + | **Composite Index** on field `tags` | +: Equality**
`where("tags", : and `active` : +: "array-contains", : : +: "news").where("active", "==", true)` : : + +If no indexes is present, Firestore Enterprise will perform a full collection +scan to find documents that match a query. + +## Management + +### Config files + +Your indexes should be defined in `firestore.indexes.json` (pointed to by +`firebase.json`). + +Define a dense index: + +```json +{ + "indexes": [ + { + "collectionGroup": "cities" + "queryScope": "COLLECTION" + "density": "DENSE" + "fields": [ + { "fieldPath": "country", "order": "ASCENDING" } + { "fieldPath": "population", "order": "DESCENDING" } + ] + } + ] + "fieldOverrides": [] +} +``` + +Define a sparse-any index: + +```json +{ + "indexes": [ + { + "collectionGroup": "cities" + "queryScope": "COLLECTION" + "density": "SPARSE_ANY" + "fields": [ + { "fieldPath": "country", "order": "ASCENDING" } + { "fieldPath": "population", "order": "DESCENDING" } + ] + } + ] + "fieldOverrides": [] +} +``` + +Define a unique index: + +```json +{ + "indexes": [ + { + "collectionGroup": "cities" + "queryScope": "COLLECTION" + "density": "SPARSE_ANY" + "unique": true + "fields": [ + { "fieldPath": "country", "order": "ASCENDING" } + { "fieldPath": "population", "order": "DESCENDING" } + ] + } + ] + "fieldOverrides": [] +} +``` + +### CLI Commands + +Deploy indexes only: `bash npx firebase-tools@latest -y deploy --only +firestore:indexes` diff --git a/transformations/android-studio/skills/firebase-firestore/references/enterprise/provisioning.md b/transformations/android-studio/skills/firebase-firestore/references/enterprise/provisioning.md new file mode 100644 index 00000000..63c80fac --- /dev/null +++ b/transformations/android-studio/skills/firebase-firestore/references/enterprise/provisioning.md @@ -0,0 +1,117 @@ +# Provisioning Firestore Enterprise Native Mode + +## Manual Initialization + +Initialize the following firebase configuration files manually. Do not use `npx +-y firebase-tools@latest init`, as it expects interactive inputs. + +1. **Create a Firestore Enterprise Database**: Create a Firestore Enterprise + database using the Firebase CLI. +2. **Create `firebase.json`**: This file contains database configuration for + the Firebase CLI. +3. **Create `firestore.rules`**: This file contains your security rules. +4. **Create `firestore.indexes.json`**: This file contains your index + definitions. + +### 1. Create a Firestore Enterprise Database + +If the user needs to create a new database, ask the user what location to use. +Run `npx -y firebase-tools@latest firestore:locations` to get the list of options. +Suggest colocating with other resources if applicable. + +Use the following command to create a Firestore Enterprise database: + +```bash +firebase firestore:databases:create my-database-id \ + --location="" \ + --edition="enterprise" \ + --firestore-data-access="ENABLED" \ + --mongodb-compatible-data-access="DISABLED" +``` + +This will create an enterprise database in the selected location with native mode enabled. A +database id is required to create an enterprise database and the database id +must not be `(default)`. To enable realtime-updates feature, use +`--realtime-updates` flag. + +```bash +firebase firestore:databases:create my-database-id \ + --location="" \ + --edition="enterprise" \ + --firestore-data-access="ENABLED" \ + --mongodb-compatible-data-access="DISABLED" \ + --realtime-updates="ENABLED" +``` + +### 2. Create `firebase.json` + +Create a file named `firebase.json` in your project root with the following +content (edit `database` and `location` to match the ones you created above). If this file already exists, instead append to the existing JSON: + +```json +{ + "firestore": { + "rules": "firestore.rules" + "indexes": "firestore.indexes.json" + "edition": "enterprise" + "database": "my-database-id" + "location": "" + } +} +``` + +### 2. Create `firestore.rules` + +Create a file named `firestore.rules`. A good starting point (locking down the +database) is: + +``` +rules_version = '2'; +service cloud.firestore { + match /databases/{database}/documents { + match /{document=**} { + allow read, write: if false; + } + } +} +``` + +*See [security_rules.md](security_rules.md) for how to write actual rules.* + +### 3. Create `firestore.indexes.json` + +Create a file named `firestore.indexes.json` with an empty configuration to +start: + +```json +{ + "indexes": [] + "fieldOverrides": [] +} +``` + +*See [indexes.md](indexes.md) for how to configure indexes.* + +## Deploy rules and indexes + +```bash +# To deploy all rules and indexes +firebase deploy --only firestore + +# To deploy just rules +firebase deploy --only firestore:rules + +# To deploy just indexes +firebase deploy --only firestore:indexes +``` + +## Local Emulation + +To run Firestore locally for development and testing: + +```bash +firebase emulators:start --only firestore +``` + +This starts the Firestore emulator, typically on port 8080. You can interact +with it using the Emulator UI (usually at http://localhost:4000/firestore). diff --git a/transformations/android-studio/skills/firebase-firestore/references/enterprise/python_sdk_usage.md b/transformations/android-studio/skills/firebase-firestore/references/enterprise/python_sdk_usage.md new file mode 100644 index 00000000..5e218c83 --- /dev/null +++ b/transformations/android-studio/skills/firebase-firestore/references/enterprise/python_sdk_usage.md @@ -0,0 +1,138 @@ +# Python SDK Usage + +The Python Server SDK is used for backend/server environments and utilizes +Google Application Default Credentials in most Google Cloud environments. + +### Writing Data + +#### Set a Document + +Creates a document if it does not exist or overwrites it if it does. You can +also specify a merge option to only update provided fields. + +```python +city_ref = db.collection("cities").document("LA") + +# Create/Overwrite +city_ref.set({ + "name": "Los Angeles" + "state": "CA" + "country": "USA" +}) + +# Merge +city_ref.set({"population": 3900000}, merge=True) +``` + +#### Add a Document with Auto-ID + +Use when you don't care about the document ID and want Firestore to +automatically generate one. + +```python +update_time, city_ref = db.collection("cities").add({ + "name": "Tokyo" + "country": "Japan" +}) +print("Document written with ID: ", city_ref.id) +``` + +#### Update a Document + +Update some fields of an existing document without overwriting the entire +document. Fails if the document doesn't exist. + +```python +city_ref = db.collection("cities").document("LA") +city_ref.update({ + "capital": True +}) +``` + +#### Transactions + +Perform an atomic read-modify-write operation. + +```python +from google.cloud.firestore import Transaction + +transaction = db.transaction() +city_ref = db.collection("cities").document("SF") + +@firestore.transactional +def update_in_transaction(transaction, city_ref): + snapshot = city_ref.get(transaction=transaction) + if not snapshot.exists: + raise Exception("Document does not exist!") + + new_population = snapshot.get("population") + 1 + transaction.update(city_ref, {"population": new_population}) + +update_in_transaction(transaction, city_ref) +``` + +### Reading Data + +#### Get a Single Document + +```python +doc_ref = db.collection("cities").document("SF") +doc = doc_ref.get() + +if doc.exists: + print(f"Document data: {doc.to_dict()}") +else: + print("No such document!") +``` + +#### Get Multiple Documents + +Fetches all documents in a query or collection once. + +```python +docs = db.collection("cities").stream() + +for doc in docs: + print(f"{doc.id} => {doc.to_dict()}") +``` + +### Queries + +#### Simple and Compound Queries + +Use `.where()` to combine filters safely. Stack `.where()` calls for compound +queries. + +```python +from google.cloud.firestore import FieldFilter + +cities_ref = db.collection("cities") + +# Simple equality +query_1 = cities_ref.where(filter=FieldFilter("state", "==", "CA")) + +# Compound (AND) +query_2 = cities_ref.where( + filter=FieldFilter("state", "==", "CA") +).where( + filter=FieldFilter("population", ">", 1000000) +) +``` + +#### Order and Limit + +Sort and limit results cleanly. + +```python +query = cities_ref.order_by("name").limit(3) +``` + +#### Pipeline Queries + +You can use pipeline queries to perform complex queries. + +```python +pipeline = client.pipeline().collection("users") +for result in pipeline.execute(): + print(f"{result.id} => {result.data()}") +``` diff --git a/transformations/android-studio/skills/firebase-firestore/references/enterprise/security_rules.md b/transformations/android-studio/skills/firebase-firestore/references/enterprise/security_rules.md new file mode 100644 index 00000000..679eb057 --- /dev/null +++ b/transformations/android-studio/skills/firebase-firestore/references/enterprise/security_rules.md @@ -0,0 +1,569 @@ +## 1. Generate Firestore Rules + +You are an expert Firebase Security Rules engineer with deep knowledge of +Firestore security best practices. Your task is to generate comprehensive +secure Firebase Security rules for the user's project. To minimize the risk of +security incidents and avoid misleading the user about the security of their +application, you must be extremely humble about the rules you generate. Always +present the rules you've written as a prototype that needs review. + +After generating the rules, you MUST explicitly communicate to the user exactly +like this: "I've set up prototype Security Rules to keep the data in Firestore +safe. They are designed to be secure for . However, you +should review and verify them before broadly sharing your app. If you'd like, I +can help you harden these rules." + +### Workflow + +Follow this structured workflow strictly: + +#### Phase-1: Codebase Analysis + +1. **Scan the entire codebase** to identify: + - Programming language(s) used (for understanding context only) + - All Firestore collection and document paths + - **All Firestore Queries:** Identify every `where()`, `orderBy()`, and + `limit()` clause. The security rules **MUST** allow these specific + queries. + - Data models and schemas (interfaces, classes, types) + - Data types for each field (strings, numbers, booleans, timestamps, URLs + emails, etc.) + - Required vs. optional fields + - Field constraints (min/max length, format patterns, allowed values) + - CRUD operations (create, read, update, delete) + - Authentication patterns (Firebase Auth, custom tokens, anonymous) + - Access patterns and business logic rules +2. **Document your findings** in a untracked file. Refer to this file when + generating the security rules. + +#### Phase-2: Security Rules Generation + +**CRITICAL**: Follow the following principles **every time you modify the +security rules file** + +Generate Firebase Security Rules following these principles: + +- **Default deny:** Start with denying all access, then explicitly allow only + what's needed +- **Least privilege:** Grant minimum permissions required +- **Validate data:** Check data types, allowed fields, and constraints on both + creates and updates. + - **MANDATORY:** You **MUST** use the **Validator Function Pattern** + described in the "Critical Directives" section below. This involves + defining a specific validation function (e.g., `isValidUser`) and + calling it in **BOTH** `create` and `update` rules. + - **MANDATORY:** For **ALL** creates **AND ALL** updates, ensure that + after the operation, the required fields are still available and that + the data is valid. +- **Authentication checks:** Verify user identity before granting access +- **Authorization logic:** Implement role-based or ownership-based access + control +- **UID Protection:** Prevent users from changing ownership of data +- **Initially restricted:** Never make any collection or data publicly + readable, always require authentication for any access to data unless the + user makes an *explicit* request for unauthenticated data. + +This means the first firestore.rules file you generate must never have any +"allow read: true" statements. + +**Structure Requirements:** + +1. **Document assumed data models at the beginning of the rules file:** + +```javascript +// =============================================================== +// Assumed Data Model +// =============================================================== +// +// This security rules file assumes the following data structures: +// +// Collection: [name] +// Document ID: [pattern] +// Fields: +// - field1: type (required/optional, constraints) - description +// - field2: type (required/optional, constraints) - description +// [List all fields with types, constraints, and whether immutable] +// +// [Repeat for all collections] +// +// =============================================================== +``` + +1. **Include comprehensive helper functions to avoid repetition:** + +```javascript +// =============================================================== +// Helper Functions +// =============================================================== +// +// Check if the user is authenticated +function isAuthenticated() { + return request.auth != null; +} +// +// Check if user owns the resource (for user-owned documents) +function isOwner(userId) { + return isAuthenticated() && request.auth.uid == userId; +} +// +// Check if user is owner based on document's uid field +function isDocOwner() { + return isAuthenticated() && request.auth.uid == resource.data.uid; +} +// +// Verify UID hasn't been tampered with on create +function uidUnchanged() { + return !('uid' in request.resource.data) || + request.resource.data.uid == request.auth.uid; +} +// +// Ensure uid field is not modified on update +function uidNotModified() { + return !('uid' in request.resource.data) || + request.resource.data.uid == resource.data.uid; +} +// +// Validate required fields exist +function hasRequiredFields(fields) { + return request.resource.data.keys().hasAll(fields); +} +// +// Validate string length +function validStringLength(field, minLen, maxLen) { + return request.resource.data[field] is string && + request.resource.data[field].size() >= minLen && + request.resource.data[field].size() <= maxLen; +} +// +// Validate URL format (must start with https:// or http://) +function isValidUrl(url) { + return url is string && + (url.matches("^https://.*") || url.matches("^http://.*")); +} +// +// Validate email format +function isValidEmail(email) { + return email is string && + email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"); +} + +// +// Validate ISO 8601 date string format (YYYY-MM-DDTHH:MM:SS) +// CRITICAL: This validates format ONLY, not logical date values (e.g., month 13). +// Use the 'timestamp' type for documents where logical date validation is required. +function isValidDateString(dateStr) { + return dateStr is string && + dateStr.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.*Z?$"); +} + +// +// Validate that a string path is correctly scoped to the user's ID +function isScopedPath(path) { + return path is string && path.matches("^users/" + request.auth.uid + "/.*"); +} +// +// Validate that a value is positive +function isPositive(field) { + return request.resource.data[field] is number && request.resource.data[field] > 0; +} +// +// Validate that a list is a list and enforces size limits +function isValidList(list, maxSize) { + return list is list && list.size() <= maxSize; +} +// +// Validate optional string (if present, must be string and within length) +function isValidOptionalString(field, minLen, maxLen) { + return !('field' in request.resource.data) || + (request.resource.data[field] is string && + request.resource.data[field].size() >= minLen && + request.resource.data[field].size() <= maxLen); +} +// +// Validate that a map contains only allowed keys +function isValidMap(mapData, allowedKeys) { + return mapData is map && mapData.keys().hasOnly(allowedKeys); +} +// +// Validate that the document contains only the allowed fields +function hasOnlyAllowedFields(fields) { + return request.resource.data.keys().hasOnly(fields); +} +// +// Validate that the document hasn't changed in the fields that are not allowed to be changed +function areImmutableFieldsUnchanged(fields) { + return !request.resource.data.diff(resource.data).affectedKeys().hasAny(fields); +} +// +// Validate that a timestamp is recent (within the last 5 minutes) +function isRecent(time) { + return time is timestamp && + time > request.time - duration.value(5, 'm') && + time <= request.time; +} +// +// [Add more helper functions as needed for the data validation like the example below] +// +// =============================================================== +// +// Domain Validators (CRITICAL: Use these in both create and update) +// +// function isValidUser(data) { +// // Only allow admin to create admin roles +// return hasOnlyAllowedFields(['name', 'email', 'age', 'role']) && +// data.name is string && data.name.size() > 0 && data.name.size() < 50 && +// data.email is string && isValidEmail(data.email) && +// data.age is number && data.age >= 18 && +// data.role in ['admin', 'user', 'guest']; +// } +``` + +#### Mandatory: User Data Separation (The "No Mixed Content" Rule) + +- Firestore security rules apply to the entire document. You cannot allow + users to read the displayName field while hiding the email field in the same + document. +- If a collection (e.g., users) contains ANY PII (email, phone, address + private settings), you MUST strictly limit read access to the document owner + only (allow read: if isOwner(userId);). +- If the application requires public profiles (e.g., showing user + names/avatars on posts): + - 1. Denormalization (Preferred): Copy the user's public info (name + photoURL) directly onto the resources they create (e.g., store + authorName and authorPhoto inside the posts document). + - 2. Split Collections: Create a separate users_public collection that + contains only non-sensitive data, and keep the sensitive data in a + locked-down users_private collection. +- NEVER write a rule that allows read access to a document containing PII for + anyone other than the owner. + +#### **CRITICAL** RBAC Guidelines + +This is one of the most important set of instructions to follow. Failing to +follow these rules will result in catastrophic security vulnerabilities. + +- **NEVER** allow users to create their own privileged roles. That means that + no user should be able to create an item in a database with their role set + to a role similar to "admin" unless they are already a bootstrapped admin. +- **NEVER** allow users to update their own roles or permissions. +- **NEVER** allow users to grant themselves access to other users' data. +- **NEVER** allow users to bypass the role hierarchy. +- **ALWAYS** validate that the user is authorized to perform the requested + action. +- **ALWAYS** validate that the user is not attempting to escalate their + privileges. +- **ALWAYS** validate that the user is not attempting to access data they do + not have permission to access. + +Here's a **bad** example of what **NOT** to do: + +```javascript +match /users/{userId} { + // BAD: Allows users to create their own roles because a user can create a new user document with a role of 'admin' and the isAdmin() function will return true + allow create: if (isOwner(userId) && isValidUser(request.resource.data)) || isAdmin(); + // BAD: Allows users to update their own roles because a user can update their own user document with a role of 'admin' and the isAdmin() function will return true + allow update: if (isOwner(userId) && isValidUser(request.resource.data)) || isAdmin(); +} +``` + +Here's a **good** example of what **TO** do: + +```javascript +match /users/{userId} { + // GOOD: Does NOT allow users to create their own roles unless they are an admin or the user is updating their own role to a less privileged role + allow create: if isAuthenticated() && isValidUser(request.resource.data) && ((isOwner(userId) && request.resource.data.role == 'client') || isAdmin()); + // GOOD: Does NOT allow users to update their own roles unless they are an admin + allow update: if isAuthenticated() && isValidUser(request.resource.data) && ((isOwner(userId) && request.resource.data.role == resource.data.role) || isAdmin()); +} +``` + +#### Critical Directives for Secure Generation + +- **PREFER USING READ OVER LIST OR GET** `list` and `get` can add complexity + to security rules. Prefer using `read` over them. +- **Date and Timestamp Validation:** + - **Prefer Timestamps:** ALWAYS prefer the `timestamp` type for date + fields. Firestore automatically ensures they are logically valid dates. + - **String Date Risks:** If using strings for dates (e.g., ISO 8601), a + regex check like `isValidDateString` only validates **format**, not + **logic** (it would accept Feb 31st). + - **Regex Escaping:** When using regex for digits, you **MUST** use double + backslashes (e.g., `\\\\d`) in the rules string. Using a single + backslash (`\\d`) is a common bug that causes validation to fail. +- **Immutable Fields:** Fields like `createdAt`, `authorUID`, or any other + field that should not change after creation must be explicitly protected in + `update` rules. (e.g., `request.resource.data.createdAt == + resource.data.createdAt`). **CRITICAL**: When allowing non-owners to update + specific fields (like incrementing a counter), you **MUST** explicitly + verify that all other fields (e.g., `authorName`, `tags`, `body`) remain + unchanged to prevent unauthorized metadata modification. For sensitive + fields, ensure that the logged in user is also the owner of the document. +- **Identity Integrity:** When storing denormalized user identity (e.g. + `authorName`, `authorPhoto`), you **MUST** validate this data. + - **Prefer Auth Token:** If possible, check if + `request.resource.data.authorName == request.auth.token.name`. + - **Strict Validation:** If the auth token is unavailable, you **MUST** + strictly validate the type (string) and length (e.g. < 50 chars) to + prevent spoofing with massive or malicious payloads. + - **Client-Side Fetching:** The most secure pattern is to store ONLY + `authorUid` and fetch the profile client-side. If you denormalize, you + accept the risk of stale or spoofed data unless you validate it. +- **Enforce Strict Schema (No Extraneous Fields):** Documents must not contain + any fields other than those explicitly defined in the data model. This + prevents users from adding arbitrary data. +- **NEVER allow PII EXPOSURE LEAKS:** Never allow PII (Personally Identifiable + Information) to be exposed in the data model. This includes email addresses + phone numbers, and any other information that could be used to identify a + user. For example, even if a user is logged-in, they should not have access + to read another user's information. +- **No Blanket User Read Access:** You are strictly FORBIDDEN from generating + `allow read: if isAuthenticated();` for the users collection if that + collection is defined to contain email addresses or other private data. +- **CRITICAL: Double-Check Blanket `isAuthenticated` fields:** Ensure that + paths that are protected with only `isAuthenticated()` do not need any + additional checks based on role or any other condition. +- **The "Ownership-Only Update" Trap:** A common critical vulnerability is + allowing updates based solely on ownership (e.g., `allow update: if + isOwner(resource.data.uid);`). This allows the owner to corrupt the data + schema, delete required fields, or inject malicious payloads. You **MUST** + always combine ownership checks with data validation (e.g., `allow update: + if isOwner(...) && isValidEntity(...);`) **AND** validate that + self-escalation is not possible. + +- **Deep Array Inspection:** It is insufficient to check if a field `is list`. + You **MUST** validate the contents of the array (e.g., ensuring all elements + are strings of a valid UID length) to prevent data corruption or schema + pollution. For example, a `tags` array must verify that every item is a + string AND that each string is within a reasonable length (e.g., < 20 + chars). + +- **Permission-Field Lockdown:** Fields that control access (e.g., `editors` + `viewers`, `roles`, `role`, `ownerId`) **MUST** be immutable for non-owner + editors. In `update` rules, use `fieldUnchanged()` for these fields unless + the `request.auth.uid` matches the document's original owner/creator. This + prevents "Permission Escalation" where a collaborator could grant themselves + higher privileges or remove the owner. + +### Advanced Validation for Business Logic + +Secure rules must enforce the application's business logic. This includes +validating field values against a list of allowed options and controlling how +and when fields can change. + +\#### 1. Enforce Enum Values + +If a field should only contain specific values (e.g., a status), validate +against a list. + +**Example:** + +```javascript + // A 'task' document's status can only be one of three values + function isValidStatus() { + let validStatuses = ['pending', 'in-progress', 'completed']; + return request.resource.data.status in validStatuses; + } + + allow create: if isValidStatus() && ... +``` + +\#### 2. Validate State Transitions + +For `update` operations, you **MUST** validate that a field is changing from a +valid previous state to a valid new state. This prevents users from bypassing +workflows (e.g., marking a task as 'completed' from 'archived'). + +**Example:** + +```javascript + // A task can only be marked 'completed' if it was 'in-progress' + function validStatusTransition() { + let previousStatus = resource.data.status; + let newStatus = request.resource.data.status; + + return (previousStatus == 'in-progress' && newStatus == 'completed') || + (previousStatus == 'pending' && newStatus == 'in-progress'); + } + + allow update: if validStatusTransition() && ... +``` + +#### 3. Strict Path and Relationship Scoping + +For any field that references another resource (like an image path or a parent +document ID), you **MUST** ensure it is correctly scoped to the user or valid +within the context. + +**Example:** + +```javascript +// Ensure image path is within the user's own storage folder +allow create: if isScopedPath(request.resource.data.imageBucket) && ... +``` + +#### 4. Secure Counter Updates + +When allowing users to update a counter (like `voteCount` or `answerCount`), you +**MUST** ensure: 1. **Atomic Increments:** The field is only changing by exactly ++1 or -1. 2. **Isolation:** **NO OTHER FIELDS** are being modified. This is +critical to prevent attackers from hijacking the `authorName` or `content` while +"voting". 3. **Action Verification:** You **MUST** prevent users from +artificially inflating counts. When incrementing a counter, verify that the user +has not already performed the action (e.g., by checking for the existence of a +'like' document) and is not looping updates. * **CRITICAL:** Relying solely on +`!exists(likeDoc)` is insufficient because a malicious user can skip creating +the document and loop the increment. * **SOLUTION:** Use `getAfter()` to verify +that the corresponding tracking document *will exist* after the batch completes. + +**Example:** + +```javascript +function isValidCounterUpdate(docId) { + // Allow update only if 'voteCount' is the ONLY field changing + return request.resource.data.diff(resource.data).affectedKeys().hasOnly(['voteCount']) && + // And the change is exactly +1 or -1 + math.abs(request.resource.data.voteCount - resource.data.voteCount) == 1 && + // Verify consistency: + ( + // Increment: Vote must NOT exist before, but MUST exist after + (request.resource.data.voteCount > resource.data.voteCount && + !exists(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) && + getAfter(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) != null) || + // Decrement: Vote MUST exist before, but must NOT exist after + (request.resource.data.voteCount < resource.data.voteCount && + exists(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) && + getAfter(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) == null) + ); +} + +allow update: if isValidCounterUpdate(docId) && ... +``` + +#### 5. **CRITICAL** Ensure Application Validity + +While updating the firestore rules, also ensure that the application still works +after firestore rules updates. + +1. **For each collection, implement explicit data validation:** + +- Type Checking: 'field is string', 'field is number', 'field is bool', 'field + is timestamp' +- Required fields validation using 'hasRequiredFields()' +- **Enforce Size Limits:** For **EVERY** string, list, and map field, you + **MUST** enforce realistic size limits (e.g., `text.size() < 1000` + `tags.size() < 20`). **Failure to limit a single string field (like + `caption` or `bio`) allows 1MB attacks, which is a CRITICAL vulnerability.** +- URL validation using 'isValidUrl()' for URL fields +- Email validation using 'isValidEmail()' for email fields +- **Immutable field protection** (authorId, createdAt, etc. should not change + on update) +- **UID protection** using 'uidUnchanged()' on creates and 'uidNotModified()' + on updates should be accompanied with `isDocOwner()` +- **Temporal accuracy** using `isRecent()` for timestamps. +- **Range validation** using `isPositive()` or similar for numbers. +- **Path scoping** using `isScopedPath()` for storage paths. + +Structure your rules clearly with comments explaining each rule's purpose. + +#### Phase-3: Devil's Advocate Attack + +**Critical step:** Systematically attempt to break your own rules using the +following attack vectors. You MUST document the outcome of each attempt. + +1. **Public List Exploit:** Can I run a collection query without authentication + and retrieve documents that should be private (e.g., where `visible == + false`)? +2. **Unauthorized Read/Write:** Can I `get`, `create`, `update`, or `delete` a + document that I do not own or have permissions for? +3. **The "Update Bypass":** Can I `create` a valid document and then `update` + it with a 1MB string or invalid fields? (Tests if validation logic is + missing from `update`). +4. **Ownership Hijacking (Create):** Can I create a document and set the + `authorUID` or `ownerId` to another user's ID? +5. **Ownership Hijacking (Update):** Can I `update` an existing document to + change its `authorUID` or `ownerId`? +6. **Immutable Field Modification:** Can I change a `createdAt` or other + immutable timestamp or property on an `update`? +7. **Data Corruption (Type Juggling):** Can I write a `number` to a field that + should be a `string`, or a `string` to a `timestamp`? +8. **Validation Bypass (Create vs. Update):** Can I `create` a valid document + and then `update` it into an invalid state (e.g., remove a required field + write a string that's too long)? +9. **Resource Exhaustion / DoS:** Can I write an enormous string (e.g., 1MB) to + any field that accepts a string or a massive array to a list field? Every + string field (e.g., `bio`, `url`, `name`) MUST have a `.size()` check. If + any are missing, it's a "Resource Exhaustion/DoS" risk. +10. **Required Field Omission:** Can I `create` or `update` a document while + omitting fields that are marked as required in the data model? +11. **Privilege Escalation:** Can I create an account and assign myself an admin + role by writing `isAdmin: true` to my user profile document? (Tests reliance + on document data vs. custom claims). +12. **Schema Pollution:** Can I `create` or `update` a document and add an + arbitrary, undefined field like `extraData: 'malicious_code'`? (Tests for + strict schema enforcement). +13. **Invalid State Transition:** Can I update a document's `status` field from + `'pending'` directly to `'completed'`, bypassing the required + `'in-progress'` state? (Tests business logic enforcement). +14. **Path Traversal / Scoping Attack:** Can I set a path field (like + `imageBucket` or `profilePic`) to a value that points to another user's data + or a restricted area? (Tests for regex path scoping). +15. **Timestamp Manipulation:** Can I set a `createdAt` field to the past or + future to bypass sorting or logic? (Tests for `request.time` validation). +16. **Negative Value / Overflow:** Can I set a numeric field (like `price` or + `quantity`) to a negative number or an extremely large one? (Tests for range + validation). +17. **The "Mixed Content" Leak:** Create a second user. Can User B read User A's + users document? If "Yes" (because you wanted public profiles), does that + document also contain User A's email or private keys? If both are true, the + rules are insecure. +18. **Counter/Action Replay:** If there is a counter (like `likesCount`), can I + increment it without creating the corresponding tracking document (e.g. + inside `likes/{userId}`)? Can I increment it twice? (Tests for `getAfter()` + consistency checks). +19. **Orphaned Subcollection Access:** Can I read/write to a subcollection + (e.g., `users/123/posts/456`) if the parent document (`users/123`) does not + exist? (Tests for parent existence checks). +20. **Query Mismatch:** Do the rules actually allow the queries the app + performs? (e.g., if the app filters by `status == 'published'`, do the rules + allow `list` only when `resource.data.status == 'published'`?) +21. **Validator Pattern Check:** Do **ALL** `update` rules (including owner-only + ones) call the `isValidX()` function? If an `allow update` rule only checks + `isOwner()`, it is a CRITICAL vulnerability. + +Document each attack attempt and whether it succeeded. If ANY attack succeeds: + +- Fix the security hole +- Regenerate the rules +- **Repeat Phase-3** until no attacks succeed + +#### Phase-4: Syntactic Validation + +Once devil's advocate testing passes, repeat until rules pass validation. + +**After all phases are complete, create or update the `firestore.rules` file.** + +### Critical Constraints + +1. **Never skip the devil's advocate phase** - this is your primary security + validation +2. **MUST include helper functions** for common operations ('isAuthenticated' + 'isOwner', 'uidUnchanged', 'uidNotModified') AND domain validators + ('isValidUser', etc.) +3. **MUST document assumed data models** at the beginning of the rules file +4. **Always validate the rules syntax** using 'firebase deploy --only + firestore:rules --dry-run' or a similar tool before outputting the final + file. +5. **Provide complete, runnable code** - no placeholders or TODOs +6. **Document all assumptions** about data structure or access patterns +7. **Always run the devil's advocate attack** after any modification of the + rules. +8. **Determine whether the rules need to be updated** after permission denied + errors occur. +9. **Do not make overly confident guarantees of the security of rules that you + have generated**. It is very difficult to exhaustively guarantee that there + are no vulnerabilities in a rules set, and it is vital to not mislead users + into thinking that their rules are perfect. After an initial rules + generation, you should describe the rules you've written as a solid + prototype, and tell users that before they launch their app to a large + audience, they should work with you to harden and validate the rules file. + Be clear that users should carefully review rules to ensure security. diff --git a/transformations/android-studio/skills/firebase-firestore/references/standard/android_sdk_usage.md b/transformations/android-studio/skills/firebase-firestore/references/standard/android_sdk_usage.md new file mode 100644 index 00000000..32215cd0 --- /dev/null +++ b/transformations/android-studio/skills/firebase-firestore/references/standard/android_sdk_usage.md @@ -0,0 +1,189 @@ +# Cloud Firestore on Android (Kotlin) + +This guide walks you through using Cloud Firestore in your Android app using Kotlin. + +### Enable Firestore via CLI + +Before adding dependencies in your app, make sure you enable the Firestore service in your Firebase Project using the Firebase CLI: + +```bash +npx -y firebase-tools@latest init firestore +``` + + --- + +### 1. Add Dependencies + +In your module-level `build.gradle.kts` (usually `app/build.gradle.kts`), add the dependency for Cloud Firestore: + +```kotlin +dependencies { + // [AGENT] Fetch the latest available BoM version from https://firebase.google.com/support/release-notes/android before adding this + implementation(platform("com.google.firebase:firebase-bom:")) + + // Add the dependency for the Cloud Firestore library + // When using the BoM, you don't specify versions in Firebase library dependencies + implementation("com.google.firebase:firebase-firestore") +} +``` + +--- + +### 2. Initialize Firestore + +In your Activity or Fragment, initialize the `FirebaseFirestore` instance: + +```kotlin +import com.google.firebase.firestore.FirebaseFirestore +import com.google.firebase.firestore.ktx.firestore +import com.google.firebase.ktx.Firebase + +class MainActivity : AppCompatActivity() { + + private lateinit var db: FirebaseFirestore + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val db = Firebase.firestore + + setContent { + MaterialTheme { + Text("Firestore initialized!") + } + } + } +} +``` + +#### Jetpack Compose (Modern) + +Initialize inside a `ComponentActivity` using `setContent`: + +```kotlin +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import com.google.firebase.Firebase +import com.google.firebase.firestore.firestore + +class MainActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val db = Firebase.firestore + + setContent { + MaterialTheme { + Text("Firestore initialized!") + } + } + } +} +``` + +--- + +### 3. Add Data + +Add a new document with a generated ID using `add()`: + +```kotlin +// Create a new user with a first and last name +val user = hashMapOf( + "first" to "Ada" + "last" to "Lovelace" + "born" to 1815 +) + +// Add a new document with a generated ID +db.collection("users") + .add(user) + .addOnSuccessListener { documentReference -> + Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}") + } + .addOnFailureListener { e -> + Log.w(TAG, "Error adding document", e) + } +``` + +Or set a document with a specific ID using `set()`: + +```kotlin +val city = hashMapOf( + "name" to "Los Angeles" + "state" to "CA" + "country" to "USA" +) + +db.collection("cities").document("LA") + .set(city) + .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully written!") } + .addOnFailureListener { e -> Log.w(TAG, "Error writing document", e) } +``` + +--- + +### 4. Read Data + +Read a single document using `get()`: + +```kotlin +val docRef = db.collection("cities").document("SF") +docRef.get() + .addOnSuccessListener { document -> + if (document != null && document.exists()) { + Log.d(TAG, "DocumentSnapshot data: ${document.data}") + } else { + Log.d(TAG, "No such document") + } + } + .addOnFailureListener { exception -> + Log.d(TAG, "get failed with ", exception) + } +``` + +Read multiple documents using a query: + +```kotlin +db.collection("cities") + .whereEqualTo("capital", true) + .get() + .addOnSuccessListener { documents -> + for (document in documents) { + Log.d(TAG, "${document.id} => ${document.data}") + } + } + .addOnFailureListener { exception -> + Log.w(TAG, "Error getting documents: ", exception) + } +``` + +--- + +### 5. Update Data + +Update some fields of a document using `update()` without overwriting the entire document: + +```kotlin +val washingtonRef = db.collection("cities").document("DC") + +// Set the "isCapital" field to true +washingtonRef + .update("capital", true) + .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully updated!") } + .addOnFailureListener { e -> Log.w(TAG, "Error updating document", e) } +``` + +--- + +### 6. Delete Data + +Delete a document using `delete()`: + +```kotlin +db.collection("cities").document("DC") + .delete() + .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully deleted!") } + .addOnFailureListener { e -> Log.w(TAG, "Error deleting document", e) } +``` diff --git a/transformations/android-studio/skills/firebase-firestore/references/standard/indexes.md b/transformations/android-studio/skills/firebase-firestore/references/standard/indexes.md new file mode 100644 index 00000000..39697248 --- /dev/null +++ b/transformations/android-studio/skills/firebase-firestore/references/standard/indexes.md @@ -0,0 +1,113 @@ +# Firestore Indexes Reference + +Indexes allow Firestore to ensure that query performance depends on the size of +the result set, not the size of the database. + +## Index Types + +### Single-Field Indexes + +In Standard Edition, Firestore **automatically creates** a single-field index +for every field in a document (and subfields in maps). * **Support**: Simple +equality queries (`==`) and single-field range/sort queries (`<`, `<=` +`orderBy`). * **Behavior**: You generally don't need to manage these unless you +want to *exempt* a field. + +### Composite Indexes + +A composite index stores a sorted mapping of all documents based on an ordered +list of fields. * **Support**: Complex queries that filter or sort by **multiple +fields**. * **Creation**: These are **NOT** automatically created. You must +define them manually or via the console/CLI. + +## Automatic vs. Manual Management + +### What is Automatic? + +* Indexes for simple queries. +* Merging of single-field indexes for multiple equality filters (e.g. + `where("state", "==", "CA").where("country", "==", "USA")`). + +### When Do I Need to Act? + +If you attempt a query that requires a composite index, the SDK will throw an +error containing a **direct link** to the Firebase Console to create that +specific index. + +**Example Error:** + +> "The query requires an index. You can create it here: +> https://console.firebase.google.com/project/..." + +## Query Support Examples + +| Query Type | Index Required | +| :----------------------------------- | :----------------------------------- | +| **Simple Equality**
`where("a", | Automatic (Single-Field) | +: "==", 1)` : : +| **Simple Range/Sort**
`where("a", | Automatic (Single-Field) | +: ">", 1).orderBy("a")` : : +| **Multiple Equality**
`where("a", | Automatic (Merged Single-Field) | +: "==", 1).where("b", "==", 2)` : : +| **Equality + | **Composite Index** | +: Range/Sort**
`where("a", "==", : : +: 1).where("b", ">", 2)` : : +| **Multiple Ranges**
`where("a", | **Composite Index** (and technically | +: ">", 1).where("b", ">", 2)` : limited query support) : +| **Array Contains + | **Composite Index** | +: Equality**
`where("tags", : : +: "array-contains", : : +: "news").where("active", "==", true)` : : + +## Best Practices & Exemptions + +You can **exempt** fields from automatic indexing to save storage or strictly +enforce write limits. + +### 1. High Write Rates (Sequential Values) + +* **Problem**: Indexing fields that increase sequentially (like `timestamp`) + limits the write rate to ~500 writes/second per collection. +* **Solution**: If you don't query on this field, **exempt** it from simple + indexing. + +### 2. Large String/Map/Array Fields + +* **Problem**: Indexing limits (40k entries per doc). Indexing large blobs + wastes storage. +* **Solution**: Exempt large text blobs or huge arrays if they aren't used for + filtering. + +### 3. TTL Fields + +* **Problem**: TTL (Time-To-Live) deletion can cause index churn. +* **Solution**: Exempt the TTL timestamp field from indexing if you don't + query it. + +## Management + +### Config files + +Your indexes should be defined in `firestore.indexes.json` (pointed to by +`firebase.json`). + +```json +{ + "indexes": [ + { + "collectionGroup": "cities" + "queryScope": "COLLECTION" + "fields": [ + { "fieldPath": "country", "order": "ASCENDING" } + { "fieldPath": "population", "order": "DESCENDING" } + ] + } + ] + "fieldOverrides": [] +} +``` + +### CLI Commands + +Deploy indexes only: `bash npx -y firebase-tools@latest deploy --only +firestore:indexes` diff --git a/transformations/android-studio/skills/firebase-firestore/references/standard/provisioning.md b/transformations/android-studio/skills/firebase-firestore/references/standard/provisioning.md new file mode 100644 index 00000000..022a78f0 --- /dev/null +++ b/transformations/android-studio/skills/firebase-firestore/references/standard/provisioning.md @@ -0,0 +1,102 @@ +# Provisioning Cloud Firestore + +## Manual Initialization + +Initialize the following firebase configuration files manually. Do not use `npx +-y firebase-tools@latest init`, as it expects interactive inputs. + +1. **Create `firebase.json`**: This file configures the Firebase CLI. +2. **Create `firestore.rules`**: This file contains your security rules. +3. **Create `firestore.indexes.json`**: This file contains your index + definitions. + +### 1. Create `firebase.json` + +Create a file named `firebase.json` in your project root with the following +content. If this file already exists, instead append to the existing JSON: + +```json +{ + "firestore": { + "rules": "firestore.rules" + "indexes": "firestore.indexes.json" + } +} +``` + +This will use the default database with the Standard edition. To use a different +database, specify the database ID and location: +1. Run `npx -y firebase-tools@latest firestore:locations` to get the list of locations. +2. Ask the user which location to use, suggesting colocation if other parts of the app already have a region selected. + +You can check the list of available databases using `npx -y firebase-tools@latest firestore:databases:list`. + +If the database does not exist, it will be created when you deploy with the specified configuration: + +```json +{ + "firestore": { + "rules": "firestore.rules" + "indexes": "firestore.indexes.json" + "database": "my-database-id" + "location": "" + } +} +``` + +### 2. Create `firestore.rules` + +Create a file named `firestore.rules`. A good starting point (locking down the +database) is: + +``` +rules_version = '2'; +service cloud.firestore { + match /databases/{database}/documents { + match /{document=**} { + allow read, write: if false; + } + } +} +``` + +*See [security_rules.md](security_rules.md) for how to write actual rules.* + +### 3. Create `firestore.indexes.json` + +Create a file named `firestore.indexes.json` with an empty configuration to +start: + +```json +{ + "indexes": [] + "fieldOverrides": [] +} +``` + +*See [indexes.md](indexes.md) for how to configure indexes.* + +## Deploy database, rules and indexes + +**CRITICAL**: You MUST deploy the firestore configuration for the database to be provisioned in the cloud and for your rules/indexes to take effect. If you don't run this, your database will not exist. +```bash +# To deploy all rules and indexes +npx -y firebase-tools@latest deploy --only firestore + +# To deploy just rules +npx -y firebase-tools@latest deploy --only firestore:rules + +# To deploy just indexes +npx -y firebase-tools@latest deploy --only firestore:indexes +``` + +## Local Emulation + +To run Firestore locally for development and testing: + +```bash +npx -y firebase-tools@latest emulators:start --only firestore +``` + +This starts the Firestore emulator, typically on port 8080. You can interact +with it using the Emulator UI (usually at http://localhost:4000/firestore). diff --git a/transformations/android-studio/skills/firebase-firestore/references/standard/security_rules.md b/transformations/android-studio/skills/firebase-firestore/references/standard/security_rules.md new file mode 100644 index 00000000..679eb057 --- /dev/null +++ b/transformations/android-studio/skills/firebase-firestore/references/standard/security_rules.md @@ -0,0 +1,569 @@ +## 1. Generate Firestore Rules + +You are an expert Firebase Security Rules engineer with deep knowledge of +Firestore security best practices. Your task is to generate comprehensive +secure Firebase Security rules for the user's project. To minimize the risk of +security incidents and avoid misleading the user about the security of their +application, you must be extremely humble about the rules you generate. Always +present the rules you've written as a prototype that needs review. + +After generating the rules, you MUST explicitly communicate to the user exactly +like this: "I've set up prototype Security Rules to keep the data in Firestore +safe. They are designed to be secure for . However, you +should review and verify them before broadly sharing your app. If you'd like, I +can help you harden these rules." + +### Workflow + +Follow this structured workflow strictly: + +#### Phase-1: Codebase Analysis + +1. **Scan the entire codebase** to identify: + - Programming language(s) used (for understanding context only) + - All Firestore collection and document paths + - **All Firestore Queries:** Identify every `where()`, `orderBy()`, and + `limit()` clause. The security rules **MUST** allow these specific + queries. + - Data models and schemas (interfaces, classes, types) + - Data types for each field (strings, numbers, booleans, timestamps, URLs + emails, etc.) + - Required vs. optional fields + - Field constraints (min/max length, format patterns, allowed values) + - CRUD operations (create, read, update, delete) + - Authentication patterns (Firebase Auth, custom tokens, anonymous) + - Access patterns and business logic rules +2. **Document your findings** in a untracked file. Refer to this file when + generating the security rules. + +#### Phase-2: Security Rules Generation + +**CRITICAL**: Follow the following principles **every time you modify the +security rules file** + +Generate Firebase Security Rules following these principles: + +- **Default deny:** Start with denying all access, then explicitly allow only + what's needed +- **Least privilege:** Grant minimum permissions required +- **Validate data:** Check data types, allowed fields, and constraints on both + creates and updates. + - **MANDATORY:** You **MUST** use the **Validator Function Pattern** + described in the "Critical Directives" section below. This involves + defining a specific validation function (e.g., `isValidUser`) and + calling it in **BOTH** `create` and `update` rules. + - **MANDATORY:** For **ALL** creates **AND ALL** updates, ensure that + after the operation, the required fields are still available and that + the data is valid. +- **Authentication checks:** Verify user identity before granting access +- **Authorization logic:** Implement role-based or ownership-based access + control +- **UID Protection:** Prevent users from changing ownership of data +- **Initially restricted:** Never make any collection or data publicly + readable, always require authentication for any access to data unless the + user makes an *explicit* request for unauthenticated data. + +This means the first firestore.rules file you generate must never have any +"allow read: true" statements. + +**Structure Requirements:** + +1. **Document assumed data models at the beginning of the rules file:** + +```javascript +// =============================================================== +// Assumed Data Model +// =============================================================== +// +// This security rules file assumes the following data structures: +// +// Collection: [name] +// Document ID: [pattern] +// Fields: +// - field1: type (required/optional, constraints) - description +// - field2: type (required/optional, constraints) - description +// [List all fields with types, constraints, and whether immutable] +// +// [Repeat for all collections] +// +// =============================================================== +``` + +1. **Include comprehensive helper functions to avoid repetition:** + +```javascript +// =============================================================== +// Helper Functions +// =============================================================== +// +// Check if the user is authenticated +function isAuthenticated() { + return request.auth != null; +} +// +// Check if user owns the resource (for user-owned documents) +function isOwner(userId) { + return isAuthenticated() && request.auth.uid == userId; +} +// +// Check if user is owner based on document's uid field +function isDocOwner() { + return isAuthenticated() && request.auth.uid == resource.data.uid; +} +// +// Verify UID hasn't been tampered with on create +function uidUnchanged() { + return !('uid' in request.resource.data) || + request.resource.data.uid == request.auth.uid; +} +// +// Ensure uid field is not modified on update +function uidNotModified() { + return !('uid' in request.resource.data) || + request.resource.data.uid == resource.data.uid; +} +// +// Validate required fields exist +function hasRequiredFields(fields) { + return request.resource.data.keys().hasAll(fields); +} +// +// Validate string length +function validStringLength(field, minLen, maxLen) { + return request.resource.data[field] is string && + request.resource.data[field].size() >= minLen && + request.resource.data[field].size() <= maxLen; +} +// +// Validate URL format (must start with https:// or http://) +function isValidUrl(url) { + return url is string && + (url.matches("^https://.*") || url.matches("^http://.*")); +} +// +// Validate email format +function isValidEmail(email) { + return email is string && + email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"); +} + +// +// Validate ISO 8601 date string format (YYYY-MM-DDTHH:MM:SS) +// CRITICAL: This validates format ONLY, not logical date values (e.g., month 13). +// Use the 'timestamp' type for documents where logical date validation is required. +function isValidDateString(dateStr) { + return dateStr is string && + dateStr.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.*Z?$"); +} + +// +// Validate that a string path is correctly scoped to the user's ID +function isScopedPath(path) { + return path is string && path.matches("^users/" + request.auth.uid + "/.*"); +} +// +// Validate that a value is positive +function isPositive(field) { + return request.resource.data[field] is number && request.resource.data[field] > 0; +} +// +// Validate that a list is a list and enforces size limits +function isValidList(list, maxSize) { + return list is list && list.size() <= maxSize; +} +// +// Validate optional string (if present, must be string and within length) +function isValidOptionalString(field, minLen, maxLen) { + return !('field' in request.resource.data) || + (request.resource.data[field] is string && + request.resource.data[field].size() >= minLen && + request.resource.data[field].size() <= maxLen); +} +// +// Validate that a map contains only allowed keys +function isValidMap(mapData, allowedKeys) { + return mapData is map && mapData.keys().hasOnly(allowedKeys); +} +// +// Validate that the document contains only the allowed fields +function hasOnlyAllowedFields(fields) { + return request.resource.data.keys().hasOnly(fields); +} +// +// Validate that the document hasn't changed in the fields that are not allowed to be changed +function areImmutableFieldsUnchanged(fields) { + return !request.resource.data.diff(resource.data).affectedKeys().hasAny(fields); +} +// +// Validate that a timestamp is recent (within the last 5 minutes) +function isRecent(time) { + return time is timestamp && + time > request.time - duration.value(5, 'm') && + time <= request.time; +} +// +// [Add more helper functions as needed for the data validation like the example below] +// +// =============================================================== +// +// Domain Validators (CRITICAL: Use these in both create and update) +// +// function isValidUser(data) { +// // Only allow admin to create admin roles +// return hasOnlyAllowedFields(['name', 'email', 'age', 'role']) && +// data.name is string && data.name.size() > 0 && data.name.size() < 50 && +// data.email is string && isValidEmail(data.email) && +// data.age is number && data.age >= 18 && +// data.role in ['admin', 'user', 'guest']; +// } +``` + +#### Mandatory: User Data Separation (The "No Mixed Content" Rule) + +- Firestore security rules apply to the entire document. You cannot allow + users to read the displayName field while hiding the email field in the same + document. +- If a collection (e.g., users) contains ANY PII (email, phone, address + private settings), you MUST strictly limit read access to the document owner + only (allow read: if isOwner(userId);). +- If the application requires public profiles (e.g., showing user + names/avatars on posts): + - 1. Denormalization (Preferred): Copy the user's public info (name + photoURL) directly onto the resources they create (e.g., store + authorName and authorPhoto inside the posts document). + - 2. Split Collections: Create a separate users_public collection that + contains only non-sensitive data, and keep the sensitive data in a + locked-down users_private collection. +- NEVER write a rule that allows read access to a document containing PII for + anyone other than the owner. + +#### **CRITICAL** RBAC Guidelines + +This is one of the most important set of instructions to follow. Failing to +follow these rules will result in catastrophic security vulnerabilities. + +- **NEVER** allow users to create their own privileged roles. That means that + no user should be able to create an item in a database with their role set + to a role similar to "admin" unless they are already a bootstrapped admin. +- **NEVER** allow users to update their own roles or permissions. +- **NEVER** allow users to grant themselves access to other users' data. +- **NEVER** allow users to bypass the role hierarchy. +- **ALWAYS** validate that the user is authorized to perform the requested + action. +- **ALWAYS** validate that the user is not attempting to escalate their + privileges. +- **ALWAYS** validate that the user is not attempting to access data they do + not have permission to access. + +Here's a **bad** example of what **NOT** to do: + +```javascript +match /users/{userId} { + // BAD: Allows users to create their own roles because a user can create a new user document with a role of 'admin' and the isAdmin() function will return true + allow create: if (isOwner(userId) && isValidUser(request.resource.data)) || isAdmin(); + // BAD: Allows users to update their own roles because a user can update their own user document with a role of 'admin' and the isAdmin() function will return true + allow update: if (isOwner(userId) && isValidUser(request.resource.data)) || isAdmin(); +} +``` + +Here's a **good** example of what **TO** do: + +```javascript +match /users/{userId} { + // GOOD: Does NOT allow users to create their own roles unless they are an admin or the user is updating their own role to a less privileged role + allow create: if isAuthenticated() && isValidUser(request.resource.data) && ((isOwner(userId) && request.resource.data.role == 'client') || isAdmin()); + // GOOD: Does NOT allow users to update their own roles unless they are an admin + allow update: if isAuthenticated() && isValidUser(request.resource.data) && ((isOwner(userId) && request.resource.data.role == resource.data.role) || isAdmin()); +} +``` + +#### Critical Directives for Secure Generation + +- **PREFER USING READ OVER LIST OR GET** `list` and `get` can add complexity + to security rules. Prefer using `read` over them. +- **Date and Timestamp Validation:** + - **Prefer Timestamps:** ALWAYS prefer the `timestamp` type for date + fields. Firestore automatically ensures they are logically valid dates. + - **String Date Risks:** If using strings for dates (e.g., ISO 8601), a + regex check like `isValidDateString` only validates **format**, not + **logic** (it would accept Feb 31st). + - **Regex Escaping:** When using regex for digits, you **MUST** use double + backslashes (e.g., `\\\\d`) in the rules string. Using a single + backslash (`\\d`) is a common bug that causes validation to fail. +- **Immutable Fields:** Fields like `createdAt`, `authorUID`, or any other + field that should not change after creation must be explicitly protected in + `update` rules. (e.g., `request.resource.data.createdAt == + resource.data.createdAt`). **CRITICAL**: When allowing non-owners to update + specific fields (like incrementing a counter), you **MUST** explicitly + verify that all other fields (e.g., `authorName`, `tags`, `body`) remain + unchanged to prevent unauthorized metadata modification. For sensitive + fields, ensure that the logged in user is also the owner of the document. +- **Identity Integrity:** When storing denormalized user identity (e.g. + `authorName`, `authorPhoto`), you **MUST** validate this data. + - **Prefer Auth Token:** If possible, check if + `request.resource.data.authorName == request.auth.token.name`. + - **Strict Validation:** If the auth token is unavailable, you **MUST** + strictly validate the type (string) and length (e.g. < 50 chars) to + prevent spoofing with massive or malicious payloads. + - **Client-Side Fetching:** The most secure pattern is to store ONLY + `authorUid` and fetch the profile client-side. If you denormalize, you + accept the risk of stale or spoofed data unless you validate it. +- **Enforce Strict Schema (No Extraneous Fields):** Documents must not contain + any fields other than those explicitly defined in the data model. This + prevents users from adding arbitrary data. +- **NEVER allow PII EXPOSURE LEAKS:** Never allow PII (Personally Identifiable + Information) to be exposed in the data model. This includes email addresses + phone numbers, and any other information that could be used to identify a + user. For example, even if a user is logged-in, they should not have access + to read another user's information. +- **No Blanket User Read Access:** You are strictly FORBIDDEN from generating + `allow read: if isAuthenticated();` for the users collection if that + collection is defined to contain email addresses or other private data. +- **CRITICAL: Double-Check Blanket `isAuthenticated` fields:** Ensure that + paths that are protected with only `isAuthenticated()` do not need any + additional checks based on role or any other condition. +- **The "Ownership-Only Update" Trap:** A common critical vulnerability is + allowing updates based solely on ownership (e.g., `allow update: if + isOwner(resource.data.uid);`). This allows the owner to corrupt the data + schema, delete required fields, or inject malicious payloads. You **MUST** + always combine ownership checks with data validation (e.g., `allow update: + if isOwner(...) && isValidEntity(...);`) **AND** validate that + self-escalation is not possible. + +- **Deep Array Inspection:** It is insufficient to check if a field `is list`. + You **MUST** validate the contents of the array (e.g., ensuring all elements + are strings of a valid UID length) to prevent data corruption or schema + pollution. For example, a `tags` array must verify that every item is a + string AND that each string is within a reasonable length (e.g., < 20 + chars). + +- **Permission-Field Lockdown:** Fields that control access (e.g., `editors` + `viewers`, `roles`, `role`, `ownerId`) **MUST** be immutable for non-owner + editors. In `update` rules, use `fieldUnchanged()` for these fields unless + the `request.auth.uid` matches the document's original owner/creator. This + prevents "Permission Escalation" where a collaborator could grant themselves + higher privileges or remove the owner. + +### Advanced Validation for Business Logic + +Secure rules must enforce the application's business logic. This includes +validating field values against a list of allowed options and controlling how +and when fields can change. + +\#### 1. Enforce Enum Values + +If a field should only contain specific values (e.g., a status), validate +against a list. + +**Example:** + +```javascript + // A 'task' document's status can only be one of three values + function isValidStatus() { + let validStatuses = ['pending', 'in-progress', 'completed']; + return request.resource.data.status in validStatuses; + } + + allow create: if isValidStatus() && ... +``` + +\#### 2. Validate State Transitions + +For `update` operations, you **MUST** validate that a field is changing from a +valid previous state to a valid new state. This prevents users from bypassing +workflows (e.g., marking a task as 'completed' from 'archived'). + +**Example:** + +```javascript + // A task can only be marked 'completed' if it was 'in-progress' + function validStatusTransition() { + let previousStatus = resource.data.status; + let newStatus = request.resource.data.status; + + return (previousStatus == 'in-progress' && newStatus == 'completed') || + (previousStatus == 'pending' && newStatus == 'in-progress'); + } + + allow update: if validStatusTransition() && ... +``` + +#### 3. Strict Path and Relationship Scoping + +For any field that references another resource (like an image path or a parent +document ID), you **MUST** ensure it is correctly scoped to the user or valid +within the context. + +**Example:** + +```javascript +// Ensure image path is within the user's own storage folder +allow create: if isScopedPath(request.resource.data.imageBucket) && ... +``` + +#### 4. Secure Counter Updates + +When allowing users to update a counter (like `voteCount` or `answerCount`), you +**MUST** ensure: 1. **Atomic Increments:** The field is only changing by exactly ++1 or -1. 2. **Isolation:** **NO OTHER FIELDS** are being modified. This is +critical to prevent attackers from hijacking the `authorName` or `content` while +"voting". 3. **Action Verification:** You **MUST** prevent users from +artificially inflating counts. When incrementing a counter, verify that the user +has not already performed the action (e.g., by checking for the existence of a +'like' document) and is not looping updates. * **CRITICAL:** Relying solely on +`!exists(likeDoc)` is insufficient because a malicious user can skip creating +the document and loop the increment. * **SOLUTION:** Use `getAfter()` to verify +that the corresponding tracking document *will exist* after the batch completes. + +**Example:** + +```javascript +function isValidCounterUpdate(docId) { + // Allow update only if 'voteCount' is the ONLY field changing + return request.resource.data.diff(resource.data).affectedKeys().hasOnly(['voteCount']) && + // And the change is exactly +1 or -1 + math.abs(request.resource.data.voteCount - resource.data.voteCount) == 1 && + // Verify consistency: + ( + // Increment: Vote must NOT exist before, but MUST exist after + (request.resource.data.voteCount > resource.data.voteCount && + !exists(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) && + getAfter(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) != null) || + // Decrement: Vote MUST exist before, but must NOT exist after + (request.resource.data.voteCount < resource.data.voteCount && + exists(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) && + getAfter(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) == null) + ); +} + +allow update: if isValidCounterUpdate(docId) && ... +``` + +#### 5. **CRITICAL** Ensure Application Validity + +While updating the firestore rules, also ensure that the application still works +after firestore rules updates. + +1. **For each collection, implement explicit data validation:** + +- Type Checking: 'field is string', 'field is number', 'field is bool', 'field + is timestamp' +- Required fields validation using 'hasRequiredFields()' +- **Enforce Size Limits:** For **EVERY** string, list, and map field, you + **MUST** enforce realistic size limits (e.g., `text.size() < 1000` + `tags.size() < 20`). **Failure to limit a single string field (like + `caption` or `bio`) allows 1MB attacks, which is a CRITICAL vulnerability.** +- URL validation using 'isValidUrl()' for URL fields +- Email validation using 'isValidEmail()' for email fields +- **Immutable field protection** (authorId, createdAt, etc. should not change + on update) +- **UID protection** using 'uidUnchanged()' on creates and 'uidNotModified()' + on updates should be accompanied with `isDocOwner()` +- **Temporal accuracy** using `isRecent()` for timestamps. +- **Range validation** using `isPositive()` or similar for numbers. +- **Path scoping** using `isScopedPath()` for storage paths. + +Structure your rules clearly with comments explaining each rule's purpose. + +#### Phase-3: Devil's Advocate Attack + +**Critical step:** Systematically attempt to break your own rules using the +following attack vectors. You MUST document the outcome of each attempt. + +1. **Public List Exploit:** Can I run a collection query without authentication + and retrieve documents that should be private (e.g., where `visible == + false`)? +2. **Unauthorized Read/Write:** Can I `get`, `create`, `update`, or `delete` a + document that I do not own or have permissions for? +3. **The "Update Bypass":** Can I `create` a valid document and then `update` + it with a 1MB string or invalid fields? (Tests if validation logic is + missing from `update`). +4. **Ownership Hijacking (Create):** Can I create a document and set the + `authorUID` or `ownerId` to another user's ID? +5. **Ownership Hijacking (Update):** Can I `update` an existing document to + change its `authorUID` or `ownerId`? +6. **Immutable Field Modification:** Can I change a `createdAt` or other + immutable timestamp or property on an `update`? +7. **Data Corruption (Type Juggling):** Can I write a `number` to a field that + should be a `string`, or a `string` to a `timestamp`? +8. **Validation Bypass (Create vs. Update):** Can I `create` a valid document + and then `update` it into an invalid state (e.g., remove a required field + write a string that's too long)? +9. **Resource Exhaustion / DoS:** Can I write an enormous string (e.g., 1MB) to + any field that accepts a string or a massive array to a list field? Every + string field (e.g., `bio`, `url`, `name`) MUST have a `.size()` check. If + any are missing, it's a "Resource Exhaustion/DoS" risk. +10. **Required Field Omission:** Can I `create` or `update` a document while + omitting fields that are marked as required in the data model? +11. **Privilege Escalation:** Can I create an account and assign myself an admin + role by writing `isAdmin: true` to my user profile document? (Tests reliance + on document data vs. custom claims). +12. **Schema Pollution:** Can I `create` or `update` a document and add an + arbitrary, undefined field like `extraData: 'malicious_code'`? (Tests for + strict schema enforcement). +13. **Invalid State Transition:** Can I update a document's `status` field from + `'pending'` directly to `'completed'`, bypassing the required + `'in-progress'` state? (Tests business logic enforcement). +14. **Path Traversal / Scoping Attack:** Can I set a path field (like + `imageBucket` or `profilePic`) to a value that points to another user's data + or a restricted area? (Tests for regex path scoping). +15. **Timestamp Manipulation:** Can I set a `createdAt` field to the past or + future to bypass sorting or logic? (Tests for `request.time` validation). +16. **Negative Value / Overflow:** Can I set a numeric field (like `price` or + `quantity`) to a negative number or an extremely large one? (Tests for range + validation). +17. **The "Mixed Content" Leak:** Create a second user. Can User B read User A's + users document? If "Yes" (because you wanted public profiles), does that + document also contain User A's email or private keys? If both are true, the + rules are insecure. +18. **Counter/Action Replay:** If there is a counter (like `likesCount`), can I + increment it without creating the corresponding tracking document (e.g. + inside `likes/{userId}`)? Can I increment it twice? (Tests for `getAfter()` + consistency checks). +19. **Orphaned Subcollection Access:** Can I read/write to a subcollection + (e.g., `users/123/posts/456`) if the parent document (`users/123`) does not + exist? (Tests for parent existence checks). +20. **Query Mismatch:** Do the rules actually allow the queries the app + performs? (e.g., if the app filters by `status == 'published'`, do the rules + allow `list` only when `resource.data.status == 'published'`?) +21. **Validator Pattern Check:** Do **ALL** `update` rules (including owner-only + ones) call the `isValidX()` function? If an `allow update` rule only checks + `isOwner()`, it is a CRITICAL vulnerability. + +Document each attack attempt and whether it succeeded. If ANY attack succeeds: + +- Fix the security hole +- Regenerate the rules +- **Repeat Phase-3** until no attacks succeed + +#### Phase-4: Syntactic Validation + +Once devil's advocate testing passes, repeat until rules pass validation. + +**After all phases are complete, create or update the `firestore.rules` file.** + +### Critical Constraints + +1. **Never skip the devil's advocate phase** - this is your primary security + validation +2. **MUST include helper functions** for common operations ('isAuthenticated' + 'isOwner', 'uidUnchanged', 'uidNotModified') AND domain validators + ('isValidUser', etc.) +3. **MUST document assumed data models** at the beginning of the rules file +4. **Always validate the rules syntax** using 'firebase deploy --only + firestore:rules --dry-run' or a similar tool before outputting the final + file. +5. **Provide complete, runnable code** - no placeholders or TODOs +6. **Document all assumptions** about data structure or access patterns +7. **Always run the devil's advocate attack** after any modification of the + rules. +8. **Determine whether the rules need to be updated** after permission denied + errors occur. +9. **Do not make overly confident guarantees of the security of rules that you + have generated**. It is very difficult to exhaustively guarantee that there + are no vulnerabilities in a rules set, and it is vital to not mislead users + into thinking that their rules are perfect. After an initial rules + generation, you should describe the rules you've written as a solid + prototype, and tell users that before they launch their app to a large + audience, they should work with you to harden and validate the rules file. + Be clear that users should carefully review rules to ensure security. diff --git a/transformations/android-studio/skills/firebase-remote-config-basics/SKILL.md b/transformations/android-studio/skills/firebase-remote-config-basics/SKILL.md new file mode 100644 index 00000000..77f3eacb --- /dev/null +++ b/transformations/android-studio/skills/firebase-remote-config-basics/SKILL.md @@ -0,0 +1,76 @@ +--- +name: firebase-remote-config-basics +description: Comprehensive guide for Firebase Remote Config, including template management and SDK usage. Use this skill when the user needs help setting up Remote Config, managing feature flags, or updating app behavior dynamically. +compatibility: This skill is best used with the Firebase CLI, but does not require it. Firebase CLI can be accessed through `npx -y firebase-tools@latest`. +--- + +# Remote Config + +This skill provides a complete guide for getting started with Remote Config on Android. Remote Config allows you to change the behavior and appearance of your app without publishing an app update by maintaining a cloud-based configuration template. + +## Prerequisites + +Provisioning Remote Config requires both a Firebase project and an Android app. To manage the Remote Config template and conditions via the command line, use the Firebase CLI. See the `firebase-basics` skill for references on project initialization. + +## Troubleshooting Execution + +### Handling npx 403 Forbidden Errors +If `npx -y firebase-tools@latest` fails due to registry permissions (403 error): +1. **Inform the user**: "I am unable to fetch the latest Firebase tools via npx due to a registry error." +2. **Fallback**: Attempt to use the local `firebase` command directly if the user confirms it is installed globally (`npm install -g firebase-tools`). + +### Handling Project Context Issues +If a command fails because "no active project is selected": +1. **Check login**: Run `npx -y firebase-tools@latest login:list`. +2. **Prompt for ID**: If logged in but no project is active, ask the user: "Please provide your Firebase Project ID to proceed." +3. **Use Flag**: Append `--project ` to every subsequent command. + + +## SDK Setup + +To learn how to set up Remote Config in your application code, choose your platform: + +* **Android**: [android_setup.md](references/android_setup.md) + +## Best Practices and Template Management + +Follow these guidelines and use the associated CLI tools to ensure efficient and safe use of Remote Config. + +### Fetching Strategies +To optimize app performance and user experience, follow these recommended patterns (see [Loading Strategies](https://firebase.google.com/docs/remote-config/loading)): +* **Load new values for next startup**: The most effective pattern is to activate previously fetched values immediately on startup and fetch new values in the background to be used next time. This minimizes user wait time. +* **Real-time Updates**: Use the SDK's real-time listener to update the app instantly without a refresh when server-side configuration changes. + +### Template Management via CLI +Use the following commands to manage your Remote Config template and version history through the terminal: + +### Template Management via CLI +Use the following commands to manage your Remote Config template and version history through the terminal: + +* **Get current template**: Save the remote template to a local JSON file for auditing or modification. + ```bash + npx -y firebase-tools@latest remoteconfig:get -o remote_config.json + ``` +* **Autonomous Editing & Discovery** : Modify the local `remote_config.json` directly. Determine the correct signal (e.g., device.country or percent) and update the "conditions" array and "parameters" map accordingly. + +* **MANDATORY: User Review and Verification** : STOP and ask the user to verify your changes before proceeding to deployment. + * Action: Inform the user: "I have prepared the changes in remote_config.json. Please review the file for accuracy. Once you are satisfied, tell me to 'deploy' to make the changes live." +* **Deployment Orchestration** : To push changes, you must ensure the environment is configured for deployment. + * Config Mapping: If a firebase.json file is missing, create one to map the local JSON to the Remote Config service: + ```json + { "remoteconfig": { "template": "remote_config.json" } } + ``` + * Deploy: Execute the partial deployment command + ```bash + npx -y firebase-tools@latest deploy --only remoteconfig + ``` +* **Verification**: After deployment, verify the update by listing the version history. + ```bash + npx -y firebase-tools@latest remoteconfig:versions:list + ``` + +The SDK provides a number of features to make your application dynamic and responsive to user segments. + +* **Set In-App Defaults**: Define baseline values to ensure the app functions offline or before the first fetch. +* **Fetch and Activate**: Retrieve values from the Firebase backend and apply them to the local UI/Logic. +* **Template Management**: Use the Firebase CLI to version-control, get, and deploy your config JSON files. diff --git a/transformations/android-studio/skills/firebase-remote-config-basics/references/android_setup.md b/transformations/android-studio/skills/firebase-remote-config-basics/references/android_setup.md new file mode 100644 index 00000000..f0f59345 --- /dev/null +++ b/transformations/android-studio/skills/firebase-remote-config-basics/references/android_setup.md @@ -0,0 +1,101 @@ +# Firebase Remote Config Android Setup Guide + +Important references: + +- Refer to the `firebase-basics` skills, particularly those for project and app setup, before proceeding. + +## Project and App Setup + +Before you begin, ensure you have the following. If a `google-services.json` file is present, then use that Firebase project and app. Otherwise you may need to create them. + +- **Firebase CLI**: Installed and logged in (see `firebase-basics`). +- **Firebase Project**: Created via `npx -y firebase-tools@latest projects:create` (see `firebase-basics`). +- **Firebase App**: Created via `npx -y firebase-tools@latest apps:create ANDROID ` + +The `google-services.json` file must be present in the Android app's module directory. If missing, get the config using the Firebase CLI: `npx -y firebase-tools@latest apps:sdkconfig ANDROID `. + +## Add Dependencies to Gradle Build + +These changes are made to your Android project's Gradle files. Google Analytics is highly recommended as it enables conditional targeting based on user properties and audiences. + +### Project-level `build.gradle.kts` (`/build.gradle.kts`) + +Ensure the Google Services plugin is in the `plugins` block: + +```kotlin +plugins { + // ... other plugins + id("com.google.gms.google-services") version "4.4.0" apply false +} +``` + +### App-level `build.gradle.kts` (`//build.gradle.kts`) + +1. Add the Google Services plugin to the `plugins` block: + + ```kotlin + plugins { + // ... other plugins + id("com.google.gms.google-services") + } + ``` + +2. Add the Firebase Remote Config and Analytics dependencies. Using the Firebase Bill of Materials (BoM) is the best practice for version management. + + ```kotlin + dependencies { + // ... other dependencies + + // Import the Firebase BoM + implementation(platform("com.google.firebase:firebase-bom:32.7.0")) + + // Add the dependencies for Remote Config and Analytics + implementation("com.google.firebase:firebase-config-ktx") + implementation("com.google.firebase:firebase-analytics-ktx") + } + ``` + + +## Follow up Steps + +The following steps cover the essential patterns for using Remote Config effectively. + +### Set In-App Defaults +Define default values so your app has functional logic before it ever fetches a template from the server. Create an XML file (e.g., `res/xml/remote_config_defaults.xml`): + ```xml + + + + + welcome_message + Welcome to the app! + + + is_feature_enabled + false + + + ``` +Then, initialize the SDK in your Activity or Application class: + + ```kotlin + val remoteConfig = Firebase.remoteConfig + remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults) + ``` + + +### Fetch and Activate Values +To apply values from the cloud, you must fetch them and then activate them. + ```kotlin + remoteConfig.fetchAndActivate() + .addOnCompleteListener(this) { task -> + if (task.isSuccessful) { + val updated = task.result + println("Config params updated: $updated") + } else { + println("Fetch failed") + } + // Access a value + val message = remoteConfig.getString("welcome_message") + } + ``` diff --git a/transformations/android-studio/skills/firebase-security-rules-auditor/SKILL.md b/transformations/android-studio/skills/firebase-security-rules-auditor/SKILL.md new file mode 100644 index 00000000..2cfadc2f --- /dev/null +++ b/transformations/android-studio/skills/firebase-security-rules-auditor/SKILL.md @@ -0,0 +1,45 @@ +--- +name: firebase-security-rules-auditor +description: A skill to evaluate how secure Firestore security rules are. Use this when Firestore security rules are updated to ensure that the generated rules are extremely secure and robust. +--- + +# Overview +This skill acts as an auditor for Firebase Security Rules, evaluating them against a rigorous set of criteria to ensure they are secure, robust, and correctly implemented. + +# Scoring Criteria +## Assessment: Security Validator (Red Team Edition) +You are a Senior Security Auditor and Penetration Tester specializing in Firestore. Your goal is to find "the hole in the wall." Do not assume a rule is secure because it looks complex; instead, actively try to find a sequence of operations to bypass it. + +### Mandatory Audit Checklist: +1. **The Update Bypass:** Compare 'create' and 'update' rules. Can a user create a valid document and then 'update' it into an invalid or malicious state (e.g., changing their role, bypassing size limits, or corrupting data types)? +2. **Authority Source:** Does the security rely on user-provided data (request.resource.data) for sensitive fields like 'role', 'isAdmin', or 'ownerId'? Carefully consider the source for that authority. +3. **Business Logic vs. Rules:** Does the rule set actually support the app's purpose? (e.g., In a collaboration app, can collaborators actually read the data? If not, the rules are "broken" or will force insecure workarounds). +4. **Storage Abuse:** Are there string length or array size limits? If not, label it as a "Resource Exhaustion/DoS" risk. +5. **Type Safety:** Are fields checked with 'is string', 'is int', or 'is timestamp'? +6. **Field-Level vs. Identity-Level Security:** Be careful with rules that use \`hasOnly()\` or \`diff()\`. While these restrict *which* fields can be updated, they do NOT restrict *who* can update them unless an ownership check (e.g., \`resource.data.uid == request.auth.uid\`) is also present. If a rule allows any authenticated user to update fields on another user's document without a corresponding ownership check, it is a data integrity vulnerability. + +### Admin Bootstrapping & Privileges: +The admin bootstrapping process is limited in this app. If the rules use a single hardcoded admin email (e.g., checking request.auth.token.email == 'admin@example.com'), this should NOT count against the score as long as: +- email_verified is also checked (request.auth.token.email_verified == true). +- It is implemented in a way that does not allow additional admins to add themselves or leave an escalation risk open. + +### Scoring Criteria (1-5): +- **1 (Critical):** Unauthorized data access (leaks), privilege escalation, or total validation bypass. +- **2 (Major):** Broken business logic, self-assigned roles, bypass of controls. +- **3 (Moderate):** PII exposure (e.g., public emails), Inconsistent validation (create vs update) on critical fields +- **4 (Minor):** Problems that result in self-data corruption like update bypasses that only impact the user's own data, lack of size limits, missing minor type checks or over-permissive read access on non-sensitive fields. +- **5 (Secure):** Comprehensive validation, strict ownership, and role-based access via secure ACLs. + +Return your assessment in JSON format using the following structure: +{ + "score": 1-5 + "summary": "overall assessment" + "findings": [ + { + "check": "checklist item" + "severity": "critical|major|moderate|minor" + "issue": "description" + "recommendation": "fix" + } + ] +} \ No newline at end of file