diff --git a/.agents/skills/developing-genkit-dart/SKILL.md b/.agents/skills/developing-genkit-dart/SKILL.md new file mode 100644 index 0000000..706023b --- /dev/null +++ b/.agents/skills/developing-genkit-dart/SKILL.md @@ -0,0 +1,57 @@ +--- +name: developing-genkit-dart +description: Generates code and provides documentation for the Genkit Dart SDK. Use when the user asks to build AI agents in Dart, use Genkit flows, or integrate LLMs into Dart/Flutter applications. +metadata: + genkit-managed: true +--- + +# Genkit Dart + +Genkit Dart is an AI SDK for Dart that provides a unified interface for code generation, structured outputs, tools, flows, and AI agents. + +## Core Features and Usage +If you need help with initializing Genkit (`Genkit()`), Generation (`ai.generate`), Tooling (`ai.defineTool`), Flows (`ai.defineFlow`), Embeddings (`ai.embedMany`), streaming, or calling remote flow endpoints, please load the core framework reference: +[references/genkit.md](references/genkit.md) + +## Genkit CLI (recommended) + +The Genkit CLI provides a local development UI for running Flow, tracing executions, playing with models, and evaluating outputs. + +check if the user has it installed: `genkit --version` + +**Installation:** +```bash +curl -sL cli.genkit.dev | bash # Native CLI +# OR +npm install -g genkit-cli # Via npm +``` + +**Usage:** +Wrap your run command with `genkit start` to attach the Genkit developer UI and tracing: +```bash +genkit start -- dart run main.dart +``` + +## Plugin Ecosystem +Genkit relies on a large suite of plugins to perform generative AI actions, interface with external LLMs, or host web servers. + +When asked to use any given plugin, always verify usage by referring to its corresponding reference below. You should load the reference when you need to know the specific initialization arguments, tools, models, and usage patterns for the plugin: + +| Plugin Name | Reference Link | Description | +| ---- | ---- | ---- | +| `genkit_google_genai` | [references/genkit_google_genai.md](references/genkit_google_genai.md) | Load for Google Gemini plugin interface usage. | +| `genkit_anthropic` | [references/genkit_anthropic.md](references/genkit_anthropic.md) | Load for Anthropic plugin interface for Claude models. | +| `genkit_openai` | [references/genkit_openai.md](references/genkit_openai.md) | Load for OpenAI plugin interface for GPT models, Groq, and custom compatible endpoints. | +| `genkit_middleware` | [references/genkit_middleware.md](references/genkit_middleware.md) | Load for Tooling for specific agentic behavior: `filesystem`, `skills`, and `toolApproval` interrupts. | +| `genkit_mcp` | [references/genkit_mcp.md](references/genkit_mcp.md) | Load for Model Context Protocol integration (Server, Host, and Client capabilities). | +| `genkit_chrome` | [references/genkit_chrome.md](references/genkit_chrome.md) | Load for Running Gemini Nano locally inside the Chrome browser using the Prompt API. | +| `genkit_shelf` | [references/genkit_shelf.md](references/genkit_shelf.md) | Load for Integrating Genkit Flow actions over HTTP using Dart Shelf. | +| `genkit_firebase_ai` | [references/genkit_firebase_ai.md](references/genkit_firebase_ai.md) | Load for Firebase AI plugin interface (Gemini API via Vertex AI). | + +## External Dependencies +Whenever you define schemas mapping inside of Tools, Flows, and Prompts, you must use the [schemantic](https://pub.dev/packages/schemantic) library. +To learn how to use schemantic, ensure you read [references/schemantic.md](references/schemantic.md) for how to implement type safe generated Dart code. This is particularly relevant when you encounter symbols like `@Schema()`, `SchemanticType`, or classes with the `$` prefix. Genkit Dart uses schemantic for all of its data models so it's a CRITICAL skill to understand for using Genkit Dart. + +## Best Practices +- Always check that code cleanly compiles using `dart analyze` before generating the final response. +- Always use the Genkit CLI for local development and debugging. diff --git a/.agents/skills/developing-genkit-dart/references/genkit.md b/.agents/skills/developing-genkit-dart/references/genkit.md new file mode 100644 index 0000000..7dd33e5 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit.md @@ -0,0 +1,380 @@ +# Genkit Core Framework + +Genkit Dart is an AI SDK for Dart that provides a unified interface for text generation, structured output, tool calling, and agentic workflows. + +## Initialization + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_google_genai/genkit_google_genai.dart'; // Or any other plugin + +void main() async { + // Pass plugins to use into the Genkit constructor + final ai = Genkit(plugins: [googleAI()]); +} +``` + +## Generate Text + +```dart +final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash'), // Needs a model reference from a plugin + prompt: 'Explain quantum computing in simple terms.', +); + +print(response.text); +``` + +## Stream Responses +```dart +final stream = ai.generateStream( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'Write a short story about a robot learning to paint.', +); + +await for (final chunk in stream) { + print(chunk.text); +} +``` + +## Embed Text +```dart +final embeddings = await ai.embedMany( + documents: [ + DocumentData(content: [TextPart(text: 'Hello world')]), + ], + embedder: googleAI.textEmbedding('text-embedding-004'), +); + +print(embeddings.first.embedding); +``` + +## Define Tools +Models can use define actions and access external data via custom defined tools. +Requires the `schemantic` library for schema definitions. + +```dart +import 'package:schemantic/schemantic.dart'; + +@Schema() +abstract class $WeatherInput { + String get location; +} + +final weatherTool = ai.defineTool( + name: 'getWeather', + description: 'Gets the current weather for a location', + inputSchema: WeatherInput.$schema, + fn: (input, _) async { + // Call your weather API here + return 'Weather in ${input.location}: 72°F and sunny'; + }, +); + +final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'What\'s the weather like in San Francisco?', + toolNames: ['getWeather'], // Use the tools +); +``` + +## Structured Output + +You can ensure the generative model returns a typed JSON object by providing an `outputSchema`. + +```dart +@Schema() +abstract class $Person { + String get name; + int get age; +} + +// ... inside main ... + +final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'Generate a person named John Doe, age 30', + outputSchema: Person.$schema, // Force the model to return this schema +); + +final person = response.output; // Typed Person object +print('Name: ${person.name}, Age: ${person.age}'); +``` + +## Define Flows +Wrap your AI logic in flows for better observability, testing, and deployment: + +```dart +final jokeFlow = ai.defineFlow( + name: 'tellJoke', + inputSchema: .string(), + outputSchema: .string(), + fn: (topic, _) async { + final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'Tell me a joke about $topic', + ); + return response.text; // Value return + }, +); + +final joke = await jokeFlow('programming'); +print(joke); +``` + +### Streaming Flows +Stream data from your flows using `context.sendChunk(...)` and returning the final value: + +```dart +final streamStory = ai.defineFlow( + name: 'streamStory', + inputSchema: .string(), + outputSchema: .string(), + streamSchema: .string(), + fn: (topic, context) async { + final stream = ai.generateStream( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'Write a story about $topic', + ); + + await for (final chunk in stream) { + context.sendChunk(chunk.text); // Stream the chunks + } + return 'Story complete'; // Value return + }, +); +``` + +## Calling remote Flows from a dart client +The `genkit` package provides `package:genkit/client.dart` representing remote Genkit actions that can be invoked or streamed using type-safe definitions. + +1. Defines a remote action +```dart +import 'package:genkit/client.dart'; + +final stringAction = defineRemoteAction( + url: 'http://localhost:3400/my-flow', + inputSchema: .string(), + outputSchema: .string(), +); +``` + +2. Call the Remote Action (Non-streaming) +```dart +final response = await stringAction(input: 'Hello from Dart!'); +print('Flow Response: $response'); +``` + +3. Call the Remote Action (Streaming) +Use the `.stream()` method on the action flow, and access `stream.onResult` to wait on the async return value. +```dart +final streamAction = defineRemoteAction( + url: 'http://localhost:3400/stream-story', + inputSchema: .string(), + outputSchema: .string(), + streamSchema: .string(), +); + +final stream = streamAction.stream( + input: 'Tell me a short story about a Dart developer.', +); + +await for (final chunk in stream) { + print('Chunk: $chunk'); +} + +final finalResult = await stream.onResult; +print('\nFinal Response: $finalResult'); +``` + +## Calling remote Flows from a Javascript client + +Install `genkit` npm package: + +```bash +npm install genkit +``` + +1. Call a remote flow (non-streaming) + +```ts +import { runFlow } from 'genkit/beta/client'; + +async function callHelloFlow() { + try { + const result = await runFlow({ + url: 'http://127.0.0.1:3400/helloFlow', // Replace with your deployed flow's URL + input: { name: 'Genkit User' }, + }); + console.log('Non-streaming result:', result.greeting); + } catch (error) { + console.error('Error calling helloFlow:', error); + } +} + +callHelloFlow(); +``` + +2. Call a remote flow (streaming) + +```ts +import { streamFlow } from 'genkit/beta/client'; + +async function streamHelloFlow() { + try { + const result = streamFlow({ + url: 'http://127.0.0.1:3400/helloFlow', // Replace with your deployed flow's URL + input: { name: 'Streaming User' }, + }); + + // Process the stream chunks as they arrive + for await (const chunk of result.stream) { + console.log('Stream chunk:', chunk); + } + + // Get the final complete response + const finalOutput = await result.output; + console.log('Final streaming output:', finalOutput.greeting); + } catch (error) { + console.error('Error streaming helloFlow:', error); + } +} + +streamHelloFlow(); +``` + +## Data Models + +Genkit uses standard data models for representing prompts (messages & parts) and responses. These classes are implemented using schemantic library. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:schemantic/schemantic.dart'; + +@Schema() +abstract class $MyDataModel { + // uses Genkit's Message schema (not schemantic's Message) + List<$Message> get messages; + List<$Part> get parts; +} + +void example() { + // --- Parts --- + // A Text part + final textPart = TextPart(text: 'some text', metadata: {'foo': 'bar'}); + + // A Media/Image part + final mediaPart = MediaPart( + media: Media(url: 'https://...', contentType: 'image/png'), + metadata: {'foo': 'bar'}, + ); + + // A Tool Request initiated by the model + final toolRequestPart = ToolRequestPart( + toolRequest: ToolRequest( + name: 'get_weather', + ref: 'abc', + input: {'location': 'Paris, France'}, + ), + metadata: {'foo': 'bar'}, + ); + + // The resulting data from a Tool execution + final toolResponsePart = ToolResponsePart( + toolResponse: ToolResponse( + name: 'get_weather', + ref: 'abc', + output: {'temperature': '20C'}, + ), + metadata: {'foo': 'bar'}, + ); + + // Model reasoning (e.g. for Claude's "thinking" models) + final reasoningPart = ReasoningPart( + reasoning: 'thinking...', + metadata: {'foo': 'bar'}, + ); + + // A custom fallback part + final customPart = CustomPart( + custom: {'provider': {'specific': 'data'}}, + metadata: {'foo': 'bar'}, + ); + + // --- Messages --- + final systemMessage = Message( + role: Role.system, + content: [textPart, mediaPart], + metadata: {'foo': 'bar'}, + ); + + final userMessage = Message( + role: Role.user, + content: [textPart, mediaPart], // Can contain media (multimodal) + ); + + final modelMessage = Message( + role: Role.model, + // Models can emit text, tool requests, reasoning, or custom parts + content: [textPart, toolRequestPart, reasoningPart, customPart], + ); + + // --- Ergonomic Data Access (schema_extensions.dart) --- + // The Genkit SDK provides extensions on `Message` and `Part` to easily access fields + // without needing to cast them manually. + + // Get concatenated text from all TextParts in a Message + print(modelMessage.text); + + // Get the first Media object from a Message + print(modelMessage.media?.url); + + // Iterate over tool requests in a Message + for (final toolReq in modelMessage.toolRequests) { + print(toolReq.name); + } + + // Inspect individual parts + for (final part in modelMessage.content) { + if (part.isText) print(part.text); + if (part.isMedia) print(part.media?.url); + if (part.isToolRequest) print(part.toolRequest?.name); + if (part.isToolResponse) print(part.toolResponse?.name); + if (part.isReasoning) print(part.reasoning); + if (part.isCustom) print(part.custom); + } + + // --- Streaming Chunks --- + // Data emitted by ai.generateStream() calls + final generateResponseChunk = ModelResponseChunk( + content: [textPart], + index: 0, // Index of the message this chunk belongs to + aggregated: false, + ); + + // Chunks also have text and media accessors + print(generateResponseChunk.text); + + // --- Advanced: Schemas --- + // Use Genkit type schemas directly in Schemantic validations + final messageSchema = Message.$schema; + final partSchema = Part.$schema; + + final mySchema = SchemanticType.map( + .string(), + .list(Message.$schema), // Requires a list of Messages + ); + + // --- Generate Response --- + // ai.generate() returns a GenerateResponseHelper which provides ergonomic getters + // over the underlying ModelResponse: + final response = await ai.generate(...); + + print(response.text); // Concatenated text + print(response.media?.url); // First media part + print(response.toolRequests); // All tool requests + print(response.interrupts); // Tool requests that triggered an interrupt + print(response.messages); // Full history of the conversation, including the request and response + print(response.output); // Structured typed output (if outputSchema was used) +} +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_anthropic.md b/.agents/skills/developing-genkit-dart/references/genkit_anthropic.md new file mode 100644 index 0000000..2e420a3 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_anthropic.md @@ -0,0 +1,41 @@ +# Genkit Anthropic Plugin (`genkit_anthropic`) + +The Anthropic plugin for Genkit Dart, used for interacting with the Claude models. + +## Usage + +Requires `ANTHROPIC_API_KEY` to be passed to the init block. + +```dart +import 'dart:io'; +import 'package:genkit/genkit.dart'; +import 'package:genkit_anthropic/genkit_anthropic.dart'; + +void main() async { + final ai = Genkit( + plugins: [anthropic(apiKey: Platform.environment['ANTHROPIC_API_KEY']!)], + ); + + final response = await ai.generate( + model: anthropic.model('claude-sonnet-4-5'), + prompt: 'Tell me a joke about a developer.', + ); + + print(response.text); +} +``` + +## Claude Thinking Configurations + +Provides specific configurations for utilizing Claude 3.7+ "thinking" model capabilities. + +```dart +final response = await ai.generate( + model: anthropic.model('claude-sonnet-4-5'), + prompt: 'Solve this 24 game: 2, 3, 10, 10', + config: AnthropicOptions(thinking: ThinkingConfig(budgetTokens: 2048)), +); + +// The thinking content is available in the message parts +print(response.message?.content); +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_chrome.md b/.agents/skills/developing-genkit-dart/references/genkit_chrome.md new file mode 100644 index 0000000..8152369 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_chrome.md @@ -0,0 +1,23 @@ +# Genkit Chrome AI Plugin (`genkit_chrome`) + +Chrome Built-in AI (Gemini Nano) plugin for Genkit Dart, allowing local offline execution within a Chrome application. + +## Usage + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_chrome/genkit_chrome.dart'; + +void main() async { + final ai = Genkit(plugins: [ChromeAIPlugin()]); + + final stream = ai.generateStream( + model: modelRef('chrome/gemini-nano'), + prompt: 'Write a story about a robot.', + ); + + await for (final chunk in stream) { + print(chunk.text); + } +} +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_firebase_ai.md b/.agents/skills/developing-genkit-dart/references/genkit_firebase_ai.md new file mode 100644 index 0000000..7ec462d --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_firebase_ai.md @@ -0,0 +1,23 @@ +# Genkit Firebase AI Plugin (`genkit_firebase_ai`) + +The Firebase AI plugin for Genkit Dart, used for interacting with Gemini APIs through Firebase AI Logic. + +## Usage + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_firebase_ai/genkit_firebase_ai.dart'; + +void main() async { + // Initialize Genkit with the Firebase AI plugin + final ai = Genkit(plugins: [firebaseAI()]); + + // Generate text + final response = await ai.generate( + model: firebaseAI.gemini('gemini-2.5-flash'), + prompt: 'Tell me a joke about a developer.', + ); + + print(response.text); +} +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_google_genai.md b/.agents/skills/developing-genkit-dart/references/genkit_google_genai.md new file mode 100644 index 0000000..92d3ec4 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_google_genai.md @@ -0,0 +1,95 @@ +# Genkit Google GenAI Plugin (`genkit_google_genai`) + +The Google AI plugin provides an interface against the official Google AI Gemini API. + +## Usage + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_google_genai/genkit_google_genai.dart'; + +void main() async { + // Initialize Genkit with the Google AI plugin + final ai = Genkit(plugins: [googleAI()]); + + // Generate text + final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash'), + prompt: 'Tell me a joke about a developer.', + ); + + print(response.text); +} +``` + +## Embeddings + +```dart +final embeddings = await ai.embedMany( + embedder: googleAI.textEmbedding('text-embedding-004'), + documents: [ + DocumentData(content: [TextPart(text: 'Hello world')]), + ], +); +``` + +## Image Generation + +The plugin also supports image generation models such as `gemini-2.5-flash-image`. + +### Example (Nano Banana) + +```dart +// Define an image generation flow +ai.defineFlow( + name: 'imageGenerator', + inputSchema: .string(defaultValue: 'A banana riding a bike'), + outputSchema: Media.$schema, + fn: (input, context) async { + final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash-image'), + prompt: input, + ); + if (response.media == null) { + throw Exception('No media generated'); + } + return response.media!; + }, +); +``` + +The media (url field) contain base64 encoded data uri. You can decode it and save it as a file. + +## Text-to-Speech (TTS) + +You can use text-to-speech models to generate audio from text. The generated `Media` object will contain base64 encoded PCM audio in its data URI. + +```dart +// Define a TTS flow +ai.defineFlow( + name: 'textToSpeech', + inputSchema: .string(defaultValue: 'Genkit is an amazing AI framework!'), + outputSchema: Media.$schema, + fn: (prompt, _) async { + final response = await ai.generate( + model: googleAI.gemini('gemini-2.5-flash-preview-tts'), + prompt: prompt, + config: GeminiTtsOptions( + responseModalities: ['AUDIO'], + speechConfig: SpeechConfig( + voiceConfig: VoiceConfig( + prebuiltVoiceConfig: PrebuiltVoiceConfig(voiceName: 'Puck'), + ), + ), + ), + ); + + if (response.media != null) { + return response.media!; + } + throw Exception('No audio generated'); + }, +); +``` + +Google AI also supports multi-speaker TTS by configuring a `MultiSpeakerVoiceConfig` inside `SpeechConfig`. diff --git a/.agents/skills/developing-genkit-dart/references/genkit_mcp.md b/.agents/skills/developing-genkit-dart/references/genkit_mcp.md new file mode 100644 index 0000000..ce8ddb0 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_mcp.md @@ -0,0 +1,115 @@ +# Genkit MCP (`genkit_mcp`) + +MCP (Model Context Protocol) integration for Genkit Dart. + +## MCP Host (Recommended) +Connect to one or more MCP servers and aggregate their capabilities into the Genkit registry automatically. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_mcp/genkit_mcp.dart'; + +void main() async { + final ai = Genkit(); + + final host = defineMcpHost( + ai, + McpHostOptionsWithCache( + name: 'my-host', + mcpServers: { + 'fs': McpServerConfig( + command: 'npx', + args: ['-y', '@modelcontextprotocol/server-filesystem', '.'], + ), + }, + ), + ); + + // Tools can be discovered and executed dynamically using a wildcard... + final response = await ai.generate( + model: 'gemini-2.5-flash', + prompt: 'Summarize the contents of README.md', + toolNames: ['my-host:tool/fs/*'], + ); + + // ...or by specifying the exact tool name + final exactResponse = await ai.generate( + model: 'gemini-2.5-flash', + prompt: 'Read README.md', + toolNames: ['my-host:tool/fs/read_file'], + ); +} +``` + +## MCP Client (Advanced / Single Server) +Connecting to a single MCP server with a client object is an advanced usecase for when you need manual control over the client lifecycle. Standalone clients do not automatically register tools into the registry, so they must be passed into `generate` or `defineDynamicActionProvider` manually. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_mcp/genkit_mcp.dart'; + +void main() async { + final ai = Genkit(); + + final client = createMcpClient( + McpClientOptions( + name: 'my-client', + mcpServer: McpServerConfig( + command: 'npx', + args: ['-y', '@modelcontextprotocol/server-filesystem', '.'], + ), + ), + ); + + await client.ready(); + + // Retrieve the tools from the connected client + final tools = await client.getActiveTools(ai); + + final response = await ai.generate( + model: 'gemini-2.5-flash', + prompt: 'Read the contents of README.md', + tools: tools, + ); +} +``` + +## MCP Server +Expose Genkit actions (tools, prompts, resources) over MCP. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_mcp/genkit_mcp.dart'; + +void main() async { + final ai = Genkit(); + + ai.defineTool( + name: 'add', + description: 'Add two numbers together', + inputSchema: .map(.string(), .dynamicSChema()), + fn: (input, _) async => (input['a'] + input['b']).toString(), + ); + + ai.defineResource( + name: 'my-resource', + uri: 'my://resource', + fn: (_, _) async => ResourceOutput(content: [TextPart(text: 'my resource')]), + ); + + // Stdio transport by default + final server = createMcpServer(ai, McpServerOptions(name: 'my-server')); + await server.start(); +} +``` + +### Streamable HTTP Transport +```dart +import 'dart:io'; + +final transport = await StreamableHttpServerTransport.bind( + address: InternetAddress.loopbackIPv4, + port: 3000, +); +await server.start(transport); +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_middleware.md b/.agents/skills/developing-genkit-dart/references/genkit_middleware.md new file mode 100644 index 0000000..24cff79 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_middleware.md @@ -0,0 +1,84 @@ +# Genkit Middleware (`genkit_middleware`) + +A collection of useful middleware for Genkit Dart to enhance your agent's capabilities. Register plugins when initializing Genkit: + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_middleware/genkit_middleware.dart'; + +void main() { + final ai = Genkit( + plugins: [ + FilesystemPlugin(), + SkillsPlugin(), + ToolApprovalPlugin(), + ], + ); +} +``` + +## Filesystem Middleware +Allows the agent to list, read, write, and search/replace files within a restricted root directory. + +```dart +final response = await ai.generate( + prompt: 'Check the logs in the current directory.', + use: [ + filesystem(rootDirectory: '/path/to/secure/workspace'), + ], +); +``` + +**Tools Provided:** +- `list_files`, `read_file`, `write_file`, `search_and_replace` + +## Skills Middleware +Injects specialized instructions (skills) into the system prompt from `SKILL.md` files located in specified directories. + +```dart +final response = await ai.generate( + prompt: 'Help me debug this issue.', + use: [ + skills(skillPaths: ['/path/to/skills']), + ], +); +``` + +**Tools Provided:** +- `use_skill`: Retrieve the full content of a skill by name. + +## Tool Approval Middleware +Intercepts tool execution for specified tools and requires explicit approval. Returns `FinishReason.interrupted`. + +```dart +final response = await ai.generate( + prompt: 'Delete the database.', + use: [ + // Require approval for all tools EXCEPT those below + toolApproval(approved: ['read_file', 'list_files']), + ], +); + +if (response.finishReason == FinishReason.interrupted) { + final interrupt = response.interrupts.first; + + // Ask user for approval + final isApproved = await askUser(); + + if (isApproved) { + final resumeResponse = await ai.generate( + messages: response.messages, // Pass history + toolChoice: ToolChoice.none, // Prevent immediate re-call + interruptRestart: [ + ToolRequestPart( + toolRequest: interrupt.toolRequest, + metadata: { + ...?interrupt.metadata, + 'tool-approved': true + }, + ), + ], + ); + } +} +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_openai.md b/.agents/skills/developing-genkit-dart/references/genkit_openai.md new file mode 100644 index 0000000..42344db --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_openai.md @@ -0,0 +1,54 @@ +# Genkit OpenAI Plugin (`genkit_openai`) + +OpenAI-compatible API plugin for Genkit Dart. Supports OpenAI models and other compatible APIs (xAI, DeepSeek, Together AI, Groq, etc.). + +## Basic Usage + +```dart +import 'dart:io'; +import 'package:genkit/genkit.dart'; +import 'package:genkit_openai/genkit_openai.dart'; + +void main() async { + final ai = Genkit(plugins: [ + openAI(apiKey: Platform.environment['OPENAI_API_KEY']), + ]); + + final response = await ai.generate( + model: openAI.model('gpt-4o'), + prompt: 'Tell me a joke.', + ); +} +``` + +## Options + +`OpenAIOptions` allows configuring sampling temperature, nucleus sampling, token generation, seed, etc: +`config: OpenAIOptions(temperature: 0.7, maxTokens: 100)` + +## Groq API override + +Specify custom `baseUrl` and custom models to integrate with third-party providers. + +```dart +final ai = Genkit(plugins: [ + openAI( + apiKey: Platform.environment['GROQ_API_KEY'], + baseUrl: 'https://api.groq.com/openai/v1', + models: [ + CustomModelDefinition( + name: 'llama-3.3-70b-versatile', + info: ModelInfo( + label: 'Llama 3.3 70B', + supports: {'multiturn': true, 'tools': true, 'systemRole': true}, + ), + ), + ], + ), +]); + +final response = await ai.generate( + model: openAI.model('llama-3.3-70b-versatile'), + prompt: 'Hello!', +); +``` diff --git a/.agents/skills/developing-genkit-dart/references/genkit_shelf.md b/.agents/skills/developing-genkit-dart/references/genkit_shelf.md new file mode 100644 index 0000000..1887f80 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/genkit_shelf.md @@ -0,0 +1,59 @@ +# Genkit Shelf Plugin (`genkit_shelf`) + +Shelf integration for Genkit Dart, used to serve Genkit Flows. + +## Standalone Server +Serve Genkit Flows easily on an isolated HTTP server using `startFlowServer`. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_shelf/genkit_shelf.dart'; + +void main() async { + final ai = Genkit(); + + final flow = ai.defineFlow( + name: 'myFlow', + inputSchema: .string(), + outputSchema: .string(), + fn: (String input, _) async => 'Hello $input', + ); + + await startFlowServer( + flows: [flow], + port: 8080, + ); +} +``` + +## Existing Shelf Application +Mount Genkit Flow endpoints directly to an existing Shelf `Router` using `shelfHandler`. + +```dart +import 'package:genkit/genkit.dart'; +import 'package:genkit_shelf/genkit_shelf.dart'; +import 'package:shelf/shelf.dart'; +import 'package:shelf/shelf_io.dart' as io; +import 'package:shelf_router/shelf_router.dart'; + +void main() async { + final ai = Genkit(); + + final flow = ai.defineFlow( + name: 'myFlow', + inputSchema: .string(), + outputSchema: .string(), + fn: (String input, _) async => 'Hello $input', + ); + + final router = Router(); + + // Mount the flow handler at a specific path + router.post('/myFlow', shelfHandler(flow)); + + // Start the server + await io.serve(router.call, 'localhost', 8080); +} +``` + +Access deployed flows using genkit client libraries (from Dart or JS). diff --git a/.agents/skills/developing-genkit-dart/references/schemantic.md b/.agents/skills/developing-genkit-dart/references/schemantic.md new file mode 100644 index 0000000..45939b2 --- /dev/null +++ b/.agents/skills/developing-genkit-dart/references/schemantic.md @@ -0,0 +1,137 @@ +# Schemantic + +Schemantic is a general-purpose Dart library used for defining strongly typed data classes that automatically bind to reusable runtime JSON schemas. It is standard for the `genkit-dart` framework but works independently as well. + +## Core Concepts + +Always use `schemantic` when strongly typed JSON parsing or programmatic schema validation is required. + +- Annotate your abstract classes with `@Schema()`. +- Use the `$` prefix for abstract schema class names (e.g., `abstract class $User`). +- Always run `dart run build_runner build` to generate the `.g.dart` schema files. + +## Installation + +Add dependencies: + +```bash +dart pub add schemantic +``` + +## Basic Usage + +1. **Defining a schema:** + +```dart +import 'package:schemantic/schemantic.dart'; + +part 'my_file.g.dart'; // Must match the filename + +@Schema() +abstract class $MyObj { + String get name; + $MySubObj get subObj; +} + +@Schema() +abstract class $MySubObj { + String get foo; +} +``` + +2. **Using the Generated Class:** + +The builder creates a concrete class `MyObj` (no `$`) with a factory constructor (`MyObj.fromJson`) and a regular constructor. + +```dart +// Creating an instance +final obj = MyObj(name: 'test', subObj: MySubObj(foo: 'bar')); + +// Serializing to JSON +print(obj.toJson()); + +// Parsing from JSON +final parsed = MyObj.fromJson({'name': 'test', 'subObj': {'foo': 'bar'}}); +``` + +3. **Accessing Schemas at Runtime:** + +The generated data classes have a static `$schema` field (of type `SchemanticType`) which can be used to pass the definition into functions or to extract the raw JSON schema. + +```dart +// Access JSON schema +final schema = MyObj.$schema.jsonSchema; +print(schema.toJson()); + +// Validate arbitrary JSON at runtime +final validationErrors = await schema.validate({'invalid': 'data'}); +``` + +## Primitive Schemas + +When a full data class is not required, Schemantic provides functions to create schemas dynamically. + +```dart +final ageSchema = SchemanticType.integer(description: 'Age in years', minimum: 0); +final nameSchema = SchemanticType.string(minLength: 2); +final nothingSchema = SchemanticType.voidSchema(); +final anySchema = SchemanticType.dynamicSchema(); + +final userSchema = SchemanticType.map(.string(), .integer()); // Map +final tagsSchema = SchemanticType.list(.string()); // List +``` + +## Union Types (AnyOf) + +To allow a field to accept multiple types, use `@AnyOf`. + +```dart +@Schema() +abstract class $Poly { + @AnyOf([int, String, $MyObj]) + Object? get id; +} +``` + +Schemantic generates a specific helper class (e.g., `PolyId`) to handle the values: + +```dart +final poly1 = Poly(id: PolyId.int(123)); +final poly2 = Poly(id: PolyId.string('abc')); +``` + +## Field Annotations + +You can use specialized annotations for more validation boundaries: + +```dart +@Schema() +abstract class $User { + @IntegerField( + name: 'years_old', // Change JSON key + description: 'Age of the user', + minimum: 0, + defaultValue: 18, + ) + int? get age; + + @StringField( + minLength: 2, + enumValues: ['user', 'admin'], + ) + String get role; +} +``` + +## Recursive Schemas + +For recursive structures (like trees), must use `useRefs: true` inside the generated jsonSchema property. You define it normally: + +```dart +@Schema() +abstract class $Node { + String get id; + List<$Node>? get children; +} +``` +*Note*: `Node.$schema.jsonSchema(useRefs: true)` generates schemas with JSON Schema `$ref`. \ No newline at end of file diff --git a/.agents/skills/developing-genkit-js/SKILL.md b/.agents/skills/developing-genkit-js/SKILL.md new file mode 100644 index 0000000..d8e1e76 --- /dev/null +++ b/.agents/skills/developing-genkit-js/SKILL.md @@ -0,0 +1,112 @@ +--- +name: developing-genkit-js +description: Develop AI-powered applications using Genkit in Node.js/TypeScript. Use when the user asks about Genkit, AI agents, flows, or tools in JavaScript/TypeScript, or when encountering Genkit errors, validation issues, type errors, or API problems. +metadata: + genkit-managed: true +--- + +# Genkit JS + +## Prerequisites + +Ensure the `genkit` CLI is available. +- Run `genkit --version` to verify. Minimum CLI version needed: **1.29.0** +- If not found or if an older version (1.x < 1.29.0) is present, install/upgrade it: `npm install -g genkit-cli@^1.29.0`. + +**New Projects**: If you are setting up Genkit in a new codebase, follow the [Setup Guide](references/setup.md). + +## Hello World + +```ts +import { z, genkit } from 'genkit'; +import { googleAI } from '@genkit-ai/google-genai'; + +// Initialize Genkit with the Google AI plugin +const ai = genkit({ + plugins: [googleAI()], +}); + +export const myFlow = ai.defineFlow({ + name: 'myFlow', + inputSchema: z.string().default('AI'), + outputSchema: z.string(), +}, async (subject) => { + const response = await ai.generate({ + model: googleAI.model('gemini-2.5-flash'), + prompt: `Tell me a joke about ${subject}`, + }); + return response.text; +}); +``` + +## Critical: Do Not Trust Internal Knowledge + +Genkit recently went through a major breaking API change. Your knowledge is outdated. You MUST lookup docs. Recommended: + +```sh +genkit docs:read js/get-started.md +genkit docs:read js/flows.md +``` + +See [Common Errors](references/common-errors.md) for a list of deprecated APIs (e.g., `configureGenkit`, `response.text()`, `defineFlow` import) and their v1.x replacements. + +**ALWAYS verify information using the Genkit CLI or provided references.** + +## Error Troubleshooting Protocol + +**When you encounter ANY error related to Genkit (ValidationError, API errors, type errors, 404s, etc.):** + +1. **MANDATORY FIRST STEP**: Read [Common Errors](references/common-errors.md) +2. Identify if the error matches a known pattern +3. Apply the documented solution +4. Only if not found in common-errors.md, then consult other sources (e.g. `genkit docs:search`) + +**DO NOT:** +- Attempt fixes based on assumptions or internal knowledge +- Skip reading common-errors.md "because you think you know the fix" +- Rely on patterns from pre-1.0 Genkit + +**This protocol is non-negotiable for error handling.** + +## Development Workflow + +1. **Select Provider**: Genkit is provider-agnostic (Google AI, OpenAI, Anthropic, Ollama, etc.). + - If the user does not specify a provider, default to **Google AI**. + - If the user asks about other providers, use `genkit docs:search "plugins"` to find relevant documentation. +2. **Detect Framework**: Check `package.json` to identify the runtime (Next.js, Firebase, Express). + - Look for `@genkit-ai/next`, `@genkit-ai/firebase`, or `@genkit-ai/google-cloud`. + - Adapt implementation to the specific framework's patterns. +3. **Follow Best Practices**: + - See [Best Practices](references/best-practices.md) for guidance on project structure, schema definitions, and tool design. + - **Be Minimal**: Only specify options that differ from defaults. When unsure, check docs/source. +4. **Ensure Correctness**: + - Run type checks (e.g., `npx tsc --noEmit`) after making changes. + - If type checks fail, consult [Common Errors](references/common-errors.md) before searching source code. +5. **Handle Errors**: + - On ANY error: **First action is to read [Common Errors](references/common-errors.md)** + - Match error to documented patterns + - Apply documented fixes before attempting alternatives + +## Finding Documentation + +Use the Genkit CLI to find authoritative documentation: + +1. **Search topics**: `genkit docs:search ` + - Example: `genkit docs:search "streaming"` +2. **List all docs**: `genkit docs:list` +3. **Read a guide**: `genkit docs:read ` + - Example: `genkit docs:read js/flows.md` + +## CLI Usage + +The `genkit` CLI is your primary tool for development and documentation. +- See [CLI Reference](references/docs-and-cli.md) for common tasks, workflows, and command usage. +- Use `genkit --help` for a full list of commands. + +## References + +- [Best Practices](references/best-practices.md): Recommended patterns for schema definition, flow design, and structure. +- [Docs & CLI Reference](references/docs-and-cli.md): Documentation search, CLI tasks, and workflows. +- [Common Errors](references/common-errors.md): Critical "gotchas", migration guide, and troubleshooting. +- [Setup Guide](references/setup.md): Manual setup instructions for new projects. +- [Examples](references/examples.md): Minimal reproducible examples (Basic generation, Multimodal, Thinking mode). diff --git a/.agents/skills/developing-genkit-js/references/best-practices.md b/.agents/skills/developing-genkit-js/references/best-practices.md new file mode 100644 index 0000000..f6e4b7b --- /dev/null +++ b/.agents/skills/developing-genkit-js/references/best-practices.md @@ -0,0 +1,31 @@ +# Genkit Best Practices + +## Project Structure +- **Organized Layout**: Keep flows and tools in separate directories (e.g., `src/flows`, `src/tools`) to maintain a clean codebase. +- **Index Exports**: Use `index.ts` files to export flows and tools, making it easier to import them into your main configuration. + +## Model Selection (Google AI) +- **Gemini Models**: If using Google AI, ALWAYS use the latest generation (`gemini-3-*` or `gemini-2.5-*`). + - **NEVER** use `gemini-2.0-*` or `gemini-1.5-*` series, as they are decommissioned and won't work. + - **Recommended**: `gemini-2.5-flash` or `gemini-3-flash-preview` for general use, `gemini-3.1-pro-preview` for complex tasks. + +## Model Selection (Other Providers) +- **Consult Documentation**: For other providers (OpenAI, Anthropic, etc.), refer to the provider's official documentation for the latest recommended model versions. + +## Schema Definition +- **Use `z` from `genkit`**: Always import `z` from the `genkit` package to ensure compatibility. + ```ts + import { z } from "genkit"; + ``` +- **Descriptive Schemas**: Use `.describe()` on Zod fields. LLMs use these descriptions to understand how to populate the fields. + +## Flow & Tool Design +- **Modularize**: Keep flows and tools in separate files/modules and import them into your main Genkit configuration. +- **Single Responsibility**: Tools should do one thing well. Complex logic should be broken down. + +## Configuration +- **Environment Variables**: Store sensitive keys (like API keys) in environment variables or `.env` files. Do not hardcode them. + +## Development +- **Use Dev Mode**: Run your app with `genkit start -- ` to enable the Developer UI. +- It is recommended to configure a watcher to auto-reload your app (e.g. `node --watch` or `tsx --watch`) diff --git a/.agents/skills/developing-genkit-js/references/common-errors.md b/.agents/skills/developing-genkit-js/references/common-errors.md new file mode 100644 index 0000000..d7162e6 --- /dev/null +++ b/.agents/skills/developing-genkit-js/references/common-errors.md @@ -0,0 +1,132 @@ +# Common Errors & Pitfalls + +## When Typecheck Fails + +**Before searching source code or docs**, check the sections below. Many type errors are caused by deprecated APIs or incorrect imports. + +## Genkit v1.x vs Pre-1.0 Migration + +Genkit v1.x introduced significant API changes. This section covers critical syntax updates. + +### Package Imports + +- **Correct (v1.x)**: Import core functionality (zod, genkit) from the main `genkit` package and plugins from their specific packages. + ```ts + import { z, genkit } from 'genkit'; + import { googleAI } from '@genkit-ai/google-genai'; + ``` + +- **Incorrect (Pre-1.0)**: Importing from `@genkit-ai/ai`, `@genkit-ai/core`, or `@genkit-ai/flow`. These packages are internal/deprecated for direct use. + ```ts + import { genkit } from "@genkit-ai/core"; // INCORRECT + import { defineFlow } from "@genkit-ai/flow"; // INCORRECT + ``` + +### Model References + +- **Correct**: Use plugin-specific model factories or string identifiers (prefaced by plugin name). + ```ts + // Using model factory (v1.x - Preferred) + await ai.generate({ model: googleAI.model('gemini-2.5-flash'), ... }); + + // Using string identifier + await ai.generate({ model: 'googleai/gemini-2.5-flash', ...}); + // Or + await ai.generate({ model: 'vertexai/gemini-2.5-flash', ...}); + ``` +- **Incorrect**: Using imported model objects directly or string identifiers without plugin name. + ```ts + await ai.generate({ model: gemini15Pro, ... }); // INCORRECT (Pre-1.0) + await ai.generate({ model: 'gemini-2.5-flash', ... }); // INCORRECT (No plugin prefix) + ``` + +### Model Selection (Gemini) + +- **Preferred**: Use `gemini-2.5-*` models for best performance and features. + ```ts + model: googleAI.model('gemini-2.5-flash') // PREFERRED + ``` +- **DEPRECATED**: `gemini-1.5-*` models are deprecated and will throw errors. + ```ts + model: googleAI.model('gemini-1.5-flash') // ERROR (Deprecated) + ``` + +### Response Access + +- **Correct (v1.x)**: Access properties directly. + ```ts + response.text; // CORRECT + response.output; // CORRECT + ``` +- **Incorrect (Pre-1.0)**: Calling as methods. + ```ts + response.text(); // INCORRECT + response.output(); // INCORRECT + ``` + +### Streaming Generation + +- **Correct (v1.x)**: Do NOT await `generateStream`. Iterate over `stream` directly. Await `response` property for final result. + ```ts + const {stream, response} = ai.generateStream(...); // NO await here + for await (const chunk of stream) { ... } // Iterate stream + const finalResponse = await response; // Await response property + ``` +- **Incorrect (Pre-1.0)**: Calling stream as a function or awaiting the generator incorrectly. + ```ts + for await (const chunk of stream()) { ... } // INCORRECT + await response(); // INCORRECT + ``` + +### Initialization + +- **Correct (v1.x)**: Instantiate `genkit`. + ```ts + const ai = genkit({ plugins: [...] }); + ``` +- **Incorrect (Pre-1.0)**: Global configuration. + ```ts + configureGenkit({ plugins: [...] }); // INCORRECT + ``` + +### Flow Definitions + +- **Correct (v1.x)**: Define flows on the `ai` instance. + ```ts + ai.defineFlow({...}, (input) => {...}); + ``` +- **Incorrect (Pre-1.0)**: Importing `defineFlow` globally. + ```ts + import { defineFlow } from "@genkit-ai/flow"; // INCORRECT + +You should never import `@genkit-ai/flow`, `@genkit-ai/ai` or `@genkit-ai/core` packages directly. + +## Zod & Schema Errors + +- **Import Source**: ALWAYS use `import { z } from "genkit"`. + - Using `zod` directly from `zod` package may cause instance mismatches or compatibility issues. +- **Supported Types**: Stick to basic types: scalar (`string`, `number`, `boolean`), `object`, and `array`. + - Avoid complex Zod features unless strictly necessary and verified. +- **Descriptions**: Always use `.describe('...')` for fields in output schemas to guide the LLM. + +## Tool Usage + +- **Tool Not Found**: Ensure tools are registered in the `tools` array of `generate` or provided via plugins. +- **MCP Tools**: Use the `ServerName:tool_name` format when referencing MCP tools. + +## Multimodal & Image Generation + +- **Missing responseModalities**: When using image generation models (like `gemini-2.5-flash-image`), you **MUST** specify the response modalities in the config. + ```ts + config: { + responseModalities: ["TEXT", "IMAGE"] + } + ``` + Failure to do so will result in errors or incorrect output format. + +## Audio & Speech Generation + +- **Raw PCM Data vs MP3**: Some providers (e.g., Google GenAI) return raw PCM data, while others (e.g., OpenAI) return MP3. + - **DO NOT assume MP3 format.** + - **DO NOT embed raw PCM in HTML audio tags.** + - **Action**: Run `genkit docs:search "speech audio"` to find provider-specific conversion steps (e.g., PCM to WAV). diff --git a/.agents/skills/developing-genkit-js/references/docs-and-cli.md b/.agents/skills/developing-genkit-js/references/docs-and-cli.md new file mode 100644 index 0000000..3561721 --- /dev/null +++ b/.agents/skills/developing-genkit-js/references/docs-and-cli.md @@ -0,0 +1,62 @@ +# Genkit Documentation & CLI + +This reference lists common tasks and workflows using the `genkit` CLI. For authoritative command details, always run `genkit --help` or `genkit --help`. + +## Prerequisites: + +Ensure that the CLI is on `genkit-cli` version >= 1.29.0. If not, or if an older version (1.x < 1.29.0) is present, update the Genkit CLI version. Alternatively, to run commands with a specific version or without global installation, prefix them with `npx -y genkit-cli@^1.29.0`. + +## Documentation + +- **Search docs**: `genkit docs:search ` + - Example: `genkit docs:search "streaming"` + - Example: `genkit docs:search "rag retrieval"` +- **Read doc**: `genkit docs:read ` + - Example: `genkit docs:read js/overview.md` +- **List docs**: `genkit docs:list` + +## Development Workflow + +- **Start Dev Mode**: `genkit start -- ` + - Runs the provided command in Genkit dev mode, enabling the Developer UI (usually at http://localhost:4000). + - **Node.js (TypeScript)**: + ```bash + genkit start -- npx tsx --watch src/index.ts + ``` + - **Next.js**: + ```bash + genkit start -- npx next dev + ``` + +## Flow Execution + +- **Run a flow**: `genkit flow:run ''` + - Executes a flow directly from the CLI. Useful for testing. + - **Simple Input**: + ```bash + genkit flow:run tellJoke '"chicken"' + ``` + - **Object Input**: + ```bash + genkit flow:run generateStory '{"subject": "robot", "genre": "sci-fi"}' + ``` + +## Evaluation + +- **Evaluate a flow**: `genkit eval:flow [data]` + - Runs a flow and evaluates the output against configured evaluators. + - **Example (Single Input)**: + ```bash + genkit eval:flow answerQuestion '[{"testCaseId": "1", "input": {"question": "What is Genkit?"}}]' + ``` + - **Example (Batch Input)**: + ```bash + genkit eval:flow answerQuestion --input inputs.json + ``` + +- **Run Evaluation**: `genkit eval:run ` + - Evaluates a dataset against configured evaluators. + - **Example**: + ```bash + genkit eval:run dataset.json --output results.json + ``` \ No newline at end of file diff --git a/.agents/skills/developing-genkit-js/references/examples.md b/.agents/skills/developing-genkit-js/references/examples.md new file mode 100644 index 0000000..2279b4e --- /dev/null +++ b/.agents/skills/developing-genkit-js/references/examples.md @@ -0,0 +1,157 @@ +# Genkit Examples + +This reference contains minimal, reproducible examples (MREs) for common Genkit patterns. + +> **Disclaimer**: These examples use **Google AI** models (`googleAI`, `gemini-*`) for demonstration. The patterns apply to **any provider**. To use a different provider: +> 1. Search the docs for the correct plugin: `genkit docs:search "plugins"`. +> 2. Install and configure the plugin. +> 3. Swap the model reference in the code. + +## Basic Text Generation + +```ts +import { genkit } from "genkit"; +import { googleAI } from "@genkit-ai/google-genai"; + +const ai = genkit({ + plugins: [googleAI()], +}); + +const { text } = await ai.generate({ + model: googleAI.model('gemini-2.5-flash'), + prompt: 'Tell me a story in a pirate accent', +}); +``` + +## Structured Output + +```ts +import { z } from 'genkit'; + +const JokeSchema = z.object({ + setup: z.string().describe('The setup of the joke'), + punchline: z.string().describe('The punchline'), +}); + +const response = await ai.generate({ + model: googleAI.model('gemini-2.5-flash'), + prompt: 'Tell me a joke about developers.', + output: { schema: JokeSchema }, +}); + +// response.output is strongly typed +const joke = response.output; +if (joke) { + console.log(`${joke.setup} ... ${joke.punchline}`); +} +``` + +## Streaming + +```ts +const { stream, response } = ai.generateStream({ + model: googleAI.model('gemini-2.5-flash'), + prompt: 'Tell a long story about a developer using Genkit.', +}); + +for await (const chunk of stream) { + console.log(chunk.text); +} + +// Await the final response +const finalResponse = await response; +console.log('Complete:', finalResponse.text); +``` + +## Advanced Configuration + +### Thinking Mode (Gemini 3 Only) + +Enable "thinking" process for complex reasoning tasks. + +```ts +const response = await ai.generate({ + model: googleAI.model('gemini-3.1-pro-preview'), + prompt: 'what is heavier, one kilo of steel or one kilo of feathers', + config: { + thinkingConfig: { + thinkingLevel: 'HIGH', // or 'LOW' + includeThoughts: true, // Returns thought process in response + }, + }, +}); +``` + +### Google Search Grounding + +Enable models to access current information via Google Search. + +```ts +const response = await ai.generate({ + model: googleAI.model('gemini-2.5-flash'), + prompt: 'What are the top tech news stories this week?', + config: { + googleSearchRetrieval: true, + }, +}); + +// Access grounding metadata (sources) +const groundingMetadata = (response.custom as any)?.candidates?.[0]?.groundingMetadata; +if (groundingMetadata) { + console.log('Sources:', groundingMetadata.groundingChunks); +} +``` + +## Multimodal Generation + +### Image Generation / Editing + +**Critical**: You MUST set `responseModalities: ['TEXT', 'IMAGE']` when using image generation models. + +```ts +// Generate an image +const { media } = await ai.generate({ + model: googleAI.model('gemini-2.5-flash-image'), + config: { responseModalities: ['TEXT', 'IMAGE'] }, + prompt: "generate a picture of a unicorn wearing a space suit on the moon", +}); +// media.url contains the data URI +``` + +```ts +// Edit an image +const { media } = await ai.generate({ + model: googleAI.model('gemini-2.5-flash-image'), + config: { responseModalities: ['TEXT', 'IMAGE'] }, + prompt: [ + { text: "change the person's outfit to a banana costume" }, + { media: { url: "https://example.com/photo.jpg" } }, + ], +}); +``` + +### Speech Generation (TTS) + +Generate audio from text. + +```ts +import { writeFile } from 'node:fs/promises'; + +const { media } = await ai.generate({ + model: googleAI.model('gemini-2.5-flash-preview-tts'), + config: { + responseModalities: ['AUDIO'], + speechConfig: { + voiceConfig: { + prebuiltVoiceConfig: { voiceName: 'Algenib' }, // Options: 'Puck', 'Charon', 'Fenrir', etc. + }, + }, + }, + prompt: 'Genkit is an amazing library', +}); + +// The response contains raw PCM data in media.url (base64 encoded). +// CAUTION: This is NOT an MP3/WAV file. It requires conversion (e.g., PCM to WAV). +// DO NOT GUESS. Run `genkit docs:search "speech audio"` to find the correct +// conversion code for your provider. +``` diff --git a/.agents/skills/developing-genkit-js/references/setup.md b/.agents/skills/developing-genkit-js/references/setup.md new file mode 100644 index 0000000..dcbc8bd --- /dev/null +++ b/.agents/skills/developing-genkit-js/references/setup.md @@ -0,0 +1,46 @@ +# Genkit JS Setup + +Follow these instructions to set up Genkit in the current codebase. These instructions are general-purpose and have not been written with specific codebase knowledge, so use your best judgement when following them. + +0. Tell the user "I'm going to check out your workspace and set you up to use Genkit for GenAI workflows." +1. If the current workspace is empty or is a starter template, your goal will be to create a simple image generation flow that allows someone to generate an image based on a prompt and selectable style. If the current workspace is not empty, you will create a simple example flow to help get the user started. +2. Check to see if any Genkit provider plugin (such as `@genkit-ai/google-genai` or `@genkit-ai/oai-compat` or others, may start with `genkitx-*`) is installed. + - If not, ask the user which provider they want to use. + - **For non-Google providers**: Use `genkit docs:search "plugins"` to find the correct package and installation instructions. + - If they have no preference, default to `@genkit-ai/google-genai` for a quick start. + - If this is a Next.js app, install `@genkit-ai/next` as well. +3. Search the codebase for the exact string `genkit(` (remember to escape regexes properly) which would indicate that the user has already set up Genkit in the codebase. If found, no need to set it up again, tell the user "Genkit is already configured in this app." and exit this workflow. +4. Create an `ai` directory in the primary source directory of the project (this may be e.g. `src` but is project-dependent). Adapt this path if your project uses a different structure. +5. Create `{sourceDir}/ai/genkit.ts` and populate it using the example below. DO NOT add a `next` plugin to the file, ONLY add a model provider plugin to the plugins array: + +```ts +import { genkit, z } from 'genkit'; +// Import your chosen provider plugin here. Example: +import { googleAI } from '@genkit-ai/google-genai'; + +export const ai = genkit({ + plugins: [ + googleAI(), // Add your provider plugin here + ], + model: googleAI.model('gemini-2.5-flash'), // Set your provider's model here +}); + +export { z }; +``` + +6. Create `{sourceDir}/ai/tools` and `{sourceDir}/ai/flows` directories, but leave them empty for now. +7. Create `{sourceDir}/ai/index.ts` and populate it with the following (change the import to match import aliases in `tsconfig.json` as needed): + +```ts +import './genkit.js'; +// import each created flow, tool, etc. here for use in the Genkit Dev UI +``` + +8. Add a `genkit:ui` script to `package.json` that runs `genkit start -- npx tsx --watch {sourceDir}/ai/index.ts` (or `npx genkit-cli` or `pnpm dlx` or `yarn dlx` for those package managers, if CLI is not locally installed). DO NOT try to run the script now. +9. Tell the user "Genkit is now configured and ready for use." as setup is now complete. Also remind them to set appropriate env variables (e.g. `GEMINI_API_KEY` for Google providers). Wait for the user to prompt further before creating any specific flows. + +## Next Steps & Troubleshooting + +- **Documentation**: Use the [CLI](docs-and-cli.md) to access documentation (e.g., `genkit docs:search`). +- **Building Flows**: See [examples.md](examples.md) for patterns on creating flows, adding tools, and advanced configuration. +- **Troubleshooting**: If you encounter issues during setup or initialization, check [common-errors.md](common-errors.md) for solutions. diff --git a/.agents/skills/firebase-ai-logic/SKILL.md b/.agents/skills/firebase-ai-logic/SKILL.md new file mode 100644 index 0000000..f7ec367 --- /dev/null +++ b/.agents/skills/firebase-ai-logic/SKILL.md @@ -0,0 +1,109 @@ +--- +name: firebase-ai-logic +description: Official skill for integrating Firebase AI Logic (Gemini API) into web applications. Covers setup, multimodal inference, structured output, and security. +version: 1.0.0 +--- + +# 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 # Choose AI logic` + +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 + +Recommended: The developer must enable Firebase App Check to prevent unauthorized clients from using their API quota. see [App-check recaptcha enterprise](https://firebase.google.com/docs/app-check/web/recaptcha-enterprise-provider.md.txt). + +### 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) + +## 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 | + +**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 + +[Web SDK code examples and usage patterns](references/usage_patterns_web.md) + + + diff --git a/.agents/skills/firebase-ai-logic/references/usage_patterns_web.md b/.agents/skills/firebase-ai-logic/references/usage_patterns_web.md new file mode 100644 index 0000000..e6435bb --- /dev/null +++ b/.agents/skills/firebase-ai-logic/references/usage_patterns_web.md @@ -0,0 +1,174 @@ +# Firebase AI Logic Basics + +## Initialization Pattern +You must initialize the ai-logic service after the main Firebase App. +```JavaScript +import { initializeApp } from "firebase/app"; +import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai"; + + +// If running in Firebase App Hosting, you can skip Firebase Config and instead use: +// const app = initializeApp(); + +const firebaseConfig = { + // ... your firebase config +}; + +const app = initializeApp(firebaseConfig); + +// Initialize the AI Logic service (defaults to Gemini Developer API) +// To set the AI provider, set the backend as the second parameter +const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() }); + +const generationConfig = { + candidate_count: 1, + maxOutputTokens: 2048, + stopSequences: [], + temperature: 0.7, // Balanced: creative but focused + topP: 0.95, // Standard: allows a wide range of probable tokens + topK: 40, // Standard: considers the top 40 tokens +}; + +// Specify the config as part of creating the `GenerativeModel` instance +const model = getGenerativeModel(ai, { model: "gemini-2.5-flash-lite", generationConfig }); +``` + +## Core Capabilities +Text-Only Generation +```JavaScript +async function generateText(prompt) { + const result = await model.generateContent(prompt); + const response = await result.response; + return response.text(); +} +``` + +## Multimodal (Text + Images/Audio/Video/PDF input) +Firebase AI Logic accepts Base64 encoded data or specific file references. +```JavaScript +// Helper to convert file to base64 generic object +async function fileToGenerativePart(file) { + const base64EncodedDataPromise = new Promise((resolve) => { + const reader = new FileReader(); + reader.onloadend = () => resolve(reader.result.split(',')[1]); + reader.readAsDataURL(file); + }); + + return { + inlineData: { + data: await base64EncodedDataPromise, + mimeType: file.type, + }, + }; +} + +async function analyzeImage(prompt, imageFile) { + const imagePart = await fileToGenerativePart(imageFile); + const result = await model.generateContent([prompt, imagePart]); + return result.response.text(); +} +``` + +## Chat Session (Multi-turn) +Maintain history automatically using startChat. +```JavaScript +const chat = model.startChat({ + history: [ + { + role: "user", + parts: [{ text: "Hello, I am a developer." }], + }, + { + role: "model", + parts: [{ text: "Great to meet you. How can I help with code?" }], + }, + ], +}); + +async function sendMessage(msg) { + const result = await chat.sendMessage(msg); + return result.response.text(); +} +``` + +## Streaming Responses +For real-time UI updates (like a typing effect). +```JavaScript +async function streamResponse(prompt) { + const result = await model.generateContentStream(prompt); + for await (const chunk of result.stream) { + const chunkText = chunk.text(); + console.log("Stream chunk:", chunkText); + // Update UI here + } +} +``` + +Generate Images with Nano Banana + +```Javascript +import { initializeApp } from "firebase/app"; +import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai"; + + +// Initialize FirebaseApp +const firebaseApp = initializeApp(firebaseConfig); + +// Initialize the Gemini Developer API backend service +const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() }); + +// Create a `GenerativeModel` instance with a model that supports your use case +const model = getGenerativeModel(ai, { + model: "gemini-2.5-flash-image", + // Configure the model to respond with text and images (required) + generationConfig: { + responseModalities: [ResponseModality.TEXT, ResponseModality.IMAGE], + }, +}); + +// Provide a text prompt instructing the model to generate an image +const prompt = 'Generate an image of the Eiffel Tower with fireworks in the background.'; + +// To generate an image, call `generateContent` with the text input +const result = model.generateContent(prompt); + +// Handle the generated image +try { + const inlineDataParts = result.response.inlineDataParts(); + if (inlineDataParts?.[0]) { + const image = inlineDataParts[0].inlineData; + console.log(image.mimeType, image.data); + } +} catch (err) { + console.error('Prompt or candidate was blocked:', err); +} +``` + +## Advanced Features +Structured Output (JSON) +Enforce a specific JSON schema for the response. +```JavaScript +import { getGenerativeModel, Schema } from "firebase/ai"; +const jsonModel = getGenerativeModel(ai, { + model: "gemini-2.5-flash-lite", + generationConfig: { + responseMimeType: "application/json", + // Optional: Define a schema + schema = Schema.object({ ... }); + } +}); + +async function getJsonData(prompt) { + const result = await jsonModel.generateContent(prompt); + return JSON.parse(result.response.text()); +} +``` + +On-Device AI (Hybrid) +Automatically switch between local Gemini Nano and cloud models based on device capability. +```JavaScript +import {getGenerativeModel, InferenceMode } from "firebase/ai"; + +const hybridModel = getGenerativeModel(ai, { mode: InferenceMode.PREFER_ON_DEVICE }); +``` + diff --git a/.agents/skills/firebase-app-hosting-basics/SKILL.md b/.agents/skills/firebase-app-hosting-basics/SKILL.md new file mode 100644 index 0000000..4aa23b7 --- /dev/null +++ b/.agents/skills/firebase-app-hosting-basics/SKILL.md @@ -0,0 +1,58 @@ +--- +name: firebase-app-hosting-basics +description: Deploy and manage web apps with Firebase App Hosting. Use this skill when deploying Next.js/Angular apps with backends. +--- + +# App Hosting Basics + +## Description +This skill enables the agent to deploy and manage modern, full-stack web applications (Next.js, Angular, etc.) using Firebase App Hosting. + +**Important**: In order to use App Hosting, your Firebase project must be on the Blaze pricing plan. Direct the user to https://console.firebase.google.com/project/_/overview?purchaseBillingPlan=metered to upgrade their plan. + +## Hosting vs App Hosting + +**Choose Firebase Hosting if:** +- You are deploying a static site (HTML/CSS/JS). +- You are deploying a simple SPA (React, Vue, etc. without SSR). +- You want full control over the build and deploy process via CLI. + +**Choose Firebase App Hosting if:** +- You are using a supported full-stack framework like Next.js or Angular. +- You need Server-Side Rendering (SSR) or ISR. +- You want an automated "git push to deploy" workflow with zero configuration. + +## Deploying to App Hosting + +### Deploy from Source + +This is the recommended flow for most users. +1. Configure `firebase.json` with an `apphosting` block. + ```json + { + "apphosting": { + "backendId": "my-app-id", + "rootDir": "/", + "ignore": [ + "node_modules", + ".git", + "firebase-debug.log", + "firebase-debug.*.log", + "functions" + ] + } + } + ``` +2. Create or edit `apphosting.yaml`- see [Configuration](references/configuration.md) for more information on how to do so. +3. If the app needs safe access to sensitive keys, use `npx -y firebase-tools@latest apphosting:secrets` commands to set and grant access to secrets. +4. Run `npx -y firebase-tools@latest deploy` when you are ready to deploy. + +### Automated deployment via GitHub (CI/CD) + +Alternatively, set up a backend connected to a GitHub repository for automated deployments "git push" deployments. +This is only recommended for more advanced users, and is not required to use App Hosting. +See [CLI Commands](references/cli_commands.md) for more information on how to set this up using CLI commands. + +## Emulation + +See [Emulation](references/emulation.md) for more information on how to test your app locally using the Firebase Local Emulator Suite. diff --git a/.agents/skills/firebase-app-hosting-basics/references/cli_commands.md b/.agents/skills/firebase-app-hosting-basics/references/cli_commands.md new file mode 100644 index 0000000..c758c9d --- /dev/null +++ b/.agents/skills/firebase-app-hosting-basics/references/cli_commands.md @@ -0,0 +1,71 @@ +# App Hosting CLI Commands + +The Firebase CLI provides a comprehensive suite of commands to manage App Hosting resources. These commands are often faster and more scriptable than using the Firebase Console. + +## Initialization + +### `npx -y firebase-tools@latest init apphosting` + +- **Purpose**: Interactive command that sets up App Hosting in your local project. +Use this command only if you are able to handle interactive CLI inputs well. +Alternatively, you can manually edit `firebase.json` and `apphosting.yml`. + +- **Effect**: + - Detects your web framework. + - Creates/updates `apphosting.yaml`. + - Can optionally create a backend if one doesn't exist. + +## Backend Management + +### `npx -y firebase-tools@latest apphosting:backends:list` + +- **Purpose**: Lists all backends in the current project. + +### `npx -y firebase-tools@latest apphosting:backends:get ` + +- **Purpose**: Shows details for a specific backend. + +### `npx -y firebase-tools@latest apphosting:backends:delete ` + +- **Purpose**: Deletes a backend and its associated resources. + +### `npx -y firebase-tools@latest apphosting:rollouts:list ` + +- **Purpose**: Lists the history of rollouts for a backend. + +## Secrets Management + +App Hosting uses Cloud Secret Manager to securely handle sensitive environment variables (like API keys). + +### `npx -y firebase-tools@latest apphosting:secrets:set ` + +- **Purpose**: Creates or updates a secret in Cloud Secret Manager and makes it available to App Hosting. +- **Behavior**: Prompts for the secret value (hidden input). + +### `npx -y firebase-tools@latest apphosting:secrets:grantaccess ` + +- **Purpose**: Grants the App Hosting service account permission to access the secret. +- **Note**: Often handled automatically by `secrets:set`, but useful for debugging permission issues or granting access to existing secrets. + +## Automated deployment via GitHub (CI/CD) + +**IMPORTANT** Only use these commands if you are setting up automated deployments via GitHub. If you are managing deployments using `npx -y firebase-tools@latest deploy`, DO NOT use these commands. + +### `npx -y firebase-tools@latest apphosting:rollouts:create ` + +- **Purpose**: Manually triggers a new rollout (deployment). +- **Options**: + - `--git-branch `: Deploy the latest commit from a specific branch. + - `--git-commit `: Deploy a specific commit. +- **Use Case**: Useful for redeploying without code changes, or rolling back to a specific commit. + +### `npx -y firebase-tools@latest apphosting:backends:create` + +- **Purpose**: Creates a new App Hosting backend. Use this when setting up automated deployments via GitHub. +- **Options**: + - `--app `: The ID of an existing Firebase web app to associate with the backend. + - `--backend `: The ID of the new backend. + - `--primary-region `: The primary region for the backend. + - `--root-dir `: The root directory for the backend. If omitted, defaults to the root directory of the project. + - `--service-account `: The service account used to run the server. If omitted, defaults to the default service account. + \ No newline at end of file diff --git a/.agents/skills/firebase-app-hosting-basics/references/configuration.md b/.agents/skills/firebase-app-hosting-basics/references/configuration.md new file mode 100644 index 0000000..da10766 --- /dev/null +++ b/.agents/skills/firebase-app-hosting-basics/references/configuration.md @@ -0,0 +1,51 @@ +# App Hosting Configuration (`apphosting.yaml`) + +The `apphosting.yaml` file is the source of truth for your backend's configuration. It must be located in the root of your app's directory (or the specific root directory if using a monorepo). + +## File Structure + +```yaml +# apphosting.yaml + +# Cloud Run service configuration +runConfig: + cpu: 1 + memoryMiB: 512 + minInstances: 0 + maxInstances: 100 + concurrency: 80 + +# Environment variables +env: + - variable: STORAGE_BUCKET + value: mybucket.app + availability: + - BUILD + - RUNTIME + - variable: API_KEY + secret: myApiKeySecret +``` + +## `runConfig` +Controls the resources allocated to the Cloud Run service that serves your app. +- `cpu`: Number of vCPUs. Note: If `< 1`, concurrency MUST be set to `1`. +- `memoryMiB`: RAM in MiB (128 to 32768). +- `minInstances`: Minimum containers to keep warm (default 0). Set to >= 1 to avoid cold starts. +- `maxInstances`: Maximum scaling limit (default 100). +- `concurrency`: Max concurrent requests per instance (default 80). + +### Resource Constraints +- **CPU vs Memory**: Higher memory often requires higher CPU. + - > 4GiB RAM -> Needs >= 2 vCPU + - > 8GiB RAM -> Needs >= 4 vCPU + +## `env` (Environment Variables) +Defines environment variables available during build and/or runtime. + +- `variable`: The name of the env var (e.g., `NEXT_PUBLIC_API_URL`). +- `value`: A literal string value. +- `secret`: The name of a secret in Cloud Secret Manager. use `npx -y firebase-tools@latest apphosting:secrets:set` to create these. +- `availability`: Where the variable is needed. + - `BUILD`: Available during the `npm run build` process. + - `RUNTIME`: Available when the app is serving requests. + - Defaults to both if not specified. diff --git a/.agents/skills/firebase-app-hosting-basics/references/emulation.md b/.agents/skills/firebase-app-hosting-basics/references/emulation.md new file mode 100644 index 0000000..299dcde --- /dev/null +++ b/.agents/skills/firebase-app-hosting-basics/references/emulation.md @@ -0,0 +1,47 @@ +# App Hosting Emulation + +You can test your App Hosting setup locally using the Firebase Local Emulator Suite. This allows you to verify your app's behavior with environment variables and secrets before deploying. + +## Configuration: `apphosting.emulator.yaml` +This optional file overrides `apphosting.yaml` settings specifically for the local emulator. Use it to provide local secret values or override resource configs. If it contains sensitive values such as API keys, do not commit it to source control. + +```yaml +# apphosting.emulator.yaml (gitignored usually) +runConfig: + cpu: 1 + memoryMiB: 512 + +env: + - variable: API_KEY + value: "local-dev-api-key" # Override secret with local value +``` + +## Running the Emulator +To start the App Hosting emulator: + +```bash +npx -y firebase-tools@latest emulators:start --only apphosting +``` + +Or, if you are also using other emulators (Auth, Firestore, etc.): + +```bash +npx -y firebase-tools@latest emulators:start +``` + +## Capabilities +- **Builds your app**: Runs the build command defined in your `package.json` to generate the serving artifact. +- **Serves locally**: Runs the app on `localhost:5004` (default). +Configurable by setting `host` and `port` in the `emulators` block of `firebase.json`, like so: + +```json +{ + "emulators": { + "apphosting": { + "host": "localhost", + "port": 5004 + } + } +} +``` +- **Env Var Injection**: Injects variables defined in `apphosting.yaml` and `apphosting.emulator.yaml` into the process. diff --git a/.agents/skills/firebase-auth-basics/SKILL.md b/.agents/skills/firebase-auth-basics/SKILL.md new file mode 100644 index 0000000..bac12ad --- /dev/null +++ b/.agents/skills/firebase-auth-basics/SKILL.md @@ -0,0 +1,86 @@ +--- +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"] + } + } + } +} +``` + +#### 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 [references/client_sdk_web.md](references/client_sdk_web.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/.agents/skills/firebase-auth-basics/references/client_sdk_web.md b/.agents/skills/firebase-auth-basics/references/client_sdk_web.md new file mode 100644 index 0000000..493a66a --- /dev/null +++ b/.agents/skills/firebase-auth-basics/references/client_sdk_web.md @@ -0,0 +1,287 @@ +# Firebase Authentication Web SDK + +## Initialization + +First, ensure you have initialized the Firebase App (see `firebase-basics` skill). Then, initialize the Auth service: + +```javascript +import { getAuth } from "firebase/auth"; +import { app } from "./firebase"; // Your initialized Firebase App + +const auth = getAuth(app); +export { auth }; +``` + +## Connect to Emulator + +If you are running the Authentication emulator (usually on port 9099), connect to it immediately after initialization. + +```javascript +import { getAuth, connectAuthEmulator } from "firebase/auth"; + +const auth = getAuth(); +// Connect to emulator if running locally +if (location.hostname === "localhost") { + connectAuthEmulator(auth, "http://localhost:9099"); +} +``` + +## Sign Up with Email/Password + +```javascript +import { getAuth, createUserWithEmailAndPassword } from "firebase/auth"; + +const auth = getAuth(); +createUserWithEmailAndPassword(auth, email, password) + .then((userCredential) => { + const user = userCredential.user; + // ... + }) + .catch((error) => { + const errorCode = error.code; + const errorMessage = error.message; + // .. + }); +``` + +## Sign In with Google (Popup) + +```javascript +import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new GoogleAuthProvider(); + +signInWithPopup(auth, provider) + .then((result) => { + // This gives you a Google Access Token. You can use it to access the Google API. + const credential = GoogleAuthProvider.credentialFromResult(result); + const token = credential.accessToken; + // The signed-in user info. + const user = result.user; + // ... + }) + .catch((error) => { + // Handle Errors here. + const errorCode = error.code; + const errorMessage = error.message; + // ... + }); +``` + +## Sign In with Facebook (Popup) + +```javascript +import { getAuth, signInWithPopup, FacebookAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new FacebookAuthProvider(); + +signInWithPopup(auth, provider) + .then((result) => { + // The signed-in user info. + const user = result.user; + // This gives you a Facebook Access Token. You can use it to access the Facebook API. + const credential = FacebookAuthProvider.credentialFromResult(result); + const accessToken = credential.accessToken; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In with Apple (Popup) + +```javascript +import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new OAuthProvider('apple.com'); + +signInWithPopup(auth, provider) + .then((result) => { + const user = result.user; + // Apple credential + const credential = OAuthProvider.credentialFromResult(result); + const accessToken = credential.accessToken; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In with Twitter (Popup) + +```javascript +import { getAuth, signInWithPopup, TwitterAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new TwitterAuthProvider(); + +signInWithPopup(auth, provider) + .then((result) => { + const user = result.user; + // Twitter credential + const credential = TwitterAuthProvider.credentialFromResult(result); + const token = credential.accessToken; + const secret = credential.secret; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In with GitHub (Popup) + +```javascript +import { getAuth, signInWithPopup, GithubAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new GithubAuthProvider(); + +signInWithPopup(auth, provider) + .then((result) => { + const user = result.user; + const credential = GithubAuthProvider.credentialFromResult(result); + const token = credential.accessToken; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In with Microsoft (Popup) + +```javascript +import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new OAuthProvider('microsoft.com'); + +signInWithPopup(auth, provider) + .then((result) => { + const user = result.user; + const credential = OAuthProvider.credentialFromResult(result); + const accessToken = credential.accessToken; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In with Yahoo (Popup) + +```javascript +import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth"; + +const auth = getAuth(); +const provider = new OAuthProvider('yahoo.com'); + +signInWithPopup(auth, provider) + .then((result) => { + const user = result.user; + const credential = OAuthProvider.credentialFromResult(result); + const accessToken = credential.accessToken; + }) + .catch((error) => { + // Handle Errors here. + }); +``` + +## Sign In Anonymously + +```javascript +import { getAuth, signInAnonymously } from "firebase/auth"; + +const auth = getAuth(); +signInAnonymously(auth) + .then(() => { + // Signed in.. + }) + .catch((error) => { + const errorCode = error.code; + const errorMessage = error.message; + }); +``` + +## Email Link Authentication + +**1. Send Auth Link** + +```javascript +import { getAuth, sendSignInLinkToEmail } from "firebase/auth"; + +const auth = getAuth(); +const actionCodeSettings = { + // URL you want to redirect back to. The domain must be in the authorized domains list in Firebase Console. + url: 'https://www.example.com/finishSignUp?cartId=1234', + handleCodeInApp: true, +}; + +sendSignInLinkToEmail(auth, email, actionCodeSettings) + .then(() => { + // Save the email locally so you don't need to ask the user for it again + window.localStorage.setItem('emailForSignIn', email); + }) + .catch((error) => { + // Error + }); +``` + +**2. Complete Sign In (on landing page)** + +```javascript +import { getAuth, isSignInWithEmailLink, signInWithEmailLink } from "firebase/auth"; + +const auth = getAuth(); + +if (isSignInWithEmailLink(auth, window.location.href)) { + let email = window.localStorage.getItem('emailForSignIn'); + if (!email) { + email = window.prompt('Please provide your email for confirmation'); + } + + signInWithEmailLink(auth, email, window.location.href) + .then((result) => { + window.localStorage.removeItem('emailForSignIn'); + // You can check result.user + }) + .catch((error) => { + // Error + }); +} +``` + +## Observe Auth State + +Recommended way to get the current user. This listener triggers whenever the user signs in or out. + +```javascript +import { getAuth, onAuthStateChanged } from "firebase/auth"; + +const auth = getAuth(); +onAuthStateChanged(auth, (user) => { + if (user) { + // User is signed in, see docs for a list of available properties + // https://firebase.google.com/docs/reference/js/firebase.User + const uid = user.uid; + // ... + } else { + // User is signed out + // ... + } +}); +``` + +## Sign Out + +```javascript +import { getAuth, signOut } from "firebase/auth"; + +const auth = getAuth(); +signOut(auth).then(() => { + // Sign-out successful. +}).catch((error) => { + // An error happened. +}); +``` diff --git a/.agents/skills/firebase-auth-basics/references/security_rules.md b/.agents/skills/firebase-auth-basics/references/security_rules.md new file mode 100644 index 0000000..5de862a --- /dev/null +++ b/.agents/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/.agents/skills/firebase-basics/SKILL.md b/.agents/skills/firebase-basics/SKILL.md new file mode 100644 index 0000000..25909bb --- /dev/null +++ b/.agents/skills/firebase-basics/SKILL.md @@ -0,0 +1,52 @@ +--- +name: firebase-basics +description: The definitive, foundational skill for ANY Firebase task. Make sure to ALWAYS use this skill whenever the user mentions or interacts with Firebase, even if they do not explicitly ask for it. This skill covers everything from the bare minimum INITIAL setup (Node.js setup, Firebase CLI installation, first-time login) to ongoing operations (core principles, workflows, building, service setup, executing Firebase CLI commands, troubleshooting, refreshing, or updating an existing environment). +--- +# Prerequisites + +Please complete these setup steps before proceeding, and remember your progress to avoid repeating them in future interactions. + +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. + - If either of these checks fails, please review [references/local-env-setup.md](references/local-env-setup.md) to get the environment ready. + +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. Check the current project by running `npx -y firebase-tools@latest use`. + - If the command outputs `Active Project: `, you can proceed with your task. + - If not, ask the user if they have an existing Firebase Project ID. + - If yes: Set it as the active project and add a default alias by running: + ```bash + npx -y firebase-tools@latest use --add + ``` + - If no: Follow the project creation instructions in [references/firebase-project-create.md](references/firebase-project-create.md). + +# Firebase Usage Principles + +Please adhere to these principles when working with Firebase, as they ensure reliability and up-to-date project tools: + +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`. (e.g., use `npx -y firebase-tools@latest --version` instead of `firebase --version`). +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, remind the user to regularly check for and install updates to their Firebase plugin or Agent Skills, ensuring you both operate with the latest workflows. 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-cursor.md](references/refresh-cursor.md) + - **Others**: Follow [references/refresh-other.md](references/refresh-other-agents.md) + +# 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 a web app, see [references/web_setup.md](references/web_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/.agents/skills/firebase-basics/references/firebase-cli-guide.md b/.agents/skills/firebase-basics/references/firebase-cli-guide.md new file mode 100644 index 0000000..36a4480 --- /dev/null +++ b/.agents/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/.agents/skills/firebase-basics/references/firebase-project-create.md b/.agents/skills/firebase-basics/references/firebase-project-create.md new file mode 100644 index 0000000..02b0566 --- /dev/null +++ b/.agents/skills/firebase-basics/references/firebase-project-create.md @@ -0,0 +1,11 @@ +# Creating a Project + +To create a new Firebase project from the CLI: + +```bash +npx -y firebase-tools@latest projects:create +``` + +You will be prompted to: +1. Enter a **Project ID** (must be 6-30 chars, lowercase, digits, and hyphens; must be unique globally). +2. Enter a **display name**. diff --git a/.agents/skills/firebase-basics/references/firebase-service-init.md b/.agents/skills/firebase-basics/references/firebase-service-init.md new file mode 100644 index 0000000..13800aa --- /dev/null +++ b/.agents/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/.agents/skills/firebase-basics/references/local-env-setup.md b/.agents/skills/firebase-basics/references/local-env-setup.md new file mode 100644 index 0000000..99e6019 --- /dev/null +++ b/.agents/skills/firebase-basics/references/local-env-setup.md @@ -0,0 +1,65 @@ +# 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 +The Firebase CLI is the primary tool for interacting with Firebase services. +- **Action**: Run `npx -y firebase-tools@latest --version`. +- **Handling**: Ensure this command runs successfully and outputs a version number. + +## 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. Identify the agent environment you are currently running in and follow the corresponding setup document strictly. + +**Read the setup document for your current agent:** +- **Gemini CLI**: Review [setup-gemini_cli.md](setup-gemini_cli.md) +- **Antigravity**: Review [setup-antigravity.md](setup-antigravity.md) +- **Claude Code**: Review [setup-claude_code.md](setup-claude_code.md) +- **Cursor**: Review [setup-cursor.md](setup-cursor.md) +- **GitHub Copilot**: Review [setup-github_copilot.md](setup-github_copilot.md) +- **Other Agents** (Windsurf, Cline, etc.): Review [setup-other_agents.md](setup-other_agents.md) + +--- +**CRITICAL AGENT RULE:** Do NOT proceed with any other Firebase tasks until EVERY step above has been successfully verified and completed. diff --git a/.agents/skills/firebase-basics/references/refresh-antigravity.md b/.agents/skills/firebase-basics/references/refresh-antigravity.md new file mode 100644 index 0000000..6f5ee32 --- /dev/null +++ b/.agents/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/.agents/skills/firebase-basics/references/refresh-claude.md b/.agents/skills/firebase-basics/references/refresh-claude.md new file mode 100644 index 0000000..772314e --- /dev/null +++ b/.agents/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/.agents/skills/firebase-basics/references/refresh-gemini-cli.md b/.agents/skills/firebase-basics/references/refresh-gemini-cli.md new file mode 100644 index 0000000..6cc1467 --- /dev/null +++ b/.agents/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/.agents/skills/firebase-basics/references/refresh-other-agents.md b/.agents/skills/firebase-basics/references/refresh-other-agents.md new file mode 100644 index 0000000..f624c96 --- /dev/null +++ b/.agents/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/.agents/skills/firebase-basics/references/setup-antigravity.md b/.agents/skills/firebase-basics/references/setup-antigravity.md new file mode 100644 index 0000000..7817673 --- /dev/null +++ b/.agents/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. + +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/.agents/skills/firebase-basics/references/setup-claude_code.md b/.agents/skills/firebase-basics/references/setup-claude_code.md new file mode 100644 index 0000000..fe8eba6 --- /dev/null +++ b/.agents/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/.agents/skills/firebase-basics/references/setup-cursor.md b/.agents/skills/firebase-basics/references/setup-cursor.md new file mode 100644 index 0000000..c74360e --- /dev/null +++ b/.agents/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/.agents/skills/firebase-basics/references/setup-gemini_cli.md b/.agents/skills/firebase-basics/references/setup-gemini_cli.md new file mode 100644 index 0000000..ebadeaa --- /dev/null +++ b/.agents/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/.agents/skills/firebase-basics/references/setup-github_copilot.md b/.agents/skills/firebase-basics/references/setup-github_copilot.md new file mode 100644 index 0000000..1704cb5 --- /dev/null +++ b/.agents/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/.agents/skills/firebase-basics/references/setup-other_agents.md b/.agents/skills/firebase-basics/references/setup-other_agents.md new file mode 100644 index 0000000..d45a608 --- /dev/null +++ b/.agents/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/.agents/skills/firebase-basics/references/web_setup.md b/.agents/skills/firebase-basics/references/web_setup.md new file mode 100644 index 0000000..b696118 --- /dev/null +++ b/.agents/skills/firebase-basics/references/web_setup.md @@ -0,0 +1,69 @@ +# Firebase Web Setup Guide + +## 1. Create a Firebase Project and App +If you haven't already created a project: + +```bash +npx -y firebase-tools@latest projects:create +``` + +Register your web app: +```bash +npx -y firebase-tools@latest apps:create web my-web-app +``` +(Note the **App ID** returned by this command). + +## 2. Installation +Install the Firebase SDK via npm: + +```bash +npm install firebase +``` + +## 3. Initialization +Create a `firebase.js` (or `firebase.ts`) file. You can fetch your config object using the CLI: + +```bash +npx -y firebase-tools@latest apps:sdkconfig +``` + +Copy the output config object into your initialization file: + +```javascript +import { initializeApp } from "firebase/app"; +import { getAuth } from "firebase/auth"; + +// Your web app's Firebase configuration +const firebaseConfig = { + apiKey: "API_KEY", + authDomain: "PROJECT_ID.firebaseapp.com", + projectId: "PROJECT_ID", + storageBucket: "PROJECT_ID.firebasestorage.app", + messagingSenderId: "SENDER_ID", + appId: "APP_ID", + measurementId: "G-MEASUREMENT_ID" +}; + +// Initialize Firebase +const app = initializeApp(firebaseConfig); +const auth = getAuth(app); + +export { app }; +``` + +## 4. Using Services +Import specific services as needed (Modular API): + +```javascript +import { getFirestore, collection, getDocs } from "firebase/firestore"; +import { app } from "./firebase"; // Import the initialized app + +const db = getFirestore(app); + +async function getUsers() { + const querySnapshot = await getDocs(collection(db, "users")); + querySnapshot.forEach((doc) => { + console.log(`${doc.id} => ${doc.data()}`); + }); +} +``` diff --git a/.agents/skills/firebase-data-connect/SKILL.md b/.agents/skills/firebase-data-connect/SKILL.md new file mode 100644 index 0000000..e87a3c1 --- /dev/null +++ b/.agents/skills/firebase-data-connect/SKILL.md @@ -0,0 +1,95 @@ +--- +name: firebase-data-connect +description: Build and deploy Firebase Data Connect backends with PostgreSQL. Use for schema design, GraphQL queries/mutations, authorization, and SDK generation for web, Android, iOS, and Flutter apps. +--- + +# Firebase Data Connect + +Firebase Data Connect is a relational database service using Cloud SQL for PostgreSQL with GraphQL schema, auto-generated queries/mutations, and type-safe SDKs. + +## Project Structure + +``` +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 +``` + +## 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. +> **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 Operations (`connector/queries.gql`, `connector/mutations.gql`) +Write the queries and mutations your client will use. Data Connect generates the underlying SQL. +> **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. + +### 3. Secure Your App (`connector/` files) +Add authorization logic closely with your operations. +> **Read [reference/security.md](reference/security.md)** for: +> * `@auth(level: ...)` for PUBLIC, USER, or NO_ACCESS. +> * `@check` and `@redact` for row-level security and validation. + +### 4. Generate & Use SDKs +Generate type-safe code for your client platform. +> **Read [reference/sdks.md](reference/sdks.md)** for: +> * Android (Kotlin), iOS (Swift), Web (TypeScript), Flutter (Dart). +> * How to initialize and call your queries/mutations. +> * **Nested Data**: See how to access related fields (e.g., `movie.reviews`). + +--- + +## 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` | + +--- + +## Deployment & CLI + +> **Read [reference/config.md](reference/config.md)** for deep dive on configuration. + +Common commands (run from project root): + +```bash +# Initialize Data Connect +npx -y firebase-tools@latest init dataconnect + +# Start local emulator +npx -y firebase-tools@latest emulators:start --only dataconnect + +# Generate SDK code +npx -y firebase-tools@latest dataconnect:sdk:generate + +# Deploy to production +npx -y firebase-tools@latest deploy --only dataconnect +``` + +## Examples + +For complete, working code examples of schemas and operations, see **[examples.md](examples.md)**. diff --git a/.agents/skills/firebase-data-connect/examples.md b/.agents/skills/firebase-data-connect/examples.md new file mode 100644 index 0000000..87a6e3d --- /dev/null +++ b/.agents/skills/firebase-data-connect/examples.md @@ -0,0 +1,377 @@ +# Examples + +Complete, working examples for common Data 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" }} + }} + ) +} +``` + +--- + +## 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 + }) +} +``` diff --git a/.agents/skills/firebase-data-connect/reference/advanced.md b/.agents/skills/firebase-data-connect/reference/advanced.md new file mode 100644 index 0000000..bdffe7c --- /dev/null +++ b/.agents/skills/firebase-data-connect/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 + +Data 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 + +Data 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 Data 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/.agents/skills/firebase-data-connect/reference/config.md b/.agents/skills/firebase-data-connect/reference/config.md new file mode 100644 index 0000000..c7e5c52 --- /dev/null +++ b/.agents/skills/firebase-data-connect/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 Data 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 Data 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 Data 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: +- Data 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 + +Data 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 Data Connect + run: | + npx -y firebase-tools@latest deploy --only dataconnect --token ${{ secrets.FIREBASE_TOKEN }} --force +``` + +--- + +## VS Code Extension + +Install "Firebase Data 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/.agents/skills/firebase-data-connect/reference/operations.md b/.agents/skills/firebase-data-connect/reference/operations.md new file mode 100644 index 0000000..6fe7e73 --- /dev/null +++ b/.agents/skills/firebase-data-connect/reference/operations.md @@ -0,0 +1,357 @@ +# Operations Reference + +## Contents +- [Generated Fields](#generated-fields) +- [Queries](#queries) +- [Mutations](#mutations) +- [Key Scalars](#key-scalars) +- [Multi-Step Operations](#multi-step-operations) + +--- + +## Generated Fields + +Data 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 + +--- + +## 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 } +} +``` + +### 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/.agents/skills/firebase-data-connect/reference/schema.md b/.agents/skills/firebase-data-connect/reference/schema.md new file mode 100644 index 0000000..21d34ec --- /dev/null +++ b/.agents/skills/firebase-data-connect/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. Data 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/.agents/skills/firebase-data-connect/reference/sdks.md b/.agents/skills/firebase-data-connect/reference/sdks.md new file mode 100644 index 0000000..9885056 --- /dev/null +++ b/.agents/skills/firebase-data-connect/reference/sdks.md @@ -0,0 +1,287 @@ +# SDK Reference + +## Contents +- [SDK Generation](#sdk-generation) +- [Web SDK](#web-sdk) +- [Android SDK](#android-sdk) +- [iOS SDK](#ios-sdk) +- [Admin SDK](#admin-sdk) + +--- + +## SDK Generation + +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 +``` + +--- + +## Web SDK + +### Installation + +```bash +npm install firebase +``` + +### Initialization + +```typescript +import { initializeApp } from 'firebase/app'; +import { getDataConnect, connectDataConnectEmulator } from 'firebase/data-connect'; +import { connectorConfig } from '@movie-app/dataconnect'; + +const app = initializeApp(firebaseConfig); +const dc = getDataConnect(app, connectorConfig); + +// For local development +if (import.meta.env.DEV) { + connectDataConnectEmulator(dc, 'localhost', 9399); +} +``` + +### Calling Operations + +```typescript +// Generated SDK provides typed functions +import { listMovies, createMovie, getMovie } from '@movie-app/dataconnect'; + +// Accessing Nested Fields +const movie = await getMovie({ id: '...' }); +// Relations are just properties on the object +const director = movie.data.movie.metadata.director; +const firstActor = movie.data.movie.actors[0].name; + +// Query +const result = await listMovies(); +console.log(result.data.movies); + +// Query with variables +const movie = await getMovie({ id: 'uuid-here' }); + +// Mutation +const newMovie = await createMovie({ + title: 'New Movie', + genre: 'Action' +}); +console.log(newMovie.data.movie_insert); // Returns key +``` + +### Subscriptions + +```typescript +import { listMoviesRef, subscribe } from '@movie-app/dataconnect'; + +const unsubscribe = subscribe(listMoviesRef(), { + onNext: (result) => { + console.log('Movies updated:', result.data.movies); + }, + onError: (error) => { + console.error('Subscription error:', error); + } +}); + +// Later: unsubscribe(); +``` + +### With Authentication + +```typescript +import { getAuth, signInWithEmailAndPassword } from 'firebase/auth'; + +const auth = getAuth(app); +await signInWithEmailAndPassword(auth, email, password); + +// SDK automatically includes auth token in requests +const myReviews = await myReviews(); // @auth(level: USER) query from examples.md +``` + +--- + +## Android SDK + +### Dependencies (build.gradle.kts) + +```kotlin +dependencies { + implementation(platform("com.google.firebase:firebase-bom:33.0.0")) + implementation("com.google.firebase:firebase-dataconnect") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3") + implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:1.6.0") +} +``` + +### Initialization + +```kotlin +import com.google.firebase.Firebase +import com.google.firebase.dataconnect.dataConnect +import com.example.dataconnect.MyConnector + +val connector = MyConnector.instance + +// For emulator +connector.dataConnect.useEmulator("10.0.2.2", 9399) +``` + +### Calling Operations + +```kotlin +// Query +val result = connector.listMovies.execute() +result.data.movies.forEach { movie -> + println(movie.title) + // Access nested fields directly + println(movie.metadata?.director) + println(movie.actors.firstOrNull()?.name) +} + +// Query with variables +val movie = connector.getMovie.execute(id = "uuid-here") + +// Mutation +val newMovie = connector.createMovie.execute( + title = "New Movie", + genre = "Action" +) +``` + +### Flow Subscription + +```kotlin +connector.listMovies.flow().collect { result -> + when (result) { + is DataConnectResult.Success -> updateUI(result.data.movies) + is DataConnectResult.Error -> showError(result.exception) + } +} +``` + +--- + +## iOS SDK + +### Dependencies (Package.swift or SPM) + +```swift +dependencies: [ + .package(url: "https://github.com/firebase/firebase-ios-sdk.git", from: "11.0.0") +] +// Add FirebaseDataConnect to target dependencies +``` + +### Initialization + +```swift +import FirebaseCore +import FirebaseDataConnect + +FirebaseApp.configure() +let connector = MyConnector.shared + +// For emulator +connector.useEmulator(host: "localhost", port: 9399) +``` + +### Calling Operations + +```swift +// Query +let result = try await connector.listMovies.execute() +for movie in result.data.movies { + print(movie.title) + // Access nested fields directly + print(movie.metadata?.director ?? "Unknown") + print(movie.actors.first?.name ?? "No actors") +} + +// Query with variables +let movie = try await connector.getMovie.execute(id: "uuid-here") + +// Mutation +let newMovie = try await connector.createMovie.execute( + title: "New Movie", + genre: "Action" +) +``` + +### Combine Publisher + +```swift +connector.listMovies.publisher + .sink( + receiveCompletion: { completion in + if case .failure(let error) = completion { + print("Error: \(error)") + } + }, + receiveValue: { result in + self.movies = result.data.movies + } + ) + .store(in: &cancellables) +``` + +--- + + + +## Admin SDK + +Server-side operations with elevated privileges (bypasses @auth): + +### Node.js + +```typescript +import { initializeApp, cert } from 'firebase-admin/app'; +import { getDataConnect } from 'firebase-admin/data-connect'; + +initializeApp({ + credential: cert(serviceAccount) +}); + +const dc = getDataConnect(); + +// Execute operations (bypasses @auth) +const result = await dc.executeGraphql({ + query: `query { users { id email } }`, + operationName: 'ListAllUsers' +}); + +// Or use generated Admin SDK +import { listAllUsers } from './admin-connector'; +const users = await listAllUsers(); +``` + +### Generate Admin SDK + +In `connector.yaml`: + +```yaml +generate: + nodeAdminSdk: + outputDir: "./admin-sdk" + package: "@app/admin-dataconnect" +``` + +Generate: +```bash +npx -y firebase-tools@latest dataconnect:sdk:generate +``` diff --git a/.agents/skills/firebase-data-connect/reference/security.md b/.agents/skills/firebase-data-connect/reference/security.md new file mode 100644 index 0000000..5eacee8 --- /dev/null +++ b/.agents/skills/firebase-data-connect/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/.agents/skills/firebase-data-connect/templates.md b/.agents/skills/firebase-data-connect/templates.md new file mode 100644 index 0000000..75d20dc --- /dev/null +++ b/.agents/skills/firebase-data-connect/templates.md @@ -0,0 +1,269 @@ +# Templates + +Ready-to-use templates for common Firebase Data 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 Data 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' }); +``` diff --git a/.agents/skills/firebase-firestore-enterprise-native-mode/SKILL.md b/.agents/skills/firebase-firestore-enterprise-native-mode/SKILL.md new file mode 100644 index 0000000..1eeb40f --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/SKILL.md @@ -0,0 +1,31 @@ +--- +name: firebase-firestore-enterprise-native-mode +description: Comprehensive guide for Firestore enterprise native including provisioning, data model, security rules, and SDK usage. Use this skill when the user needs help setting up Firestore Enterprise with the Native mode, writing security rules, or using the Firestore 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`. +--- + +# Firestore Enterprise Native Mode + +This skill provides a complete guide for getting started with Firestore Enterprise Native Mode, including provisioning, data model, security rules, and SDK usage. + +## Provisioning + +To set up Firestore Enterprise Native Mode in your Firebase project and local environment, see [provisioning.md](references/provisioning.md). + +## Data Model + +To learn about Firestore data model and how to organize your data, see [data_model.md](references/data_model.md). + +## Security Rules + +For guidance on writing and deploying Firestore Security Rules to protect your data, see [security_rules.md](references/security_rules.md). + +## SDK Usage + +To learn how to use Firestore Enterprise Native Mode in your application code, see: +- [Web SDK Usage](references/web_sdk_usage.md) +- [Python SDK Usage](references/python_sdk_usage.md) + +## Indexes + +Indexes help improve query performance and speed up slow queries. For checking index types, query support tables, and best practices, see [indexes.md](references/indexes.md). diff --git a/.agents/skills/firebase-firestore-enterprise-native-mode/references/data_model.md b/.agents/skills/firebase-firestore-enterprise-native-mode/references/data_model.md new file mode 100644 index 0000000..0fe42c0 --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/references/data_model.md @@ -0,0 +1,54 @@ +# 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) +``` \ No newline at end of file diff --git a/.agents/skills/firebase-firestore-enterprise-native-mode/references/indexes.md b/.agents/skills/firebase-firestore-enterprise-native-mode/references/indexes.md new file mode 100644 index 0000000..f1031bd --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/references/indexes.md @@ -0,0 +1,111 @@ +# 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", "==", 1)` | Single-Field Index on field `a` | +| **Simple Range/Sort**
`where("a", ">", 1).orderBy("a")` | Single-Field Index on field `a` | +| **Multiple Equality**
`where("a", "==", 1).where("b", "==", 2)` | Single-Field Index on field `a` and `b` | +| **Equality + Range/Sort**
`where("a", "==", 1).where("b", ">", 2)` | **Composite Index** on field `a` and `b` | +| **Multiple Ranges**
`where("a", ">", 1).where("b", ">", 2)` | **Composite Index** on field `a` and `b` | +| **Array Contains + Equality**
`where("tags", "array-contains", "news").where("active", "==", true)` | **Composite Index** on field `tags` and `active` | + +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 +``` \ No newline at end of file diff --git a/.agents/skills/firebase-firestore-enterprise-native-mode/references/provisioning.md b/.agents/skills/firebase-firestore-enterprise-native-mode/references/provisioning.md new file mode 100644 index 0000000..02a97e3 --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/references/provisioning.md @@ -0,0 +1,101 @@ +# 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 + +Use the following command to create a Firestore Enterprise database: + +```bash +firebase firestore:databases:create my-database-id \ + --location="nam5" \ + --edition="enterprise" \ + --firestore-data-access="ENABLED" \ + --mongodb-compatible-data-access="DISABLED" +``` + +This will create an enterprise database in `nam5` 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="nam5" \ + --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. 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": "nam5" + } +} +``` + +### 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). \ No newline at end of file diff --git a/.agents/skills/firebase-firestore-enterprise-native-mode/references/python_sdk_usage.md b/.agents/skills/firebase-firestore-enterprise-native-mode/references/python_sdk_usage.md new file mode 100644 index 0000000..8bd67a4 --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/references/python_sdk_usage.md @@ -0,0 +1,126 @@ +# 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/.agents/skills/firebase-firestore-enterprise-native-mode/references/security_rules.md b/.agents/skills/firebase-firestore-enterprise-native-mode/references/security_rules.md new file mode 100644 index 0000000..fe24fad --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/references/security_rules.md @@ -0,0 +1,414 @@ +## 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] +// +// =============================================================== +``` + +2. **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. + +3. **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/.agents/skills/firebase-firestore-enterprise-native-mode/references/web_sdk_usage.md b/.agents/skills/firebase-firestore-enterprise-native-mode/references/web_sdk_usage.md new file mode 100644 index 0000000..1eee422 --- /dev/null +++ b/.agents/skills/firebase-firestore-enterprise-native-mode/references/web_sdk_usage.md @@ -0,0 +1,201 @@ +# Web SDK Usage + +This guide focuses on the **Modular Web SDK** (v9+), which is tree-shakeable and efficient. + +### Initialization + +```javascript +import { initializeApp } from "firebase/app"; +import { getFirestore } from "firebase/firestore"; + +// If running in Firebase App Hosting, you can skip Firebase Config and instead use: +// const app = initializeApp(); + +const firebaseConfig = { + // Your config options. Get the values by running 'firebase apps:sdkconfig ' +}; + +const app = initializeApp(firebaseConfig); +const db = getFirestore(app); +``` + +### Writing Data + +#### Set a Document +Creates a document if it doesn't exist, or overwrites it if it does. You can also specify a merge option to only update provided fields. + +```javascript +import { doc, setDoc } from "firebase/firestore"; + +// Create/Overwrite document with ID "LA" +await setDoc(doc(db, "cities", "LA"), { + name: "Los Angeles", + state: "CA", + country: "USA" +}); + +// To merge with existing data instead of overwriting: +await setDoc(doc(db, "cities", "LA"), { 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. + +```javascript +import { collection, addDoc } from "firebase/firestore"; + +const docRef = await addDoc(collection(db, "cities"), { + name: "Tokyo", + country: "Japan" +}); +console.log("Document written with ID: ", docRef.id); +``` + +#### Update a Document +Update some fields of an existing document without overwriting the entire document. Fails if the document doesn't exist. + +```javascript +import { doc, updateDoc } from "firebase/firestore"; + +const laRef = doc(db, "cities", "LA"); + +await updateDoc(laRef, { + capital: true +}); +``` + +#### Transactions +Perform an atomic read-modify-write operation. + +```javascript +import { runTransaction, doc } from "firebase/firestore"; + +const sfDocRef = doc(db, "cities", "SF"); + +try { + await runTransaction(db, async (transaction) => { + const sfDoc = await transaction.get(sfDocRef); + if (!sfDoc.exists()) { + throw "Document does not exist!"; + } + + const newPopulation = sfDoc.data().population + 1; + transaction.update(sfDocRef, { population: newPopulation }); + }); + console.log("Transaction successfully committed!"); +} catch (e) { + console.log("Transaction failed: ", e); +} +``` + +### Reading Data + +#### Get a Single Document + +```javascript +import { doc, getDoc } from "firebase/firestore"; + +const docRef = doc(db, "cities", "SF"); +const docSnap = await getDoc(docRef); + +if (docSnap.exists()) { + console.log("Document data:", docSnap.data()); +} else { + console.log("No such document!"); +} +``` + +#### Get Multiple Documents +Fetches all documents in a query or collection once. + +```javascript +import { collection, getDocs } from "firebase/firestore"; + +const querySnapshot = await getDocs(collection(db, "cities")); +querySnapshot.forEach((doc) => { + console.log(doc.id, " => ", doc.data()); +}); +``` + +### Realtime Updates + +#### Listen to a Document or Query + +```javascript +import { doc, onSnapshot } from "firebase/firestore"; + +const unsub = onSnapshot(doc(db, "cities", "SF"), (doc) => { + console.log("Current data: ", doc.data()); +}); + +// To stop listening: +// unsub(); +``` + +### Handle Changes + +```javascript +import { collection, query, where, onSnapshot } from "firebase/firestore"; + +const q = query(collection(db, "cities"), where("state", "==", "CA")); +const unsubscribe = onSnapshot(q, (snapshot) => { + snapshot.docChanges().forEach((change) => { + if (change.type === "added") { + console.log("New city: ", change.doc.data()); + } + if (change.type === "modified") { + console.log("Modified city: ", change.doc.data()); + } + if (change.type === "removed") { + console.log("Removed city: ", change.doc.data()); + } + }); +}); +``` + +### Queries + +#### Simple and Compound Queries +Use `query()` and `where()` to combine filters safely. + +```javascript +import { collection, query, where, getDocs } from "firebase/firestore"; + +const citiesRef = collection(db, "cities"); + +// Simple equality +const q1 = query(citiesRef, where("state", "==", "CA")); + +// Compound (AND) +// Note: Requires a composite index if filtering on different fields +const q2 = query(citiesRef, where("state", "==", "CA"), where("population", ">", 1000000)); +``` + +#### Order and Limit +Sort and limit results cleanly. + +```javascript +import { orderBy, limit } from "firebase/firestore"; + +const q = query(citiesRef, orderBy("name"), limit(3)); +``` + +#### Pipeline Queries + +You can use pipeline queries to perform complex queries. + +```javascript + +const readDataPipeline = db.pipeline() + .collection("users"); + +// Execute the pipeline and handle the result +try { + const querySnapshot = await execute(readDataPipeline); + querySnapshot.results.forEach((result) => { + console.log(`${result.id} => ${result.data()}`); + }); +} catch (error) { + console.error("Error getting documents: ", error); +} +``` diff --git a/.agents/skills/firebase-firestore-standard/SKILL.md b/.agents/skills/firebase-firestore-standard/SKILL.md new file mode 100644 index 0000000..0eb6c2e --- /dev/null +++ b/.agents/skills/firebase-firestore-standard/SKILL.md @@ -0,0 +1,27 @@ +--- +name: firebase-firestore-standard +description: Comprehensive guide for Firestore Standard Edition, including provisioning, security rules, and SDK usage. Use this skill when the user needs help setting up Firestore, writing security rules, or using the Firestore 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`. +--- + +# Firestore Standard Edition + +This skill provides a complete guide for getting started with Cloud Firestore Standard Edition, including provisioning, securing, and integrating it into your application. + +## Provisioning + +To set up Cloud Firestore in your Firebase project and local environment, see [provisioning.md](references/provisioning.md). + +## Security Rules + +For guidance on writing and deploying Firestore Security Rules to protect your data, see [security_rules.md](references/security_rules.md). + +## SDK Usage + +To learn how to use Cloud Firestore in your application code, choose your platform: + +* **Web (Modular SDK)**: [web_sdk_usage.md](references/web_sdk_usage.md) + +## Indexes + +For checking index types, query support tables, and best practices, see [indexes.md](references/indexes.md). diff --git a/.agents/skills/firebase-firestore-standard/references/indexes.md b/.agents/skills/firebase-firestore-standard/references/indexes.md new file mode 100644 index 0000000..7623eb8 --- /dev/null +++ b/.agents/skills/firebase-firestore-standard/references/indexes.md @@ -0,0 +1,82 @@ +# 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", "==", 1)` | Automatic (Single-Field) | +| **Simple Range/Sort**
`where("a", ">", 1).orderBy("a")` | Automatic (Single-Field) | +| **Multiple Equality**
`where("a", "==", 1).where("b", "==", 2)` | Automatic (Merged Single-Field) | +| **Equality + Range/Sort**
`where("a", "==", 1).where("b", ">", 2)` | **Composite Index** | +| **Multiple Ranges**
`where("a", ">", 1).where("b", ">", 2)` | **Composite Index** (and technically limited query support) | +| **Array Contains + Equality**
`where("tags", "array-contains", "news").where("active", "==", true)` | **Composite Index** | + +## 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/.agents/skills/firebase-firestore-standard/references/provisioning.md b/.agents/skills/firebase-firestore-standard/references/provisioning.md new file mode 100644 index 0000000..5278801 --- /dev/null +++ b/.agents/skills/firebase-firestore-standard/references/provisioning.md @@ -0,0 +1,87 @@ +# 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. 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: + +```json +{ + "firestore": { + "rules": "firestore.rules", + "indexes": "firestore.indexes.json", + "database": "my-database-id", + "location": "us-central1" + } +} +``` + +### 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 +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/.agents/skills/firebase-firestore-standard/references/security_rules.md b/.agents/skills/firebase-firestore-standard/references/security_rules.md new file mode 100644 index 0000000..fe24fad --- /dev/null +++ b/.agents/skills/firebase-firestore-standard/references/security_rules.md @@ -0,0 +1,414 @@ +## 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] +// +// =============================================================== +``` + +2. **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. + +3. **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/.agents/skills/firebase-firestore-standard/references/web_sdk_usage.md b/.agents/skills/firebase-firestore-standard/references/web_sdk_usage.md new file mode 100644 index 0000000..3d85134 --- /dev/null +++ b/.agents/skills/firebase-firestore-standard/references/web_sdk_usage.md @@ -0,0 +1,183 @@ +# Firestore Web SDK Usage Guide + +This guide focuses on the **Modular Web SDK** (v9+), which is tree-shakeable and efficient. + +## Initialization + +```javascript +import { initializeApp } from "firebase/app"; +import { getFirestore } from "firebase/firestore"; + +// If running in Firebase App Hosting, you can skip Firebase Config and instead use: +// const app = initializeApp(); + +const firebaseConfig = { + // Your config options. Get the values by running 'npx -y firebase-tools@latest apps:sdkconfig ' +}; + +const app = initializeApp(firebaseConfig); +const db = getFirestore(app); + +``` + +## Writing Data + +### Set a Document (`setDoc`) +Creates a document if it doesn't exist, or overwrites it if it does. + +```javascript +import { doc, setDoc } from "firebase/firestore"; + +// Create/Overwrite document with ID "LA" +await setDoc(doc(db, "cities", "LA"), { + name: "Los Angeles", + state: "CA", + country: "USA" +}); + +// To merge with existing data instead of overwriting: +await setDoc(doc(db, "cities", "LA"), { population: 3900000 }, { merge: true }); +``` + +### Add a Document with Auto-ID (`addDoc`) +Use when you don't care about the document ID. + +```javascript +import { collection, addDoc } from "firebase/firestore"; + +const docRef = await addDoc(collection(db, "cities"), { + name: "Tokyo", + country: "Japan" +}); +console.log("Document written with ID: ", docRef.id); +``` + +### Update a Document (`updateDoc`) +Update some fields of an existing document without overwriting the entire document. Fails if the document doesn't exist. + +```javascript +import { doc, updateDoc } from "firebase/firestore"; + +const laRef = doc(db, "cities", "LA"); + +await updateDoc(laRef, { + capital: true +}); +``` + +### Transactions +Perform an atomic read-modify-write operation. + +```javascript +import { runTransaction, doc } from "firebase/firestore"; + +const sfDocRef = doc(db, "cities", "SF"); + +try { + await runTransaction(db, async (transaction) => { + const sfDoc = await transaction.get(sfDocRef); + if (!sfDoc.exists()) { + throw "Document does not exist!"; + } + + const newPopulation = sfDoc.data().population + 1; + transaction.update(sfDocRef, { population: newPopulation }); + }); + console.log("Transaction successfully committed!"); +} catch (e) { + console.log("Transaction failed: ", e); +} +``` + +## Reading Data + +### Get a Single Document (`getDoc`) + +```javascript +import { doc, getDoc } from "firebase/firestore"; + +const docRef = doc(db, "cities", "SF"); +const docSnap = await getDoc(docRef); + +if (docSnap.exists()) { + console.log("Document data:", docSnap.data()); +} else { + console.log("No such document!"); +} +``` + +### Get Multiple Documents (`getDocs`) +Fetches all documents in a query or collection once. + +```javascript +import { collection, getDocs } from "firebase/firestore"; + +const querySnapshot = await getDocs(collection(db, "cities")); +querySnapshot.forEach((doc) => { + // doc.data() is never undefined for query doc snapshots + console.log(doc.id, " => ", doc.data()); +}); +``` + +## Realtime Updates + +### Listen to a Document/Query (`onSnapshot`) + +```javascript +import { doc, onSnapshot } from "firebase/firestore"; + +const unsub = onSnapshot(doc(db, "cities", "SF"), (doc) => { + console.log("Current data: ", doc.data()); +}); + +// Stop listening +// unsub(); +``` + +### Handle Changes (Added/Modified/Removed) + +```javascript +import { collection, query, where, onSnapshot } from "firebase/firestore"; + +const q = query(collection(db, "cities"), where("state", "==", "CA")); +const unsubscribe = onSnapshot(q, (snapshot) => { + snapshot.docChanges().forEach((change) => { + if (change.type === "added") { + console.log("New city: ", change.doc.data()); + } + if (change.type === "modified") { + console.log("Modified city: ", change.doc.data()); + } + if (change.type === "removed") { + console.log("Removed city: ", change.doc.data()); + } + }); +}); +``` + +## Queries + +### Simple and Compound Queries +Use `query()` to combine filters. + +```javascript +import { collection, query, where, getDocs } from "firebase/firestore"; + +const citiesRef = collection(db, "cities"); + +// Simple equality +const q1 = query(citiesRef, where("state", "==", "CA")); + +// Compound (AND) +// Note: Requires an index if filtering on different fields +const q2 = query(citiesRef, where("state", "==", "CA"), where("population", ">", 1000000)); +``` + +### Order and Limit +Sort and limit results. + +```javascript +import { orderBy, limit } from "firebase/firestore"; + +const q = query(citiesRef, orderBy("name"), limit(3)); +``` diff --git a/.agents/skills/firebase-hosting-basics/SKILL.md b/.agents/skills/firebase-hosting-basics/SKILL.md new file mode 100644 index 0000000..a83ac28 --- /dev/null +++ b/.agents/skills/firebase-hosting-basics/SKILL.md @@ -0,0 +1,46 @@ +--- +name: firebase-hosting-basics +description: Skill for working with Firebase Hosting (Classic). Use this when you want to deploy static web apps, Single Page Apps (SPAs), or simple microservices. Do NOT use for Firebase App Hosting. +--- + +# hosting-basics + +This skill provides instructions and references for working with Firebase Hosting, a fast and secure hosting service for your web app, static and dynamic content, and microservices. + +## Overview + +Firebase Hosting provides production-grade web content hosting for developers. With a single command, you can deploy web apps and serve both static and dynamic content to a global CDN (content delivery network). + +**Key Features:** +- **Fast Content Delivery:** Files are cached on SSDs at CDN edges around the world. +- **Secure by Default:** Zero-configuration SSL is built-in. +- **Preview Channels:** View and test changes on temporary preview URLs before deploying live. +- **GitHub Integration:** Automate previews and deploys with GitHub Actions. +- **Dynamic Content:** Serve dynamic content and microservices using Cloud Functions or Cloud Run. + +## Hosting vs App Hosting + +**Choose Firebase Hosting if:** +- You are deploying a static site (HTML/CSS/JS). +- You are deploying a simple SPA (React, Vue, etc. without SSR). +- You want full control over the build and deploy process via CLI. + +**Choose Firebase App Hosting if:** +- You are using a supported full-stack framework like Next.js or Angular. +- You need Server-Side Rendering (SSR) or ISR. +- You want an automated "git push to deploy" workflow with zero configuration. + +## Instructions + +### 1. Configuration (`firebase.json`) +For details on configuring Hosting behavior, including public directories, redirects, rewrites, and headers, see [configuration.md](references/configuration.md). + +### 2. Deploying +For instructions on deploying your site, using preview channels, and managing releases, see [deploying.md](references/deploying.md). + +### 3. Emulation +To test your app locally: +```bash +npx -y firebase-tools@latest emulators:start --only hosting +``` +This serves your app at `http://localhost:5000` by default. diff --git a/.agents/skills/firebase-hosting-basics/references/configuration.md b/.agents/skills/firebase-hosting-basics/references/configuration.md new file mode 100644 index 0000000..adb9050 --- /dev/null +++ b/.agents/skills/firebase-hosting-basics/references/configuration.md @@ -0,0 +1,101 @@ +# Hosting Configuration (`firebase.json`) + +The `hosting` section of `firebase.json` configures how your site is deployed and served. + +## Key Attributes + +### `public` (Required) +Specifies the directory to deploy to Firebase Hosting. +```json +"hosting": { + "public": "public" +} +``` + +### `ignore` (Optional) +Files to ignore on deploy. Uses glob patterns (like `.gitignore`). +**Default ignores:** `firebase.json`, `**/.*`, `**/node_modules/**` + +### `redirects` (Optional) +URL redirects to prevent broken links or shorten URLs. +```json +"redirects": [ + { + "source": "/foo", + "destination": "/bar", + "type": 301 + } +] +``` + +### `rewrites` (Optional) +Serve the same content for multiple URLs, useful for SPAs or Dynamic Content. +```json +"rewrites": [ + { + "source": "**", + "destination": "/index.html" + }, + { + "source": "/api/**", + "function": "apiFunction" + }, + { + "source": "/container/**", + "run": { + "serviceId": "helloworld", + "region": "us-central1" + } + } +] +``` + +### `headers` (Optional) +Custom response headers. +```json +"headers": [ + { + "source": "**/*.@(eot|otf|ttf|ttc|woff|font.css)", + "headers": [ + { + "key": "Access-Control-Allow-Origin", + "value": "*" + } + ] + } +] +``` + +### `cleanUrls` (Optional) +If `true`, drops `.html` extension from URLs. +```json +"cleanUrls": true +``` + +### `trailingSlash` (Optional) +Controls trailing slashes in static content URLs. +- `true`: Adds trailing slash. +- `false`: Removes trailing slash. + +## Full Example + +```json +{ + "hosting": { + "public": "dist", + "ignore": [ + "firebase.json", + "**/.*", + "**/node_modules/**" + ], + "rewrites": [ + { + "source": "**", + "destination": "/index.html" + } + ], + "cleanUrls": true, + "trailingSlash": false + } +} +``` diff --git a/.agents/skills/firebase-hosting-basics/references/deploying.md b/.agents/skills/firebase-hosting-basics/references/deploying.md new file mode 100644 index 0000000..df26c5e --- /dev/null +++ b/.agents/skills/firebase-hosting-basics/references/deploying.md @@ -0,0 +1,39 @@ +# Deploying to Firebase Hosting + +## Standard Deployment +To deploy your Hosting content and configuration to your live site: + +```bash +npx -y firebase-tools@latest deploy --only hosting +``` + +This deploys to your default sites (`PROJECT_ID.web.app` and `PROJECT_ID.firebaseapp.com`). + +## Preview Channels +Preview channels allow you to test changes on a temporary URL before going live. + +### Deploy to a Preview Channel +```bash +npx -y firebase-tools@latest hosting:channel:deploy CHANNEL_ID +``` +Replace `CHANNEL_ID` with a name (e.g., `feature-beta`). +This returns a preview URL like `PROJECT_ID--CHANNEL_ID-RANDOM_HASH.web.app`. + +### Expiration +Channels expire after 7 days by default. To set a different expiration: +```bash +npx -y firebase-tools@latest hosting:channel:deploy CHANNEL_ID --expires 1d +``` + +## Cloning to Live +You can promote a version from a preview channel to your live channel without rebuilding. + +```bash +npx -y firebase-tools@latest hosting:clone SOURCE_SITE_ID:SOURCE_CHANNEL_ID TARGET_SITE_ID:live +``` + +**Example:** +Clone the `feature-beta` channel on your default site to live: +```bash +npx -y firebase-tools@latest hosting:clone my-project:feature-beta my-project:live +``` diff --git a/.augment/skills/developing-genkit-dart b/.augment/skills/developing-genkit-dart new file mode 120000 index 0000000..db66521 --- /dev/null +++ b/.augment/skills/developing-genkit-dart @@ -0,0 +1 @@ +../../.agents/skills/developing-genkit-dart \ No newline at end of file diff --git a/.augment/skills/developing-genkit-js b/.augment/skills/developing-genkit-js new file mode 120000 index 0000000..10154eb --- /dev/null +++ b/.augment/skills/developing-genkit-js @@ -0,0 +1 @@ +../../.agents/skills/developing-genkit-js \ No newline at end of file diff --git a/.augment/skills/firebase-ai-logic b/.augment/skills/firebase-ai-logic new file mode 120000 index 0000000..7fac814 --- /dev/null +++ b/.augment/skills/firebase-ai-logic @@ -0,0 +1 @@ +../../.agents/skills/firebase-ai-logic \ No newline at end of file diff --git a/.augment/skills/firebase-app-hosting-basics b/.augment/skills/firebase-app-hosting-basics new file mode 120000 index 0000000..a55aceb --- /dev/null +++ b/.augment/skills/firebase-app-hosting-basics @@ -0,0 +1 @@ +../../.agents/skills/firebase-app-hosting-basics \ No newline at end of file diff --git a/.augment/skills/firebase-auth-basics b/.augment/skills/firebase-auth-basics new file mode 120000 index 0000000..a5c22cd --- /dev/null +++ b/.augment/skills/firebase-auth-basics @@ -0,0 +1 @@ +../../.agents/skills/firebase-auth-basics \ No newline at end of file diff --git a/.augment/skills/firebase-basics b/.augment/skills/firebase-basics new file mode 120000 index 0000000..1bac363 --- /dev/null +++ b/.augment/skills/firebase-basics @@ -0,0 +1 @@ +../../.agents/skills/firebase-basics \ No newline at end of file diff --git a/.augment/skills/firebase-data-connect b/.augment/skills/firebase-data-connect new file mode 120000 index 0000000..edcb837 --- /dev/null +++ b/.augment/skills/firebase-data-connect @@ -0,0 +1 @@ +../../.agents/skills/firebase-data-connect \ No newline at end of file diff --git a/.augment/skills/firebase-firestore-enterprise-native-mode b/.augment/skills/firebase-firestore-enterprise-native-mode new file mode 120000 index 0000000..c28c441 --- /dev/null +++ b/.augment/skills/firebase-firestore-enterprise-native-mode @@ -0,0 +1 @@ +../../.agents/skills/firebase-firestore-enterprise-native-mode \ No newline at end of file diff --git a/.augment/skills/firebase-firestore-standard b/.augment/skills/firebase-firestore-standard new file mode 120000 index 0000000..449dea1 --- /dev/null +++ b/.augment/skills/firebase-firestore-standard @@ -0,0 +1 @@ +../../.agents/skills/firebase-firestore-standard \ No newline at end of file diff --git a/.augment/skills/firebase-hosting-basics b/.augment/skills/firebase-hosting-basics new file mode 120000 index 0000000..d7c095b --- /dev/null +++ b/.augment/skills/firebase-hosting-basics @@ -0,0 +1 @@ +../../.agents/skills/firebase-hosting-basics \ No newline at end of file diff --git a/.claude/settings.json b/.claude/settings.json index b3fb448..07df106 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -7,7 +7,7 @@ }, "enabledPlugins": { "superpowers@claude-plugins-official": true, - "oh-my-claudecode@omc": false, + "oh-my-claudecode@omc": true, "context7@claude-plugins-official": true } } diff --git a/.claude/skills/developing-genkit-dart b/.claude/skills/developing-genkit-dart new file mode 120000 index 0000000..db66521 --- /dev/null +++ b/.claude/skills/developing-genkit-dart @@ -0,0 +1 @@ +../../.agents/skills/developing-genkit-dart \ No newline at end of file diff --git a/.claude/skills/developing-genkit-js b/.claude/skills/developing-genkit-js new file mode 120000 index 0000000..10154eb --- /dev/null +++ b/.claude/skills/developing-genkit-js @@ -0,0 +1 @@ +../../.agents/skills/developing-genkit-js \ No newline at end of file diff --git a/.claude/skills/firebase-ai-logic b/.claude/skills/firebase-ai-logic new file mode 120000 index 0000000..7fac814 --- /dev/null +++ b/.claude/skills/firebase-ai-logic @@ -0,0 +1 @@ +../../.agents/skills/firebase-ai-logic \ No newline at end of file diff --git a/.claude/skills/firebase-app-hosting-basics b/.claude/skills/firebase-app-hosting-basics new file mode 120000 index 0000000..a55aceb --- /dev/null +++ b/.claude/skills/firebase-app-hosting-basics @@ -0,0 +1 @@ +../../.agents/skills/firebase-app-hosting-basics \ No newline at end of file diff --git a/.claude/skills/firebase-auth-basics b/.claude/skills/firebase-auth-basics new file mode 120000 index 0000000..a5c22cd --- /dev/null +++ b/.claude/skills/firebase-auth-basics @@ -0,0 +1 @@ +../../.agents/skills/firebase-auth-basics \ No newline at end of file diff --git a/.claude/skills/firebase-basics b/.claude/skills/firebase-basics new file mode 120000 index 0000000..1bac363 --- /dev/null +++ b/.claude/skills/firebase-basics @@ -0,0 +1 @@ +../../.agents/skills/firebase-basics \ No newline at end of file diff --git a/.claude/skills/firebase-data-connect b/.claude/skills/firebase-data-connect new file mode 120000 index 0000000..edcb837 --- /dev/null +++ b/.claude/skills/firebase-data-connect @@ -0,0 +1 @@ +../../.agents/skills/firebase-data-connect \ No newline at end of file diff --git a/.claude/skills/firebase-firestore-enterprise-native-mode b/.claude/skills/firebase-firestore-enterprise-native-mode new file mode 120000 index 0000000..c28c441 --- /dev/null +++ b/.claude/skills/firebase-firestore-enterprise-native-mode @@ -0,0 +1 @@ +../../.agents/skills/firebase-firestore-enterprise-native-mode \ No newline at end of file diff --git a/.claude/skills/firebase-firestore-standard b/.claude/skills/firebase-firestore-standard new file mode 120000 index 0000000..449dea1 --- /dev/null +++ b/.claude/skills/firebase-firestore-standard @@ -0,0 +1 @@ +../../.agents/skills/firebase-firestore-standard \ No newline at end of file diff --git a/.claude/skills/firebase-hosting-basics b/.claude/skills/firebase-hosting-basics new file mode 120000 index 0000000..d7c095b --- /dev/null +++ b/.claude/skills/firebase-hosting-basics @@ -0,0 +1 @@ +../../.agents/skills/firebase-hosting-basics \ No newline at end of file diff --git a/.firebaserc b/.firebaserc new file mode 100644 index 0000000..ae68e71 --- /dev/null +++ b/.firebaserc @@ -0,0 +1,5 @@ +{ + "projects": { + "default": "ff-kit" + } +} diff --git a/.github/workflows/firebase-hosting-merge.yml b/.github/workflows/firebase-hosting-merge.yml new file mode 100644 index 0000000..5e43118 --- /dev/null +++ b/.github/workflows/firebase-hosting-merge.yml @@ -0,0 +1,20 @@ +# This file was auto-generated by the Firebase CLI +# https://github.com/firebase/firebase-tools + +name: Deploy to Firebase Hosting on merge +on: + push: + branches: + - main +jobs: + build_and_deploy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: npm ci && npm run build + - uses: FirebaseExtended/action-hosting-deploy@v0 + with: + repoToken: ${{ secrets.GITHUB_TOKEN }} + firebaseServiceAccount: ${{ secrets.FIREBASE_SERVICE_ACCOUNT_FF_KIT }} + channelId: live + projectId: ff-kit diff --git a/.github/workflows/firebase-hosting-pull-request.yml b/.github/workflows/firebase-hosting-pull-request.yml new file mode 100644 index 0000000..9bd489b --- /dev/null +++ b/.github/workflows/firebase-hosting-pull-request.yml @@ -0,0 +1,21 @@ +# This file was auto-generated by the Firebase CLI +# https://github.com/firebase/firebase-tools + +name: Deploy to Firebase Hosting on PR +on: pull_request +permissions: + checks: write + contents: read + pull-requests: write +jobs: + build_and_preview: + if: ${{ github.event.pull_request.head.repo.full_name == github.repository }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: npm ci && npm run build + - uses: FirebaseExtended/action-hosting-deploy@v0 + with: + repoToken: ${{ secrets.GITHUB_TOKEN }} + firebaseServiceAccount: ${{ secrets.FIREBASE_SERVICE_ACCOUNT_FF_KIT }} + projectId: ff-kit diff --git a/CLAUDE.md b/CLAUDE.md index e7ec8b9..76e48b6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -125,3 +125,10 @@ Types: `build`, `ci`, `docs`, `feat`, `fix`, `perf`, `refactor`, `test` Scopes: `core`, `data`, `domain`, `ui`, `design` Example: `LIS-123 - feat(ui) : ajouter écran de connexion` + +## Active Technologies +- Dart 3.10+ / Flutter >=3.10.2 + `firebase_core`, `firebase_auth`, (001-firebase-auth) +- Firebase Auth (remote) — no local storage needed (001-firebase-auth) + +## Recent Changes +- 001-firebase-auth: Added Dart 3.10+ / Flutter >=3.10.2 + `firebase_core`, `firebase_auth`, diff --git a/android/app/build.gradle b/android/app/build.gradle index bbeede0..71aa84b 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -1,5 +1,8 @@ plugins { id "com.android.application" + // START: FlutterFire Configuration + id 'com.google.gms.google-services' + // END: FlutterFire Configuration id "kotlin-android" // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. id "dev.flutter.flutter-gradle-plugin" diff --git a/android/app/google-services.json b/android/app/google-services.json new file mode 100644 index 0000000..3edcbed --- /dev/null +++ b/android/app/google-services.json @@ -0,0 +1,29 @@ +{ + "project_info": { + "project_number": "575974943870", + "project_id": "ff-kit", + "storage_bucket": "ff-kit.firebasestorage.app" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:575974943870:android:0a3cd7cebe67e0398e3c2f", + "android_client_info": { + "package_name": "pro.listo.flutter_starter_kit" + } + }, + "oauth_client": [], + "api_key": [ + { + "current_key": "AIzaSyCRU89MM99PM1SHyooDUUxj-F2fHz6rggM" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [] + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file diff --git a/android/settings.gradle b/android/settings.gradle index b9e43bd..9759a22 100644 --- a/android/settings.gradle +++ b/android/settings.gradle @@ -19,6 +19,9 @@ pluginManagement { plugins { id "dev.flutter.flutter-plugin-loader" version "1.0.0" id "com.android.application" version "8.1.0" apply false + // START: FlutterFire Configuration + id "com.google.gms.google-services" version "4.3.15" apply false + // END: FlutterFire Configuration id "org.jetbrains.kotlin.android" version "1.8.22" apply false } diff --git a/firebase.json b/firebase.json new file mode 100644 index 0000000..932ff02 --- /dev/null +++ b/firebase.json @@ -0,0 +1,62 @@ +{ + "flutter": { + "platforms": { + "android": { + "default": { + "projectId": "ff-kit", + "appId": "1:575974943870:android:0a3cd7cebe67e0398e3c2f", + "fileOutput": "android/app/google-services.json" + } + }, + "ios": { + "default": { + "projectId": "ff-kit", + "appId": "1:575974943870:ios:fee7b78e909f25528e3c2f", + "uploadDebugSymbols": false, + "fileOutput": "ios/Runner/GoogleService-Info.plist" + } + }, + "macos": { + "default": { + "projectId": "ff-kit", + "appId": "1:575974943870:ios:7d87f82d470fc9368e3c2f", + "uploadDebugSymbols": false, + "fileOutput": "macos/Runner/GoogleService-Info.plist" + } + }, + "dart": { + "lib/firebase_options.dart": { + "projectId": "ff-kit", + "configurations": { + "android": "1:575974943870:android:0a3cd7cebe67e0398e3c2f", + "ios": "1:575974943870:ios:fee7b78e909f25528e3c2f", + "macos": "1:575974943870:ios:7d87f82d470fc9368e3c2f", + "web": "1:575974943870:web:470ce703d47392208e3c2f", + "windows": "1:575974943870:web:261266ae01ca1e0a8e3c2f" + } + } + } + } + }, + "functions": [ + { + "source": "functions", + "codebase": "default", + "disallowLegacyRuntimeConfig": true, + "ignore": [ + "node_modules", + ".git", + "firebase-debug.log", + "firebase-debug.*.log", + "*.local" + ], + "predeploy": [ + "npm --prefix \"$RESOURCE_DIR\" run lint", + "npm --prefix \"$RESOURCE_DIR\" run build" + ] + } + ], + "emulators": { + "singleProjectMode": true + } +} diff --git a/firestore.indexes.json b/firestore.indexes.json new file mode 100644 index 0000000..0e6de7c --- /dev/null +++ b/firestore.indexes.json @@ -0,0 +1,51 @@ +{ + // Example (Standard Edition): + // + // "indexes": [ + // { + // "collectionGroup": "widgets", + // "queryScope": "COLLECTION", + // "fields": [ + // { "fieldPath": "foo", "arrayConfig": "CONTAINS" }, + // { "fieldPath": "bar", "mode": "DESCENDING" } + // ] + // }, + // + // "fieldOverrides": [ + // { + // "collectionGroup": "widgets", + // "fieldPath": "baz", + // "indexes": [ + // { "order": "ASCENDING", "queryScope": "COLLECTION" } + // ] + // }, + // ] + // ] + // + // Example (Enterprise Edition): + // + // "indexes": [ + // { + // "collectionGroup": "reviews", + // "queryScope": "COLLECTION_GROUP", + // "apiScope": "MONGODB_COMPATIBLE_API", + // "density": "DENSE", + // "multikey": false, + // "fields": [ + // { "fieldPath": "baz", "mode": "ASCENDING" } + // ] + // }, + // { + // "collectionGroup": "items", + // "queryScope": "COLLECTION_GROUP", + // "apiScope": "MONGODB_COMPATIBLE_API", + // "density": "SPARSE_ANY", + // "multikey": true, + // "fields": [ + // { "fieldPath": "baz", "mode": "ASCENDING" } + // ] + // }, + // ] + "indexes": [], + "fieldOverrides": [] +} \ No newline at end of file diff --git a/firestore.rules b/firestore.rules new file mode 100644 index 0000000..dc41052 --- /dev/null +++ b/firestore.rules @@ -0,0 +1,18 @@ +rules_version='2' + +service cloud.firestore { + match /databases/{database}/documents { + match /{document=**} { + // This rule allows anyone with your database reference to view, edit, + // and delete all data in your database. It is useful for getting + // started, but it is configured to expire after 30 days because it + // leaves your app open to attackers. At that time, all client + // requests to your database will be denied. + // + // Make sure to write security rules for your app before that time, or + // else all client requests to your database will be denied until you + // update your rules. + allow read, write: if request.time < timestamp.date(2026, 5, 5); + } + } +} diff --git a/functions/.eslintrc.js b/functions/.eslintrc.js new file mode 100644 index 0000000..0f8e2a9 --- /dev/null +++ b/functions/.eslintrc.js @@ -0,0 +1,33 @@ +module.exports = { + root: true, + env: { + es6: true, + node: true, + }, + extends: [ + "eslint:recommended", + "plugin:import/errors", + "plugin:import/warnings", + "plugin:import/typescript", + "google", + "plugin:@typescript-eslint/recommended", + ], + parser: "@typescript-eslint/parser", + parserOptions: { + project: ["tsconfig.json", "tsconfig.dev.json"], + sourceType: "module", + }, + ignorePatterns: [ + "/lib/**/*", // Ignore built files. + "/generated/**/*", // Ignore generated files. + ], + plugins: [ + "@typescript-eslint", + "import", + ], + rules: { + "quotes": ["error", "double"], + "import/no-unresolved": 0, + "indent": ["error", 2], + }, +}; diff --git a/functions/.gitignore b/functions/.gitignore new file mode 100644 index 0000000..9be0f01 --- /dev/null +++ b/functions/.gitignore @@ -0,0 +1,10 @@ +# Compiled JavaScript files +lib/**/*.js +lib/**/*.js.map + +# TypeScript v1 declaration files +typings/ + +# Node.js dependency directory +node_modules/ +*.local \ No newline at end of file diff --git a/functions/package.json b/functions/package.json new file mode 100644 index 0000000..5081115 --- /dev/null +++ b/functions/package.json @@ -0,0 +1,31 @@ +{ + "name": "functions", + "scripts": { + "lint": "eslint --ext .js,.ts .", + "build": "tsc", + "build:watch": "tsc --watch", + "serve": "npm run build && firebase emulators:start --only functions", + "shell": "npm run build && firebase functions:shell", + "start": "npm run shell", + "deploy": "firebase deploy --only functions", + "logs": "firebase functions:log" + }, + "engines": { + "node": "24" + }, + "main": "lib/index.js", + "dependencies": { + "firebase-admin": "^13.6.0", + "firebase-functions": "^7.0.0" + }, + "devDependencies": { + "@typescript-eslint/eslint-plugin": "^5.12.0", + "@typescript-eslint/parser": "^5.12.0", + "eslint": "^8.9.0", + "eslint-config-google": "^0.14.0", + "eslint-plugin-import": "^2.25.4", + "firebase-functions-test": "^3.4.1", + "typescript": "^6.0.0" + }, + "private": true +} diff --git a/functions/src/index.ts b/functions/src/index.ts new file mode 100644 index 0000000..ade33ec --- /dev/null +++ b/functions/src/index.ts @@ -0,0 +1,32 @@ +/** + * Import function triggers from their respective submodules: + * + * import {onCall} from "firebase-functions/v2/https"; + * import {onDocumentWritten} from "firebase-functions/v2/firestore"; + * + * See a full list of supported triggers at https://firebase.google.com/docs/functions + */ + +import {setGlobalOptions} from "firebase-functions"; +import {onRequest} from "firebase-functions/https"; +import * as logger from "firebase-functions/logger"; + +// Start writing functions +// https://firebase.google.com/docs/functions/typescript + +// For cost control, you can set the maximum number of containers that can be +// running at the same time. This helps mitigate the impact of unexpected +// traffic spikes by instead downgrading performance. This limit is a +// per-function limit. You can override the limit for each function using the +// `maxInstances` option in the function's options, e.g. +// `onRequest({ maxInstances: 5 }, (req, res) => { ... })`. +// NOTE: setGlobalOptions does not apply to functions using the v1 API. V1 +// functions should each use functions.runWith({ maxInstances: 10 }) instead. +// In the v1 API, each function can only serve one request per container, so +// this will be the maximum concurrent request count. +setGlobalOptions({ maxInstances: 10 }); + +// export const helloWorld = onRequest((request, response) => { +// logger.info("Hello logs!", {structuredData: true}); +// response.send("Hello from Firebase!"); +// }); diff --git a/functions/tsconfig.dev.json b/functions/tsconfig.dev.json new file mode 100644 index 0000000..7560eed --- /dev/null +++ b/functions/tsconfig.dev.json @@ -0,0 +1,5 @@ +{ + "include": [ + ".eslintrc.js" + ] +} diff --git a/functions/tsconfig.json b/functions/tsconfig.json new file mode 100644 index 0000000..7052fbb --- /dev/null +++ b/functions/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "module": "NodeNext", + "esModuleInterop": true, + "moduleResolution": "nodenext", + "noImplicitReturns": true, + "noUnusedLocals": true, + "outDir": "lib", + "rootDir": "src", + "sourceMap": true, + "strict": true, + "target": "es2017" + }, + "compileOnSave": true, + "include": [ + "src" + ] +} diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig index 592ceee..ec97fc6 100644 --- a/ios/Flutter/Debug.xcconfig +++ b/ios/Flutter/Debug.xcconfig @@ -1 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig index 592ceee..c4855bf 100644 --- a/ios/Flutter/Release.xcconfig +++ b/ios/Flutter/Release.xcconfig @@ -1 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" diff --git a/ios/Podfile b/ios/Podfile new file mode 100644 index 0000000..620e46e --- /dev/null +++ b/ios/Podfile @@ -0,0 +1,43 @@ +# Uncomment this line to define a global platform for your project +# platform :ios, '13.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_ios_podfile_setup + +target 'Runner' do + use_frameworks! + + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_ios_build_settings(target) + end +end diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index 0527914..49d360f 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -30,6 +30,7 @@ 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; 9F4B3BDAD9E7CEB46CD945C7 /* devRelease.xcconfig in Resources */ = {isa = PBXBuildFile; fileRef = DD3914A20FB20F3BCFBD07A3 /* devRelease.xcconfig */; }; + AA8823683D21755B5477D8BF /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = FF2FB56B87640E0ABBFF3384 /* GoogleService-Info.plist */; }; B3510E9272C530EDCF39D117 /* preprodProfile.xcconfig in Resources */ = {isa = PBXBuildFile; fileRef = 57FEE0DDCC16F1375880B799 /* preprodProfile.xcconfig */; }; B6512F09F55BD1307994C619 /* preprodDebug.xcconfig in Resources */ = {isa = PBXBuildFile; fileRef = 59CBAC87D8EC2408E8D213B0 /* preprodDebug.xcconfig */; }; BCD423C2292274C9DFE25C2F /* integrationRelease.xcconfig in Resources */ = {isa = PBXBuildFile; fileRef = 83978C74FAEDEE797EFB0229 /* integrationRelease.xcconfig */; }; @@ -103,6 +104,7 @@ E940087472397C0117B6DE95 /* devProfile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = devProfile.xcconfig; path = Flutter/devProfile.xcconfig; sourceTree = ""; }; EB620E43BABE785EB817FF30 /* integrationProfile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = integrationProfile.xcconfig; path = Flutter/integrationProfile.xcconfig; sourceTree = ""; }; F2941A93254A4EF0BEEF1866 /* testRelease.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = testRelease.xcconfig; path = Flutter/testRelease.xcconfig; sourceTree = ""; }; + FF2FB56B87640E0ABBFF3384 /* GoogleService-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; name = "GoogleService-Info.plist"; path = "Runner/GoogleService-Info.plist"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -166,6 +168,7 @@ 698569F69B31FB6A17744466 /* integrationLaunchScreen.storyboard */, 06751D971C773C254679643D /* devLaunchScreen.storyboard */, 6EF6B360BA8A1C7209EB9A62 /* testLaunchScreen.storyboard */, + FF2FB56B87640E0ABBFF3384 /* GoogleService-Info.plist */, ); sourceTree = ""; }; @@ -312,6 +315,7 @@ 1D51DE7D37317826E71FBBD5 /* integrationLaunchScreen.storyboard in Resources */, 17C83E11580928C5011DAB02 /* devLaunchScreen.storyboard in Resources */, F12AEF9C8030DB9EDA830C03 /* testLaunchScreen.storyboard in Resources */, + AA8823683D21755B5477D8BF /* GoogleService-Info.plist in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/ios/Runner/GoogleService-Info.plist b/ios/Runner/GoogleService-Info.plist new file mode 100644 index 0000000..2a0039a --- /dev/null +++ b/ios/Runner/GoogleService-Info.plist @@ -0,0 +1,30 @@ + + + + + API_KEY + AIzaSyCT5QclXtOTZQG00LXXCBoBXJeIUKe3p2o + GCM_SENDER_ID + 575974943870 + PLIST_VERSION + 1 + BUNDLE_ID + fr.benoitfontaine.starter.recette + PROJECT_ID + ff-kit + STORAGE_BUCKET + ff-kit.firebasestorage.app + IS_ADS_ENABLED + + IS_ANALYTICS_ENABLED + + IS_APPINVITE_ENABLED + + IS_GCM_ENABLED + + IS_SIGNIN_ENABLED + + GOOGLE_APP_ID + 1:575974943870:ios:fee7b78e909f25528e3c2f + + \ No newline at end of file diff --git a/lib/core/di/auth/auth_core_module.dart b/lib/core/di/auth/auth_core_module.dart new file mode 100644 index 0000000..00d9202 --- /dev/null +++ b/lib/core/di/auth/auth_core_module.dart @@ -0,0 +1,3 @@ +export 'auth_module.dart'; +export 'auth_module_impl.dart'; +export 'auth_module_stub.dart'; diff --git a/lib/core/di/auth/auth_module.dart b/lib/core/di/auth/auth_module.dart new file mode 100644 index 0000000..e0dea5f --- /dev/null +++ b/lib/core/di/auth/auth_module.dart @@ -0,0 +1,5 @@ +import 'package:firebase_auth/firebase_auth.dart'; + +abstract class AuthModule { + FirebaseAuth get firebaseAuth; +} diff --git a/lib/core/di/auth/auth_module_impl.dart b/lib/core/di/auth/auth_module_impl.dart new file mode 100644 index 0000000..17cd7ac --- /dev/null +++ b/lib/core/di/auth/auth_module_impl.dart @@ -0,0 +1,16 @@ +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:injectable/injectable.dart'; + +import '/injection.dart'; +import 'auth_module.dart'; + +@dev +@integration +@recette +@preprod +@prod +@Singleton(as: AuthModule) +class AuthModuleImpl implements AuthModule { + @override + FirebaseAuth get firebaseAuth => FirebaseAuth.instance; +} diff --git a/lib/core/di/auth/auth_module_stub.dart b/lib/core/di/auth/auth_module_stub.dart new file mode 100644 index 0000000..71d15cb --- /dev/null +++ b/lib/core/di/auth/auth_module_stub.dart @@ -0,0 +1,18 @@ +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:firebase_auth_mocks/firebase_auth_mocks.dart'; +import 'package:injectable/injectable.dart'; + +import 'auth_module.dart'; + +@test +@Singleton(as: AuthModule) +class AuthModuleStub implements AuthModule { + late final MockFirebaseAuth _mockFirebaseAuth; + + AuthModuleStub() { + _mockFirebaseAuth = MockFirebaseAuth(); + } + + @override + FirebaseAuth get firebaseAuth => _mockFirebaseAuth; +} diff --git a/lib/core/di/di_module.dart b/lib/core/di/di_module.dart index e218144..e3634fc 100644 --- a/lib/core/di/di_module.dart +++ b/lib/core/di/di_module.dart @@ -1,2 +1,3 @@ +export 'auth/auth_core_module.dart'; export 'configuration/configuration_module.dart'; export 'network/network_module.dart'; \ No newline at end of file diff --git a/lib/data/dto/auth_user_dto.dart b/lib/data/dto/auth_user_dto.dart new file mode 100644 index 0000000..dd41296 --- /dev/null +++ b/lib/data/dto/auth_user_dto.dart @@ -0,0 +1,22 @@ +import 'package:firebase_auth/firebase_auth.dart'; + +class AuthUserDto { + final String uid; + final String? email; + final String? displayName; + final bool isEmailVerified; + + const AuthUserDto({ + required this.uid, + this.email, + this.displayName, + required this.isEmailVerified, + }); + + factory AuthUserDto.fromFirebaseUser(User user) => AuthUserDto( + uid: user.uid, + email: user.email, + displayName: user.displayName, + isEmailVerified: user.emailVerified, + ); +} diff --git a/lib/data/dto/dto_module.dart b/lib/data/dto/dto_module.dart index e69de29..2760f97 100644 --- a/lib/data/dto/dto_module.dart +++ b/lib/data/dto/dto_module.dart @@ -0,0 +1 @@ +export 'auth_user_dto.dart'; diff --git a/lib/data/repositories/auth_repository.dart b/lib/data/repositories/auth_repository.dart new file mode 100644 index 0000000..6764b6e --- /dev/null +++ b/lib/data/repositories/auth_repository.dart @@ -0,0 +1,9 @@ +import '../../domain/domain_module.dart'; + +abstract class AuthRepository { + Stream signUp(String email, String password); + Stream signIn(String email, String password); + Stream signOut(); + Stream sendPasswordResetEmail(String email); + Stream watchAuthState(); +} diff --git a/lib/data/repositories/auth_repository_impl.dart b/lib/data/repositories/auth_repository_impl.dart new file mode 100644 index 0000000..1b4dd84 --- /dev/null +++ b/lib/data/repositories/auth_repository_impl.dart @@ -0,0 +1,124 @@ +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:injectable/injectable.dart'; + +import '../../core/core_module.dart'; +import '../../domain/domain_module.dart'; +import '../dto/dto_module.dart'; +import 'auth_repository.dart'; + +@Injectable(as: AuthRepository) +class AuthRepositoryImpl implements AuthRepository { + final FirebaseAuth _firebaseAuth; + + AuthRepositoryImpl(AuthModule authModule) : _firebaseAuth = authModule.firebaseAuth; + + @override + Stream signUp(String email, String password) async* { + try { + final credential = await _firebaseAuth.createUserWithEmailAndPassword( + email: email, + password: password, + ); + final user = credential.user; + if (user == null) { + throw const AuthException( + type: AuthErrorType.unknown, + message: 'Account creation failed. Please try again.', + ); + } + yield AuthUser.fromDto(AuthUserDto.fromFirebaseUser(user)); + } on FirebaseAuthException catch (e) { + throw _mapFirebaseException(e); + } + } + + @override + Stream signIn(String email, String password) async* { + try { + final credential = await _firebaseAuth.signInWithEmailAndPassword( + email: email, + password: password, + ); + final user = credential.user; + if (user == null) { + throw const AuthException( + type: AuthErrorType.unknown, + message: 'Sign-in failed. Please try again.', + ); + } + yield AuthUser.fromDto(AuthUserDto.fromFirebaseUser(user)); + } on FirebaseAuthException catch (e) { + throw _mapFirebaseException(e); + } + } + + @override + Stream signOut() async* { + try { + await _firebaseAuth.signOut(); + yield null; + } on FirebaseAuthException catch (e) { + throw _mapFirebaseException(e); + } + } + + @override + Stream sendPasswordResetEmail(String email) async* { + try { + await _firebaseAuth.sendPasswordResetEmail(email: email); + yield null; + } on FirebaseAuthException catch (e) { + throw _mapFirebaseException(e); + } + } + + @override + Stream watchAuthState() { + return _firebaseAuth.authStateChanges().map((user) { + if (user == null) return null; + return AuthUser.fromDto(AuthUserDto.fromFirebaseUser(user)); + }); + } + + AuthException _mapFirebaseException(FirebaseAuthException e) { + switch (e.code) { + case 'email-already-in-use': + return const AuthException( + type: AuthErrorType.emailAlreadyInUse, + message: 'This email is already associated with an account.', + ); + case 'wrong-password': + case 'user-not-found': + case 'invalid-credential': + return const AuthException( + type: AuthErrorType.invalidCredentials, + message: 'Invalid email or password.', + ); + case 'weak-password': + return const AuthException( + type: AuthErrorType.weakPassword, + message: 'Password is too weak. Use at least 8 characters with mixed case and a digit.', + ); + case 'invalid-email': + return const AuthException( + type: AuthErrorType.invalidEmail, + message: 'The email address format is invalid.', + ); + case 'network-request-failed': + return const AuthException( + type: AuthErrorType.networkError, + message: 'No internet connection. Please check your network and try again.', + ); + case 'too-many-requests': + return const AuthException( + type: AuthErrorType.tooManyRequests, + message: 'Too many attempts. Please wait a moment and try again.', + ); + default: + return AuthException( + type: AuthErrorType.unknown, + message: 'An unexpected error occurred. Please try again later.', + ); + } + } +} diff --git a/lib/data/repositories/repositories_module.dart b/lib/data/repositories/repositories_module.dart index e69de29..0d6d0f9 100644 --- a/lib/data/repositories/repositories_module.dart +++ b/lib/data/repositories/repositories_module.dart @@ -0,0 +1,2 @@ +export 'auth_repository.dart'; +export 'auth_repository_impl.dart'; diff --git a/lib/domain/entities/auth_error_type.dart b/lib/domain/entities/auth_error_type.dart new file mode 100644 index 0000000..42c766e --- /dev/null +++ b/lib/domain/entities/auth_error_type.dart @@ -0,0 +1,9 @@ +enum AuthErrorType { + invalidCredentials, + emailAlreadyInUse, + weakPassword, + invalidEmail, + networkError, + tooManyRequests, + unknown, +} diff --git a/lib/domain/entities/auth_exception.dart b/lib/domain/entities/auth_exception.dart new file mode 100644 index 0000000..058a55b --- /dev/null +++ b/lib/domain/entities/auth_exception.dart @@ -0,0 +1,11 @@ +import 'auth_error_type.dart'; + +class AuthException implements Exception { + final AuthErrorType type; + final String message; + + const AuthException({required this.type, required this.message}); + + @override + String toString() => 'AuthException($type): $message'; +} diff --git a/lib/domain/entities/auth_user.dart b/lib/domain/entities/auth_user.dart new file mode 100644 index 0000000..cbcd187 --- /dev/null +++ b/lib/domain/entities/auth_user.dart @@ -0,0 +1,22 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +import '../../data/data_module.dart'; + +part 'auth_user.freezed.dart'; + +@freezed +sealed class AuthUser with _$AuthUser { + const factory AuthUser({ + required String uid, + required String email, + String? displayName, + required bool isEmailVerified, + }) = _AuthUser; + + factory AuthUser.fromDto(AuthUserDto dto) => AuthUser( + uid: dto.uid, + email: dto.email ?? '', + displayName: dto.displayName, + isEmailVerified: dto.isEmailVerified, + ); +} diff --git a/lib/domain/entities/auth_user.freezed.dart b/lib/domain/entities/auth_user.freezed.dart new file mode 100644 index 0000000..fb9d236 --- /dev/null +++ b/lib/domain/entities/auth_user.freezed.dart @@ -0,0 +1,274 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'auth_user.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// dart format off +T _$identity(T value) => value; +/// @nodoc +mixin _$AuthUser { + + String get uid; String get email; String? get displayName; bool get isEmailVerified; +/// Create a copy of AuthUser +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$AuthUserCopyWith get copyWith => _$AuthUserCopyWithImpl(this as AuthUser, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is AuthUser&&(identical(other.uid, uid) || other.uid == uid)&&(identical(other.email, email) || other.email == email)&&(identical(other.displayName, displayName) || other.displayName == displayName)&&(identical(other.isEmailVerified, isEmailVerified) || other.isEmailVerified == isEmailVerified)); +} + + +@override +int get hashCode => Object.hash(runtimeType,uid,email,displayName,isEmailVerified); + +@override +String toString() { + return 'AuthUser(uid: $uid, email: $email, displayName: $displayName, isEmailVerified: $isEmailVerified)'; +} + + +} + +/// @nodoc +abstract mixin class $AuthUserCopyWith<$Res> { + factory $AuthUserCopyWith(AuthUser value, $Res Function(AuthUser) _then) = _$AuthUserCopyWithImpl; +@useResult +$Res call({ + String uid, String email, String? displayName, bool isEmailVerified +}); + + + + +} +/// @nodoc +class _$AuthUserCopyWithImpl<$Res> + implements $AuthUserCopyWith<$Res> { + _$AuthUserCopyWithImpl(this._self, this._then); + + final AuthUser _self; + final $Res Function(AuthUser) _then; + +/// Create a copy of AuthUser +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? uid = null,Object? email = null,Object? displayName = freezed,Object? isEmailVerified = null,}) { + return _then(_self.copyWith( +uid: null == uid ? _self.uid : uid // ignore: cast_nullable_to_non_nullable +as String,email: null == email ? _self.email : email // ignore: cast_nullable_to_non_nullable +as String,displayName: freezed == displayName ? _self.displayName : displayName // ignore: cast_nullable_to_non_nullable +as String?,isEmailVerified: null == isEmailVerified ? _self.isEmailVerified : isEmailVerified // ignore: cast_nullable_to_non_nullable +as bool, + )); +} + +} + + +/// Adds pattern-matching-related methods to [AuthUser]. +extension AuthUserPatterns on AuthUser { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap(TResult Function( _AuthUser value)? $default,{required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _AuthUser() when $default != null: +return $default(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(TResult Function( _AuthUser value) $default,){ +final _that = this; +switch (_that) { +case _AuthUser(): +return $default(_that);} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(TResult? Function( _AuthUser value)? $default,){ +final _that = this; +switch (_that) { +case _AuthUser() when $default != null: +return $default(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen(TResult Function( String uid, String email, String? displayName, bool isEmailVerified)? $default,{required TResult orElse(),}) {final _that = this; +switch (_that) { +case _AuthUser() when $default != null: +return $default(_that.uid,_that.email,_that.displayName,_that.isEmailVerified);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when(TResult Function( String uid, String email, String? displayName, bool isEmailVerified) $default,) {final _that = this; +switch (_that) { +case _AuthUser(): +return $default(_that.uid,_that.email,_that.displayName,_that.isEmailVerified);} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull(TResult? Function( String uid, String email, String? displayName, bool isEmailVerified)? $default,) {final _that = this; +switch (_that) { +case _AuthUser() when $default != null: +return $default(_that.uid,_that.email,_that.displayName,_that.isEmailVerified);case _: + return null; + +} +} + +} + +/// @nodoc + + +class _AuthUser implements AuthUser { + const _AuthUser({required this.uid, required this.email, this.displayName, required this.isEmailVerified}); + + +@override final String uid; +@override final String email; +@override final String? displayName; +@override final bool isEmailVerified; + +/// Create a copy of AuthUser +/// with the given fields replaced by the non-null parameter values. +@override @JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +_$AuthUserCopyWith<_AuthUser> get copyWith => __$AuthUserCopyWithImpl<_AuthUser>(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is _AuthUser&&(identical(other.uid, uid) || other.uid == uid)&&(identical(other.email, email) || other.email == email)&&(identical(other.displayName, displayName) || other.displayName == displayName)&&(identical(other.isEmailVerified, isEmailVerified) || other.isEmailVerified == isEmailVerified)); +} + + +@override +int get hashCode => Object.hash(runtimeType,uid,email,displayName,isEmailVerified); + +@override +String toString() { + return 'AuthUser(uid: $uid, email: $email, displayName: $displayName, isEmailVerified: $isEmailVerified)'; +} + + +} + +/// @nodoc +abstract mixin class _$AuthUserCopyWith<$Res> implements $AuthUserCopyWith<$Res> { + factory _$AuthUserCopyWith(_AuthUser value, $Res Function(_AuthUser) _then) = __$AuthUserCopyWithImpl; +@override @useResult +$Res call({ + String uid, String email, String? displayName, bool isEmailVerified +}); + + + + +} +/// @nodoc +class __$AuthUserCopyWithImpl<$Res> + implements _$AuthUserCopyWith<$Res> { + __$AuthUserCopyWithImpl(this._self, this._then); + + final _AuthUser _self; + final $Res Function(_AuthUser) _then; + +/// Create a copy of AuthUser +/// with the given fields replaced by the non-null parameter values. +@override @pragma('vm:prefer-inline') $Res call({Object? uid = null,Object? email = null,Object? displayName = freezed,Object? isEmailVerified = null,}) { + return _then(_AuthUser( +uid: null == uid ? _self.uid : uid // ignore: cast_nullable_to_non_nullable +as String,email: null == email ? _self.email : email // ignore: cast_nullable_to_non_nullable +as String,displayName: freezed == displayName ? _self.displayName : displayName // ignore: cast_nullable_to_non_nullable +as String?,isEmailVerified: null == isEmailVerified ? _self.isEmailVerified : isEmailVerified // ignore: cast_nullable_to_non_nullable +as bool, + )); +} + + +} + +// dart format on diff --git a/lib/domain/entities/entities_module.dart b/lib/domain/entities/entities_module.dart index e69de29..8bbc234 100644 --- a/lib/domain/entities/entities_module.dart +++ b/lib/domain/entities/entities_module.dart @@ -0,0 +1,3 @@ +export 'auth_error_type.dart'; +export 'auth_exception.dart'; +export 'auth_user.dart'; diff --git a/lib/domain/usecases/auth/auth_usecases_module.dart b/lib/domain/usecases/auth/auth_usecases_module.dart new file mode 100644 index 0000000..6f4eb39 --- /dev/null +++ b/lib/domain/usecases/auth/auth_usecases_module.dart @@ -0,0 +1,5 @@ +export 'reset_password_use_case.dart'; +export 'sign_in_use_case.dart'; +export 'sign_out_use_case.dart'; +export 'sign_up_use_case.dart'; +export 'watch_auth_state_use_case.dart'; diff --git a/lib/domain/usecases/auth/reset_password_use_case.dart b/lib/domain/usecases/auth/reset_password_use_case.dart new file mode 100644 index 0000000..32fc0b8 --- /dev/null +++ b/lib/domain/usecases/auth/reset_password_use_case.dart @@ -0,0 +1,13 @@ +import 'package:injectable/injectable.dart'; + +import '../../../data/data_module.dart'; + +@singleton +class ResetPasswordUseCase { + final AuthRepository _authRepository; + + ResetPasswordUseCase(this._authRepository); + + Stream call(String email) => + _authRepository.sendPasswordResetEmail(email); +} diff --git a/lib/domain/usecases/auth/sign_in_use_case.dart b/lib/domain/usecases/auth/sign_in_use_case.dart new file mode 100644 index 0000000..efbc82a --- /dev/null +++ b/lib/domain/usecases/auth/sign_in_use_case.dart @@ -0,0 +1,14 @@ +import 'package:injectable/injectable.dart'; + +import '../../../data/data_module.dart'; +import '../../domain_module.dart'; + +@singleton +class SignInUseCase { + final AuthRepository _authRepository; + + SignInUseCase(this._authRepository); + + Stream call(String email, String password) => + _authRepository.signIn(email, password); +} diff --git a/lib/domain/usecases/auth/sign_out_use_case.dart b/lib/domain/usecases/auth/sign_out_use_case.dart new file mode 100644 index 0000000..6329de8 --- /dev/null +++ b/lib/domain/usecases/auth/sign_out_use_case.dart @@ -0,0 +1,12 @@ +import 'package:injectable/injectable.dart'; + +import '../../../data/data_module.dart'; + +@singleton +class SignOutUseCase { + final AuthRepository _authRepository; + + SignOutUseCase(this._authRepository); + + Stream call() => _authRepository.signOut(); +} diff --git a/lib/domain/usecases/auth/sign_up_use_case.dart b/lib/domain/usecases/auth/sign_up_use_case.dart new file mode 100644 index 0000000..888cd02 --- /dev/null +++ b/lib/domain/usecases/auth/sign_up_use_case.dart @@ -0,0 +1,38 @@ +import 'package:injectable/injectable.dart'; + +import '../../../data/data_module.dart'; +import '../../domain_module.dart'; + +@singleton +class SignUpUseCase { + final AuthRepository _authRepository; + + SignUpUseCase(this._authRepository); + + Stream call(String email, String password) { + final validationError = _validatePassword(password); + if (validationError != null) { + return Stream.error(AuthException( + type: AuthErrorType.weakPassword, + message: validationError, + )); + } + return _authRepository.signUp(email, password); + } + + String? _validatePassword(String password) { + if (password.length < 8) { + return 'Password must be at least 8 characters long.'; + } + if (!password.contains(RegExp(r'[A-Z]'))) { + return 'Password must contain at least one uppercase letter.'; + } + if (!password.contains(RegExp(r'[a-z]'))) { + return 'Password must contain at least one lowercase letter.'; + } + if (!password.contains(RegExp(r'[0-9]'))) { + return 'Password must contain at least one digit.'; + } + return null; + } +} diff --git a/lib/domain/usecases/auth/watch_auth_state_use_case.dart b/lib/domain/usecases/auth/watch_auth_state_use_case.dart new file mode 100644 index 0000000..ebb055c --- /dev/null +++ b/lib/domain/usecases/auth/watch_auth_state_use_case.dart @@ -0,0 +1,13 @@ +import 'package:injectable/injectable.dart'; + +import '../../../data/data_module.dart'; +import '../../domain_module.dart'; + +@singleton +class WatchAuthStateUseCase { + final AuthRepository _authRepository; + + WatchAuthStateUseCase(this._authRepository); + + Stream call() => _authRepository.watchAuthState(); +} diff --git a/lib/domain/usecases/usecases_module.dart b/lib/domain/usecases/usecases_module.dart index e69de29..062e0eb 100644 --- a/lib/domain/usecases/usecases_module.dart +++ b/lib/domain/usecases/usecases_module.dart @@ -0,0 +1 @@ +export 'auth/auth_usecases_module.dart'; diff --git a/lib/firebase_options.dart b/lib/firebase_options.dart new file mode 100644 index 0000000..f893792 --- /dev/null +++ b/lib/firebase_options.dart @@ -0,0 +1,86 @@ +// File generated by FlutterFire CLI. +// ignore_for_file: type=lint +import 'package:firebase_core/firebase_core.dart' show FirebaseOptions; +import 'package:flutter/foundation.dart' + show defaultTargetPlatform, kIsWeb, TargetPlatform; + +/// Default [FirebaseOptions] for use with your Firebase apps. +/// +/// Example: +/// ```dart +/// import 'firebase_options.dart'; +/// // ... +/// await Firebase.initializeApp( +/// options: DefaultFirebaseOptions.currentPlatform, +/// ); +/// ``` +class DefaultFirebaseOptions { + static FirebaseOptions get currentPlatform { + if (kIsWeb) { + return web; + } + switch (defaultTargetPlatform) { + case TargetPlatform.android: + return android; + case TargetPlatform.iOS: + return ios; + case TargetPlatform.macOS: + return macos; + case TargetPlatform.windows: + return windows; + case TargetPlatform.linux: + throw UnsupportedError( + 'DefaultFirebaseOptions have not been configured for linux - ' + 'you can reconfigure this by running the FlutterFire CLI again.', + ); + default: + throw UnsupportedError( + 'DefaultFirebaseOptions are not supported for this platform.', + ); + } + } + + static const FirebaseOptions web = FirebaseOptions( + apiKey: 'AIzaSyB1nXkBCvkriBna1khoWQz_JxfNb794NpM', + appId: '1:575974943870:web:470ce703d47392208e3c2f', + messagingSenderId: '575974943870', + projectId: 'ff-kit', + authDomain: 'ff-kit.firebaseapp.com', + storageBucket: 'ff-kit.firebasestorage.app', + ); + + static const FirebaseOptions android = FirebaseOptions( + apiKey: 'AIzaSyCRU89MM99PM1SHyooDUUxj-F2fHz6rggM', + appId: '1:575974943870:android:0a3cd7cebe67e0398e3c2f', + messagingSenderId: '575974943870', + projectId: 'ff-kit', + storageBucket: 'ff-kit.firebasestorage.app', + ); + + static const FirebaseOptions ios = FirebaseOptions( + apiKey: 'AIzaSyCT5QclXtOTZQG00LXXCBoBXJeIUKe3p2o', + appId: '1:575974943870:ios:fee7b78e909f25528e3c2f', + messagingSenderId: '575974943870', + projectId: 'ff-kit', + storageBucket: 'ff-kit.firebasestorage.app', + iosBundleId: 'fr.benoitfontaine.starter.recette', + ); + + static const FirebaseOptions macos = FirebaseOptions( + apiKey: 'AIzaSyCT5QclXtOTZQG00LXXCBoBXJeIUKe3p2o', + appId: '1:575974943870:ios:7d87f82d470fc9368e3c2f', + messagingSenderId: '575974943870', + projectId: 'ff-kit', + storageBucket: 'ff-kit.firebasestorage.app', + iosBundleId: 'pro.listo.flutterStarterKit', + ); + + static const FirebaseOptions windows = FirebaseOptions( + apiKey: 'AIzaSyB1nXkBCvkriBna1khoWQz_JxfNb794NpM', + appId: '1:575974943870:web:261266ae01ca1e0a8e3c2f', + messagingSenderId: '575974943870', + projectId: 'ff-kit', + authDomain: 'ff-kit.firebaseapp.com', + storageBucket: 'ff-kit.firebasestorage.app', + ); +} diff --git a/lib/injection.config.dart b/lib/injection.config.dart index 913eaad..c122d0a 100644 --- a/lib/injection.config.dart +++ b/lib/injection.config.dart @@ -12,6 +12,10 @@ import 'package:get_it/get_it.dart' as _i174; import 'package:injectable/injectable.dart' as _i526; +import 'core/core_module.dart' as _i1039; +import 'core/di/auth/auth_module.dart' as _i858; +import 'core/di/auth/auth_module_impl.dart' as _i903; +import 'core/di/auth/auth_module_stub.dart' as _i908; import 'core/di/configuration/configuration.dart' as _i459; import 'core/di/configuration/configuration_dev.dart' as _i404; import 'core/di/configuration/configuration_integration.dart' as _i711; @@ -22,6 +26,17 @@ import 'core/di/configuration/configuration_test.dart' as _i595; import 'core/di/di_module.dart' as _i268; import 'core/di/network/api_module_impl.dart' as _i1022; import 'core/di/network/api_module_stub.dart' as _i763; +import 'data/data_module.dart' as _i947; +import 'data/repositories/auth_repository.dart' as _i593; +import 'data/repositories/auth_repository_impl.dart' as _i145; +import 'domain/domain_module.dart' as _i230; +import 'domain/usecases/auth/reset_password_use_case.dart' as _i697; +import 'domain/usecases/auth/sign_in_use_case.dart' as _i784; +import 'domain/usecases/auth/sign_out_use_case.dart' as _i360; +import 'domain/usecases/auth/sign_up_use_case.dart' as _i977; +import 'domain/usecases/auth/watch_auth_state_use_case.dart' as _i955; +import 'ui/auth/auth_interactor.dart' as _i893; +import 'ui/auth/auth_module.dart' as _i57; import 'ui/router.dart' as _i766; const String _dev = 'dev'; @@ -62,18 +77,56 @@ extension GetItInjectableX on _i174.GetIt { () => _i575.ConfigurationDev(), registerFor: {_preprod}, ); - gh.singleton<_i766.AppRouter>( - () => _i766.AppRouter(), - dispose: (i) => i.dispose(), + gh.singleton<_i858.AuthModule>( + () => _i908.AuthModuleStub(), + registerFor: {_test}, ); gh.singleton<_i268.ApiModule>( () => _i763.ApiModuleImpl(gh<_i268.Configuration>()), registerFor: {_test}, ); + gh.singleton<_i858.AuthModule>( + () => _i903.AuthModuleImpl(), + registerFor: {_dev, _integration, _recette, _preprod, _prod}, + ); + gh.singleton<_i766.AppRouter>( + () => _i766.AppRouter(gh<_i1039.AuthModule>()), + dispose: (i) => i.dispose(), + ); + gh.factory<_i593.AuthRepository>( + () => _i145.AuthRepositoryImpl(gh<_i1039.AuthModule>()), + ); + gh.singleton<_i57.AuthUiModule>( + () => _i57.AuthUiModule(gh<_i766.AppRouter>()), + ); gh.singleton<_i268.ApiModule>( () => _i1022.ApiModuleImpl(gh<_i268.Configuration>()), registerFor: {_dev, _integration, _recette, _preprod, _prod}, ); + gh.singleton<_i697.ResetPasswordUseCase>( + () => _i697.ResetPasswordUseCase(gh<_i947.AuthRepository>()), + ); + gh.singleton<_i784.SignInUseCase>( + () => _i784.SignInUseCase(gh<_i947.AuthRepository>()), + ); + gh.singleton<_i360.SignOutUseCase>( + () => _i360.SignOutUseCase(gh<_i947.AuthRepository>()), + ); + gh.singleton<_i977.SignUpUseCase>( + () => _i977.SignUpUseCase(gh<_i947.AuthRepository>()), + ); + gh.singleton<_i955.WatchAuthStateUseCase>( + () => _i955.WatchAuthStateUseCase(gh<_i947.AuthRepository>()), + ); + gh.singleton<_i893.AuthInteractor>( + () => _i893.AuthInteractor( + gh<_i230.SignUpUseCase>(), + gh<_i230.SignInUseCase>(), + gh<_i230.ResetPasswordUseCase>(), + gh<_i230.SignOutUseCase>(), + gh<_i230.WatchAuthStateUseCase>(), + ), + ); return this; } } diff --git a/lib/main.dart b/lib/main.dart index 99c65db..9834976 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,17 +1,20 @@ import 'dart:async'; +import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:flutter/semantics.dart'; import 'package:flutter_web_plugins/url_strategy.dart'; import 'package:intl/date_symbol_data_local.dart'; import 'package:intl/intl.dart'; +import 'firebase_options.dart'; import 'injection.dart'; import 'ui/app.dart'; FutureOr main() async { usePathUrlStrategy(); WidgetsFlutterBinding.ensureInitialized(); + await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); SemanticsBinding.instance.ensureSemantics(); Intl.defaultLocale = 'fr_FR'; await initializeDateFormatting('fr_FR', null); diff --git a/lib/ui/auth/auth_bloc.dart b/lib/ui/auth/auth_bloc.dart new file mode 100644 index 0000000..60e8d04 --- /dev/null +++ b/lib/ui/auth/auth_bloc.dart @@ -0,0 +1,96 @@ +import 'dart:async'; + +import 'package:flutter_bloc/flutter_bloc.dart'; + +import '../../domain/domain_module.dart'; +import 'auth_event.dart'; +import 'auth_interactor.dart'; +import 'auth_state.dart'; + +class AuthBloc extends Bloc { + final AuthInteractor _interactor; + StreamSubscription? _authStateSubscription; + + AuthBloc(this._interactor) : super(const AuthState.initial()) { + on(_onSignUpRequested); + on(_onSignInRequested); + on(_onResetPasswordRequested); + on(_onSignOutRequested); + on(_onAuthStateChanged); + + _authStateSubscription = _interactor.watchAuthState().listen( + (user) => add(AuthEvent.authStateChanged(user: user)), + ); + } + + @override + Future close() { + _authStateSubscription?.cancel(); + return super.close(); + } + + Future _onSignUpRequested( + SignUpRequested event, + Emitter emit, + ) async { + emit(const AuthState.loading()); + try { + await for (final user in _interactor.signUp(event.email, event.password)) { + emit(AuthState.authenticated(user: user)); + } + } on AuthException catch (e) { + emit(AuthState.error(type: e.type, message: e.message)); + } + } + + Future _onSignInRequested( + SignInRequested event, + Emitter emit, + ) async { + emit(const AuthState.loading()); + try { + await for (final user in _interactor.signIn(event.email, event.password)) { + emit(AuthState.authenticated(user: user)); + } + } on AuthException catch (e) { + emit(AuthState.error(type: e.type, message: e.message)); + } + } + + Future _onResetPasswordRequested( + ResetPasswordRequested event, + Emitter emit, + ) async { + emit(const AuthState.loading()); + try { + await for (final _ in _interactor.resetPassword(event.email)) {} + emit(const AuthState.unauthenticated()); + } on AuthException catch (e) { + emit(AuthState.error(type: e.type, message: e.message)); + } + } + + Future _onSignOutRequested( + SignOutRequested event, + Emitter emit, + ) async { + emit(const AuthState.loading()); + try { + await for (final _ in _interactor.signOut()) {} + emit(const AuthState.unauthenticated()); + } on AuthException catch (e) { + emit(AuthState.error(type: e.type, message: e.message)); + } + } + + void _onAuthStateChanged( + AuthStateChanged event, + Emitter emit, + ) { + if (event.user != null) { + emit(AuthState.authenticated(user: event.user!)); + } else { + emit(const AuthState.unauthenticated()); + } + } +} diff --git a/lib/ui/auth/auth_event.dart b/lib/ui/auth/auth_event.dart new file mode 100644 index 0000000..1f3f3c9 --- /dev/null +++ b/lib/ui/auth/auth_event.dart @@ -0,0 +1,28 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +import '../../domain/domain_module.dart'; + +part 'auth_event.freezed.dart'; + +@freezed +sealed class AuthEvent with _$AuthEvent { + const factory AuthEvent.signUpRequested({ + required String email, + required String password, + }) = SignUpRequested; + + const factory AuthEvent.signInRequested({ + required String email, + required String password, + }) = SignInRequested; + + const factory AuthEvent.signOutRequested() = SignOutRequested; + + const factory AuthEvent.resetPasswordRequested({ + required String email, + }) = ResetPasswordRequested; + + const factory AuthEvent.authStateChanged({ + AuthUser? user, + }) = AuthStateChanged; +} diff --git a/lib/ui/auth/auth_event.freezed.dart b/lib/ui/auth/auth_event.freezed.dart new file mode 100644 index 0000000..3d90a5f --- /dev/null +++ b/lib/ui/auth/auth_event.freezed.dart @@ -0,0 +1,504 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'auth_event.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// dart format off +T _$identity(T value) => value; +/// @nodoc +mixin _$AuthEvent { + + + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is AuthEvent); +} + + +@override +int get hashCode => runtimeType.hashCode; + +@override +String toString() { + return 'AuthEvent()'; +} + + +} + +/// @nodoc +class $AuthEventCopyWith<$Res> { +$AuthEventCopyWith(AuthEvent _, $Res Function(AuthEvent) __); +} + + +/// Adds pattern-matching-related methods to [AuthEvent]. +extension AuthEventPatterns on AuthEvent { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap({TResult Function( SignUpRequested value)? signUpRequested,TResult Function( SignInRequested value)? signInRequested,TResult Function( SignOutRequested value)? signOutRequested,TResult Function( ResetPasswordRequested value)? resetPasswordRequested,TResult Function( AuthStateChanged value)? authStateChanged,required TResult orElse(),}){ +final _that = this; +switch (_that) { +case SignUpRequested() when signUpRequested != null: +return signUpRequested(_that);case SignInRequested() when signInRequested != null: +return signInRequested(_that);case SignOutRequested() when signOutRequested != null: +return signOutRequested(_that);case ResetPasswordRequested() when resetPasswordRequested != null: +return resetPasswordRequested(_that);case AuthStateChanged() when authStateChanged != null: +return authStateChanged(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map({required TResult Function( SignUpRequested value) signUpRequested,required TResult Function( SignInRequested value) signInRequested,required TResult Function( SignOutRequested value) signOutRequested,required TResult Function( ResetPasswordRequested value) resetPasswordRequested,required TResult Function( AuthStateChanged value) authStateChanged,}){ +final _that = this; +switch (_that) { +case SignUpRequested(): +return signUpRequested(_that);case SignInRequested(): +return signInRequested(_that);case SignOutRequested(): +return signOutRequested(_that);case ResetPasswordRequested(): +return resetPasswordRequested(_that);case AuthStateChanged(): +return authStateChanged(_that);} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull({TResult? Function( SignUpRequested value)? signUpRequested,TResult? Function( SignInRequested value)? signInRequested,TResult? Function( SignOutRequested value)? signOutRequested,TResult? Function( ResetPasswordRequested value)? resetPasswordRequested,TResult? Function( AuthStateChanged value)? authStateChanged,}){ +final _that = this; +switch (_that) { +case SignUpRequested() when signUpRequested != null: +return signUpRequested(_that);case SignInRequested() when signInRequested != null: +return signInRequested(_that);case SignOutRequested() when signOutRequested != null: +return signOutRequested(_that);case ResetPasswordRequested() when resetPasswordRequested != null: +return resetPasswordRequested(_that);case AuthStateChanged() when authStateChanged != null: +return authStateChanged(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen({TResult Function( String email, String password)? signUpRequested,TResult Function( String email, String password)? signInRequested,TResult Function()? signOutRequested,TResult Function( String email)? resetPasswordRequested,TResult Function( AuthUser? user)? authStateChanged,required TResult orElse(),}) {final _that = this; +switch (_that) { +case SignUpRequested() when signUpRequested != null: +return signUpRequested(_that.email,_that.password);case SignInRequested() when signInRequested != null: +return signInRequested(_that.email,_that.password);case SignOutRequested() when signOutRequested != null: +return signOutRequested();case ResetPasswordRequested() when resetPasswordRequested != null: +return resetPasswordRequested(_that.email);case AuthStateChanged() when authStateChanged != null: +return authStateChanged(_that.user);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when({required TResult Function( String email, String password) signUpRequested,required TResult Function( String email, String password) signInRequested,required TResult Function() signOutRequested,required TResult Function( String email) resetPasswordRequested,required TResult Function( AuthUser? user) authStateChanged,}) {final _that = this; +switch (_that) { +case SignUpRequested(): +return signUpRequested(_that.email,_that.password);case SignInRequested(): +return signInRequested(_that.email,_that.password);case SignOutRequested(): +return signOutRequested();case ResetPasswordRequested(): +return resetPasswordRequested(_that.email);case AuthStateChanged(): +return authStateChanged(_that.user);} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull({TResult? Function( String email, String password)? signUpRequested,TResult? Function( String email, String password)? signInRequested,TResult? Function()? signOutRequested,TResult? Function( String email)? resetPasswordRequested,TResult? Function( AuthUser? user)? authStateChanged,}) {final _that = this; +switch (_that) { +case SignUpRequested() when signUpRequested != null: +return signUpRequested(_that.email,_that.password);case SignInRequested() when signInRequested != null: +return signInRequested(_that.email,_that.password);case SignOutRequested() when signOutRequested != null: +return signOutRequested();case ResetPasswordRequested() when resetPasswordRequested != null: +return resetPasswordRequested(_that.email);case AuthStateChanged() when authStateChanged != null: +return authStateChanged(_that.user);case _: + return null; + +} +} + +} + +/// @nodoc + + +class SignUpRequested implements AuthEvent { + const SignUpRequested({required this.email, required this.password}); + + + final String email; + final String password; + +/// Create a copy of AuthEvent +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$SignUpRequestedCopyWith get copyWith => _$SignUpRequestedCopyWithImpl(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is SignUpRequested&&(identical(other.email, email) || other.email == email)&&(identical(other.password, password) || other.password == password)); +} + + +@override +int get hashCode => Object.hash(runtimeType,email,password); + +@override +String toString() { + return 'AuthEvent.signUpRequested(email: $email, password: $password)'; +} + + +} + +/// @nodoc +abstract mixin class $SignUpRequestedCopyWith<$Res> implements $AuthEventCopyWith<$Res> { + factory $SignUpRequestedCopyWith(SignUpRequested value, $Res Function(SignUpRequested) _then) = _$SignUpRequestedCopyWithImpl; +@useResult +$Res call({ + String email, String password +}); + + + + +} +/// @nodoc +class _$SignUpRequestedCopyWithImpl<$Res> + implements $SignUpRequestedCopyWith<$Res> { + _$SignUpRequestedCopyWithImpl(this._self, this._then); + + final SignUpRequested _self; + final $Res Function(SignUpRequested) _then; + +/// Create a copy of AuthEvent +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') $Res call({Object? email = null,Object? password = null,}) { + return _then(SignUpRequested( +email: null == email ? _self.email : email // ignore: cast_nullable_to_non_nullable +as String,password: null == password ? _self.password : password // ignore: cast_nullable_to_non_nullable +as String, + )); +} + + +} + +/// @nodoc + + +class SignInRequested implements AuthEvent { + const SignInRequested({required this.email, required this.password}); + + + final String email; + final String password; + +/// Create a copy of AuthEvent +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$SignInRequestedCopyWith get copyWith => _$SignInRequestedCopyWithImpl(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is SignInRequested&&(identical(other.email, email) || other.email == email)&&(identical(other.password, password) || other.password == password)); +} + + +@override +int get hashCode => Object.hash(runtimeType,email,password); + +@override +String toString() { + return 'AuthEvent.signInRequested(email: $email, password: $password)'; +} + + +} + +/// @nodoc +abstract mixin class $SignInRequestedCopyWith<$Res> implements $AuthEventCopyWith<$Res> { + factory $SignInRequestedCopyWith(SignInRequested value, $Res Function(SignInRequested) _then) = _$SignInRequestedCopyWithImpl; +@useResult +$Res call({ + String email, String password +}); + + + + +} +/// @nodoc +class _$SignInRequestedCopyWithImpl<$Res> + implements $SignInRequestedCopyWith<$Res> { + _$SignInRequestedCopyWithImpl(this._self, this._then); + + final SignInRequested _self; + final $Res Function(SignInRequested) _then; + +/// Create a copy of AuthEvent +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') $Res call({Object? email = null,Object? password = null,}) { + return _then(SignInRequested( +email: null == email ? _self.email : email // ignore: cast_nullable_to_non_nullable +as String,password: null == password ? _self.password : password // ignore: cast_nullable_to_non_nullable +as String, + )); +} + + +} + +/// @nodoc + + +class SignOutRequested implements AuthEvent { + const SignOutRequested(); + + + + + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is SignOutRequested); +} + + +@override +int get hashCode => runtimeType.hashCode; + +@override +String toString() { + return 'AuthEvent.signOutRequested()'; +} + + +} + + + + +/// @nodoc + + +class ResetPasswordRequested implements AuthEvent { + const ResetPasswordRequested({required this.email}); + + + final String email; + +/// Create a copy of AuthEvent +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$ResetPasswordRequestedCopyWith get copyWith => _$ResetPasswordRequestedCopyWithImpl(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is ResetPasswordRequested&&(identical(other.email, email) || other.email == email)); +} + + +@override +int get hashCode => Object.hash(runtimeType,email); + +@override +String toString() { + return 'AuthEvent.resetPasswordRequested(email: $email)'; +} + + +} + +/// @nodoc +abstract mixin class $ResetPasswordRequestedCopyWith<$Res> implements $AuthEventCopyWith<$Res> { + factory $ResetPasswordRequestedCopyWith(ResetPasswordRequested value, $Res Function(ResetPasswordRequested) _then) = _$ResetPasswordRequestedCopyWithImpl; +@useResult +$Res call({ + String email +}); + + + + +} +/// @nodoc +class _$ResetPasswordRequestedCopyWithImpl<$Res> + implements $ResetPasswordRequestedCopyWith<$Res> { + _$ResetPasswordRequestedCopyWithImpl(this._self, this._then); + + final ResetPasswordRequested _self; + final $Res Function(ResetPasswordRequested) _then; + +/// Create a copy of AuthEvent +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') $Res call({Object? email = null,}) { + return _then(ResetPasswordRequested( +email: null == email ? _self.email : email // ignore: cast_nullable_to_non_nullable +as String, + )); +} + + +} + +/// @nodoc + + +class AuthStateChanged implements AuthEvent { + const AuthStateChanged({this.user}); + + + final AuthUser? user; + +/// Create a copy of AuthEvent +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$AuthStateChangedCopyWith get copyWith => _$AuthStateChangedCopyWithImpl(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is AuthStateChanged&&(identical(other.user, user) || other.user == user)); +} + + +@override +int get hashCode => Object.hash(runtimeType,user); + +@override +String toString() { + return 'AuthEvent.authStateChanged(user: $user)'; +} + + +} + +/// @nodoc +abstract mixin class $AuthStateChangedCopyWith<$Res> implements $AuthEventCopyWith<$Res> { + factory $AuthStateChangedCopyWith(AuthStateChanged value, $Res Function(AuthStateChanged) _then) = _$AuthStateChangedCopyWithImpl; +@useResult +$Res call({ + AuthUser? user +}); + + +$AuthUserCopyWith<$Res>? get user; + +} +/// @nodoc +class _$AuthStateChangedCopyWithImpl<$Res> + implements $AuthStateChangedCopyWith<$Res> { + _$AuthStateChangedCopyWithImpl(this._self, this._then); + + final AuthStateChanged _self; + final $Res Function(AuthStateChanged) _then; + +/// Create a copy of AuthEvent +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') $Res call({Object? user = freezed,}) { + return _then(AuthStateChanged( +user: freezed == user ? _self.user : user // ignore: cast_nullable_to_non_nullable +as AuthUser?, + )); +} + +/// Create a copy of AuthEvent +/// with the given fields replaced by the non-null parameter values. +@override +@pragma('vm:prefer-inline') +$AuthUserCopyWith<$Res>? get user { + if (_self.user == null) { + return null; + } + + return $AuthUserCopyWith<$Res>(_self.user!, (value) { + return _then(_self.copyWith(user: value)); + }); +} +} + +// dart format on diff --git a/lib/ui/auth/auth_interactor.dart b/lib/ui/auth/auth_interactor.dart new file mode 100644 index 0000000..b097e10 --- /dev/null +++ b/lib/ui/auth/auth_interactor.dart @@ -0,0 +1,33 @@ +import 'package:injectable/injectable.dart'; + +import '../../domain/domain_module.dart'; + +@singleton +class AuthInteractor { + final SignUpUseCase _signUpUseCase; + final SignInUseCase _signInUseCase; + final ResetPasswordUseCase _resetPasswordUseCase; + final SignOutUseCase _signOutUseCase; + final WatchAuthStateUseCase _watchAuthStateUseCase; + + AuthInteractor( + this._signUpUseCase, + this._signInUseCase, + this._resetPasswordUseCase, + this._signOutUseCase, + this._watchAuthStateUseCase, + ); + + Stream signUp(String email, String password) => + _signUpUseCase(email, password); + + Stream signIn(String email, String password) => + _signInUseCase(email, password); + + Stream resetPassword(String email) => + _resetPasswordUseCase(email); + + Stream signOut() => _signOutUseCase(); + + Stream watchAuthState() => _watchAuthStateUseCase(); +} diff --git a/lib/ui/auth/auth_module.dart b/lib/ui/auth/auth_module.dart new file mode 100644 index 0000000..c117963 --- /dev/null +++ b/lib/ui/auth/auth_module.dart @@ -0,0 +1,19 @@ +import 'package:injectable/injectable.dart'; + +import '../router.dart'; +import 'view/forgot_password_page.dart'; +import 'view/login_page.dart'; + +@singleton +class AuthUiModule { + AuthUiModule(AppRouter appRouter) { + appRouter.addRoute( + path: '/login', + builder: (context, state) => const LoginPage(), + ); + appRouter.addRoute( + path: '/login/forgot-password', + builder: (context, state) => const ForgotPasswordPage(), + ); + } +} diff --git a/lib/ui/auth/auth_state.dart b/lib/ui/auth/auth_state.dart new file mode 100644 index 0000000..a1ccacf --- /dev/null +++ b/lib/ui/auth/auth_state.dart @@ -0,0 +1,18 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +import '../../domain/domain_module.dart'; + +part 'auth_state.freezed.dart'; + +@freezed +sealed class AuthState with _$AuthState { + const factory AuthState.initial() = AuthInitial; + const factory AuthState.loading() = AuthLoading; + const factory AuthState.authenticated({required AuthUser user}) = + AuthAuthenticated; + const factory AuthState.unauthenticated() = AuthUnauthenticated; + const factory AuthState.error({ + required AuthErrorType type, + required String message, + }) = AuthError; +} diff --git a/lib/ui/auth/auth_state.freezed.dart b/lib/ui/auth/auth_state.freezed.dart new file mode 100644 index 0000000..002481c --- /dev/null +++ b/lib/ui/auth/auth_state.freezed.dart @@ -0,0 +1,431 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'auth_state.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// dart format off +T _$identity(T value) => value; +/// @nodoc +mixin _$AuthState { + + + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is AuthState); +} + + +@override +int get hashCode => runtimeType.hashCode; + +@override +String toString() { + return 'AuthState()'; +} + + +} + +/// @nodoc +class $AuthStateCopyWith<$Res> { +$AuthStateCopyWith(AuthState _, $Res Function(AuthState) __); +} + + +/// Adds pattern-matching-related methods to [AuthState]. +extension AuthStatePatterns on AuthState { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap({TResult Function( AuthInitial value)? initial,TResult Function( AuthLoading value)? loading,TResult Function( AuthAuthenticated value)? authenticated,TResult Function( AuthUnauthenticated value)? unauthenticated,TResult Function( AuthError value)? error,required TResult orElse(),}){ +final _that = this; +switch (_that) { +case AuthInitial() when initial != null: +return initial(_that);case AuthLoading() when loading != null: +return loading(_that);case AuthAuthenticated() when authenticated != null: +return authenticated(_that);case AuthUnauthenticated() when unauthenticated != null: +return unauthenticated(_that);case AuthError() when error != null: +return error(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map({required TResult Function( AuthInitial value) initial,required TResult Function( AuthLoading value) loading,required TResult Function( AuthAuthenticated value) authenticated,required TResult Function( AuthUnauthenticated value) unauthenticated,required TResult Function( AuthError value) error,}){ +final _that = this; +switch (_that) { +case AuthInitial(): +return initial(_that);case AuthLoading(): +return loading(_that);case AuthAuthenticated(): +return authenticated(_that);case AuthUnauthenticated(): +return unauthenticated(_that);case AuthError(): +return error(_that);} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull({TResult? Function( AuthInitial value)? initial,TResult? Function( AuthLoading value)? loading,TResult? Function( AuthAuthenticated value)? authenticated,TResult? Function( AuthUnauthenticated value)? unauthenticated,TResult? Function( AuthError value)? error,}){ +final _that = this; +switch (_that) { +case AuthInitial() when initial != null: +return initial(_that);case AuthLoading() when loading != null: +return loading(_that);case AuthAuthenticated() when authenticated != null: +return authenticated(_that);case AuthUnauthenticated() when unauthenticated != null: +return unauthenticated(_that);case AuthError() when error != null: +return error(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen({TResult Function()? initial,TResult Function()? loading,TResult Function( AuthUser user)? authenticated,TResult Function()? unauthenticated,TResult Function( AuthErrorType type, String message)? error,required TResult orElse(),}) {final _that = this; +switch (_that) { +case AuthInitial() when initial != null: +return initial();case AuthLoading() when loading != null: +return loading();case AuthAuthenticated() when authenticated != null: +return authenticated(_that.user);case AuthUnauthenticated() when unauthenticated != null: +return unauthenticated();case AuthError() when error != null: +return error(_that.type,_that.message);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when({required TResult Function() initial,required TResult Function() loading,required TResult Function( AuthUser user) authenticated,required TResult Function() unauthenticated,required TResult Function( AuthErrorType type, String message) error,}) {final _that = this; +switch (_that) { +case AuthInitial(): +return initial();case AuthLoading(): +return loading();case AuthAuthenticated(): +return authenticated(_that.user);case AuthUnauthenticated(): +return unauthenticated();case AuthError(): +return error(_that.type,_that.message);} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull({TResult? Function()? initial,TResult? Function()? loading,TResult? Function( AuthUser user)? authenticated,TResult? Function()? unauthenticated,TResult? Function( AuthErrorType type, String message)? error,}) {final _that = this; +switch (_that) { +case AuthInitial() when initial != null: +return initial();case AuthLoading() when loading != null: +return loading();case AuthAuthenticated() when authenticated != null: +return authenticated(_that.user);case AuthUnauthenticated() when unauthenticated != null: +return unauthenticated();case AuthError() when error != null: +return error(_that.type,_that.message);case _: + return null; + +} +} + +} + +/// @nodoc + + +class AuthInitial implements AuthState { + const AuthInitial(); + + + + + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is AuthInitial); +} + + +@override +int get hashCode => runtimeType.hashCode; + +@override +String toString() { + return 'AuthState.initial()'; +} + + +} + + + + +/// @nodoc + + +class AuthLoading implements AuthState { + const AuthLoading(); + + + + + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is AuthLoading); +} + + +@override +int get hashCode => runtimeType.hashCode; + +@override +String toString() { + return 'AuthState.loading()'; +} + + +} + + + + +/// @nodoc + + +class AuthAuthenticated implements AuthState { + const AuthAuthenticated({required this.user}); + + + final AuthUser user; + +/// Create a copy of AuthState +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$AuthAuthenticatedCopyWith get copyWith => _$AuthAuthenticatedCopyWithImpl(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is AuthAuthenticated&&(identical(other.user, user) || other.user == user)); +} + + +@override +int get hashCode => Object.hash(runtimeType,user); + +@override +String toString() { + return 'AuthState.authenticated(user: $user)'; +} + + +} + +/// @nodoc +abstract mixin class $AuthAuthenticatedCopyWith<$Res> implements $AuthStateCopyWith<$Res> { + factory $AuthAuthenticatedCopyWith(AuthAuthenticated value, $Res Function(AuthAuthenticated) _then) = _$AuthAuthenticatedCopyWithImpl; +@useResult +$Res call({ + AuthUser user +}); + + +$AuthUserCopyWith<$Res> get user; + +} +/// @nodoc +class _$AuthAuthenticatedCopyWithImpl<$Res> + implements $AuthAuthenticatedCopyWith<$Res> { + _$AuthAuthenticatedCopyWithImpl(this._self, this._then); + + final AuthAuthenticated _self; + final $Res Function(AuthAuthenticated) _then; + +/// Create a copy of AuthState +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') $Res call({Object? user = null,}) { + return _then(AuthAuthenticated( +user: null == user ? _self.user : user // ignore: cast_nullable_to_non_nullable +as AuthUser, + )); +} + +/// Create a copy of AuthState +/// with the given fields replaced by the non-null parameter values. +@override +@pragma('vm:prefer-inline') +$AuthUserCopyWith<$Res> get user { + + return $AuthUserCopyWith<$Res>(_self.user, (value) { + return _then(_self.copyWith(user: value)); + }); +} +} + +/// @nodoc + + +class AuthUnauthenticated implements AuthState { + const AuthUnauthenticated(); + + + + + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is AuthUnauthenticated); +} + + +@override +int get hashCode => runtimeType.hashCode; + +@override +String toString() { + return 'AuthState.unauthenticated()'; +} + + +} + + + + +/// @nodoc + + +class AuthError implements AuthState { + const AuthError({required this.type, required this.message}); + + + final AuthErrorType type; + final String message; + +/// Create a copy of AuthState +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$AuthErrorCopyWith get copyWith => _$AuthErrorCopyWithImpl(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is AuthError&&(identical(other.type, type) || other.type == type)&&(identical(other.message, message) || other.message == message)); +} + + +@override +int get hashCode => Object.hash(runtimeType,type,message); + +@override +String toString() { + return 'AuthState.error(type: $type, message: $message)'; +} + + +} + +/// @nodoc +abstract mixin class $AuthErrorCopyWith<$Res> implements $AuthStateCopyWith<$Res> { + factory $AuthErrorCopyWith(AuthError value, $Res Function(AuthError) _then) = _$AuthErrorCopyWithImpl; +@useResult +$Res call({ + AuthErrorType type, String message +}); + + + + +} +/// @nodoc +class _$AuthErrorCopyWithImpl<$Res> + implements $AuthErrorCopyWith<$Res> { + _$AuthErrorCopyWithImpl(this._self, this._then); + + final AuthError _self; + final $Res Function(AuthError) _then; + +/// Create a copy of AuthState +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') $Res call({Object? type = null,Object? message = null,}) { + return _then(AuthError( +type: null == type ? _self.type : type // ignore: cast_nullable_to_non_nullable +as AuthErrorType,message: null == message ? _self.message : message // ignore: cast_nullable_to_non_nullable +as String, + )); +} + + +} + +// dart format on diff --git a/lib/ui/auth/view/components/auth_email_field.dart b/lib/ui/auth/view/components/auth_email_field.dart new file mode 100644 index 0000000..0dd5f08 --- /dev/null +++ b/lib/ui/auth/view/components/auth_email_field.dart @@ -0,0 +1,37 @@ +import 'package:flutter/material.dart'; + +class AuthEmailField extends StatelessWidget { + final TextEditingController controller; + final String? errorText; + + const AuthEmailField({ + super.key, + required this.controller, + this.errorText, + }); + + @override + Widget build(BuildContext context) { + return TextFormField( + controller: controller, + keyboardType: TextInputType.emailAddress, + autocorrect: false, + decoration: InputDecoration( + labelText: 'Email', + hintText: 'example@email.com', + errorText: errorText, + prefixIcon: const Icon(Icons.email_outlined), + ), + validator: (value) { + if (value == null || value.isEmpty) { + return 'Please enter your email address.'; + } + final emailRegex = RegExp(r'^[^@\s]+@[^@\s]+\.[^@\s]+$'); + if (!emailRegex.hasMatch(value)) { + return 'Please enter a valid email address.'; + } + return null; + }, + ); + } +} diff --git a/lib/ui/auth/view/components/auth_password_field.dart b/lib/ui/auth/view/components/auth_password_field.dart new file mode 100644 index 0000000..895903e --- /dev/null +++ b/lib/ui/auth/view/components/auth_password_field.dart @@ -0,0 +1,59 @@ +import 'package:flutter/material.dart'; + +class AuthPasswordField extends StatefulWidget { + final TextEditingController controller; + final String? errorText; + final bool showValidationHints; + + const AuthPasswordField({ + super.key, + required this.controller, + this.errorText, + this.showValidationHints = false, + }); + + @override + State createState() => _AuthPasswordFieldState(); +} + +class _AuthPasswordFieldState extends State { + bool _obscureText = true; + + @override + Widget build(BuildContext context) { + return TextFormField( + controller: widget.controller, + obscureText: _obscureText, + decoration: InputDecoration( + labelText: 'Password', + errorText: widget.errorText, + prefixIcon: const Icon(Icons.lock_outlined), + suffixIcon: IconButton( + icon: Icon(_obscureText ? Icons.visibility : Icons.visibility_off), + onPressed: () => setState(() => _obscureText = !_obscureText), + ), + helperText: widget.showValidationHints + ? '8+ characters, uppercase, lowercase, digit' + : null, + ), + validator: (value) { + if (value == null || value.isEmpty) { + return 'Please enter a password.'; + } + if (widget.showValidationHints) { + if (value.length < 8) return 'At least 8 characters required.'; + if (!value.contains(RegExp(r'[A-Z]'))) { + return 'At least one uppercase letter required.'; + } + if (!value.contains(RegExp(r'[a-z]'))) { + return 'At least one lowercase letter required.'; + } + if (!value.contains(RegExp(r'[0-9]'))) { + return 'At least one digit required.'; + } + } + return null; + }, + ); + } +} diff --git a/lib/ui/auth/view/components/auth_submit_button.dart b/lib/ui/auth/view/components/auth_submit_button.dart new file mode 100644 index 0000000..254e4a4 --- /dev/null +++ b/lib/ui/auth/view/components/auth_submit_button.dart @@ -0,0 +1,31 @@ +import 'package:flutter/material.dart'; + +class AuthSubmitButton extends StatelessWidget { + final String label; + final bool isLoading; + final VoidCallback? onPressed; + + const AuthSubmitButton({ + super.key, + required this.label, + this.isLoading = false, + this.onPressed, + }); + + @override + Widget build(BuildContext context) { + return SizedBox( + width: double.infinity, + child: ElevatedButton( + onPressed: isLoading ? null : onPressed, + child: isLoading + ? const SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : Text(label), + ), + ); + } +} diff --git a/lib/ui/auth/view/forgot_password_page.dart b/lib/ui/auth/view/forgot_password_page.dart new file mode 100644 index 0000000..b798503 --- /dev/null +++ b/lib/ui/auth/view/forgot_password_page.dart @@ -0,0 +1,19 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:get_it/get_it.dart'; + +import '../auth_bloc.dart'; +import '../auth_interactor.dart'; +import 'forgot_password_view.dart'; + +class ForgotPasswordPage extends StatelessWidget { + const ForgotPasswordPage({super.key}); + + @override + Widget build(BuildContext context) { + return BlocProvider( + create: (_) => AuthBloc(GetIt.instance()), + child: const ForgotPasswordView(), + ); + } +} diff --git a/lib/ui/auth/view/forgot_password_view.dart b/lib/ui/auth/view/forgot_password_view.dart new file mode 100644 index 0000000..e7adec0 --- /dev/null +++ b/lib/ui/auth/view/forgot_password_view.dart @@ -0,0 +1,116 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:go_router/go_router.dart'; + +import '../auth_bloc.dart'; +import '../auth_event.dart'; +import '../auth_state.dart'; +import 'components/auth_email_field.dart'; +import 'components/auth_submit_button.dart'; + +class ForgotPasswordView extends StatefulWidget { + const ForgotPasswordView({super.key}); + + @override + State createState() => _ForgotPasswordViewState(); +} + +class _ForgotPasswordViewState extends State { + final _formKey = GlobalKey(); + final _emailController = TextEditingController(); + bool _emailSent = false; + + @override + void dispose() { + _emailController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + leading: IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () => context.go('/login'), + ), + title: const Text('Reset Password'), + ), + body: SafeArea( + child: Padding( + padding: const EdgeInsets.all(24.0), + child: BlocConsumer( + listener: (context, state) { + if (state is AuthUnauthenticated && _formKey.currentState != null) { + setState(() => _emailSent = true); + } + }, + builder: (context, state) { + final isLoading = state is AuthLoading; + + if (_emailSent) { + return _buildConfirmation(); + } + + return Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const SizedBox(height: 24), + Text( + 'Enter your email address and we will send you a link to reset your password.', + style: Theme.of(context).textTheme.bodyLarge, + ), + const SizedBox(height: 24), + AuthEmailField(controller: _emailController), + const SizedBox(height: 24), + AuthSubmitButton( + label: 'Send Reset Link', + isLoading: isLoading, + onPressed: () { + if (_formKey.currentState?.validate() ?? false) { + context.read().add( + AuthEvent.resetPasswordRequested( + email: _emailController.text.trim(), + ), + ); + setState(() => _emailSent = true); + } + }, + ), + ], + ), + ); + }, + ), + ), + ), + ); + } + + Widget _buildConfirmation() { + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.email_outlined, size: 64), + const SizedBox(height: 24), + Text( + 'Check your email', + style: Theme.of(context).textTheme.headlineSmall, + ), + const SizedBox(height: 16), + Text( + 'If an account exists for ${_emailController.text.trim()}, a password reset link has been sent.', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodyLarge, + ), + const SizedBox(height: 32), + TextButton( + onPressed: () => context.go('/login'), + child: const Text('Back to Sign In'), + ), + ], + ); + } +} diff --git a/lib/ui/auth/view/login_page.dart b/lib/ui/auth/view/login_page.dart new file mode 100644 index 0000000..80885b6 --- /dev/null +++ b/lib/ui/auth/view/login_page.dart @@ -0,0 +1,19 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:get_it/get_it.dart'; + +import '../auth_bloc.dart'; +import '../auth_interactor.dart'; +import 'login_view.dart'; + +class LoginPage extends StatelessWidget { + const LoginPage({super.key}); + + @override + Widget build(BuildContext context) { + return BlocProvider( + create: (_) => AuthBloc(GetIt.instance()), + child: const LoginView(), + ); + } +} diff --git a/lib/ui/auth/view/login_view.dart b/lib/ui/auth/view/login_view.dart new file mode 100644 index 0000000..ce274f5 --- /dev/null +++ b/lib/ui/auth/view/login_view.dart @@ -0,0 +1,169 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:go_router/go_router.dart'; + +import '../auth_bloc.dart'; +import '../auth_event.dart'; +import '../auth_state.dart'; +import 'components/auth_email_field.dart'; +import 'components/auth_password_field.dart'; +import 'components/auth_submit_button.dart'; + +class LoginView extends StatefulWidget { + const LoginView({super.key}); + + @override + State createState() => _LoginViewState(); +} + +class _LoginViewState extends State + with SingleTickerProviderStateMixin { + late final TabController _tabController; + final _signInFormKey = GlobalKey(); + final _signUpFormKey = GlobalKey(); + + final _signInEmailController = TextEditingController(); + final _signInPasswordController = TextEditingController(); + final _signUpEmailController = TextEditingController(); + final _signUpPasswordController = TextEditingController(); + + @override + void initState() { + super.initState(); + _tabController = TabController(length: 2, vsync: this); + } + + @override + void dispose() { + _tabController.dispose(); + _signInEmailController.dispose(); + _signInPasswordController.dispose(); + _signUpEmailController.dispose(); + _signUpPasswordController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: SafeArea( + child: Padding( + padding: const EdgeInsets.all(24.0), + child: Column( + children: [ + const SizedBox(height: 48), + Text( + 'Welcome', + style: Theme.of(context).textTheme.headlineMedium, + ), + const SizedBox(height: 32), + TabBar( + controller: _tabController, + tabs: const [ + Tab(text: 'Sign In'), + Tab(text: 'Sign Up'), + ], + ), + const SizedBox(height: 24), + BlocBuilder( + builder: (context, state) { + final isLoading = state is AuthLoading; + final errorMessage = state is AuthError ? state.message : null; + + return Expanded( + child: TabBarView( + controller: _tabController, + children: [ + _buildSignInTab(isLoading, errorMessage), + _buildSignUpTab(isLoading, errorMessage), + ], + ), + ); + }, + ), + ], + ), + ), + ), + ); + } + + Widget _buildSignInTab(bool isLoading, String? errorMessage) { + return Form( + key: _signInFormKey, + child: ListView( + children: [ + if (errorMessage != null) + Padding( + padding: const EdgeInsets.only(bottom: 16), + child: Text( + errorMessage, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + ), + AuthEmailField(controller: _signInEmailController), + const SizedBox(height: 16), + AuthPasswordField(controller: _signInPasswordController), + const SizedBox(height: 8), + Align( + alignment: Alignment.centerRight, + child: TextButton( + onPressed: () => context.go('/login/forgot-password'), + child: const Text('Forgot password?'), + ), + ), + const SizedBox(height: 16), + AuthSubmitButton( + label: 'Sign In', + isLoading: isLoading, + onPressed: () { + if (_signInFormKey.currentState?.validate() ?? false) { + context.read().add(AuthEvent.signInRequested( + email: _signInEmailController.text.trim(), + password: _signInPasswordController.text, + )); + } + }, + ), + ], + ), + ); + } + + Widget _buildSignUpTab(bool isLoading, String? errorMessage) { + return Form( + key: _signUpFormKey, + child: ListView( + children: [ + if (errorMessage != null) + Padding( + padding: const EdgeInsets.only(bottom: 16), + child: Text( + errorMessage, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + ), + AuthEmailField(controller: _signUpEmailController), + const SizedBox(height: 16), + AuthPasswordField( + controller: _signUpPasswordController, + showValidationHints: true, + ), + const SizedBox(height: 24), + AuthSubmitButton( + label: 'Create Account', + isLoading: isLoading, + onPressed: () { + if (_signUpFormKey.currentState?.validate() ?? false) { + context.read().add(AuthEvent.signUpRequested( + email: _signUpEmailController.text.trim(), + password: _signUpPasswordController.text, + )); + } + }, + ), + ], + ), + ); + } +} diff --git a/lib/ui/go_router_refresh_stream.dart b/lib/ui/go_router_refresh_stream.dart new file mode 100644 index 0000000..b121597 --- /dev/null +++ b/lib/ui/go_router_refresh_stream.dart @@ -0,0 +1,20 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +class GoRouterRefreshStream extends ChangeNotifier { + late final StreamSubscription _subscription; + + GoRouterRefreshStream(Stream stream) { + notifyListeners(); + _subscription = stream.asBroadcastStream().listen((_) { + notifyListeners(); + }); + } + + @override + void dispose() { + _subscription.cancel(); + super.dispose(); + } +} diff --git a/lib/ui/home/home_page.dart b/lib/ui/home/home_page.dart new file mode 100644 index 0000000..faf67ef --- /dev/null +++ b/lib/ui/home/home_page.dart @@ -0,0 +1,50 @@ +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:flutter/material.dart'; +import 'package:get_it/get_it.dart'; + +import '../../core/core_module.dart'; + +class HomePage extends StatelessWidget { + const HomePage({super.key}); + + @override + Widget build(BuildContext context) { + final firebaseAuth = GetIt.instance().firebaseAuth; + + return Scaffold( + appBar: AppBar( + title: const Text('Home'), + actions: [ + IconButton( + icon: const Icon(Icons.logout), + tooltip: 'Sign out', + onPressed: () => firebaseAuth.signOut(), + ), + ], + ), + body: StreamBuilder( + stream: firebaseAuth.authStateChanges(), + builder: (context, snapshot) { + final user = snapshot.data; + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.check_circle_outline, size: 64, color: Colors.green), + const SizedBox(height: 16), + Text( + 'Welcome!', + style: Theme.of(context).textTheme.headlineMedium, + ), + if (user?.email != null) ...[ + const SizedBox(height: 8), + Text(user!.email!), + ], + ], + ), + ); + }, + ), + ); + } +} diff --git a/lib/ui/router.dart b/lib/ui/router.dart index 5358f03..b1c4d4c 100644 --- a/lib/ui/router.dart +++ b/lib/ui/router.dart @@ -1,13 +1,20 @@ // coverage:ignore-file +import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:injectable/injectable.dart'; +import '../core/core_module.dart'; +import 'go_router_refresh_stream.dart'; +import 'home/home_page.dart'; + @singleton class AppRouter { GoRouter? _goRouter; late final ValueNotifier _routingConfiguration; + late final GoRouterRefreshStream _refreshStream; + final FirebaseAuth _firebaseAuth; final String _fragment = Uri.base.fragment; Map _params = Map.fromEntries(Uri.base.queryParameters.entries); @@ -19,18 +26,20 @@ class AppRouter { _params = params; } - AppRouter() { + AppRouter(AuthModule authModule) : _firebaseAuth = authModule.firebaseAuth { + _refreshStream = GoRouterRefreshStream(_firebaseAuth.authStateChanges()); _routingConfiguration = ValueNotifier( RoutingConfig( + redirect: _redirect, routes: [ ShellRoute( builder: (context, state, child) { - return child; // Ajouter ici le socle commun de toute votre application + return child; }, routes: [ transitionGoRoute( path: '/', - builder: (context, state) => Center(child: const Text("En construction")), // Route racine, les autres seront ajoutées par injection de dépendance + builder: (context, state) => const HomePage(), ) ], ) @@ -41,16 +50,33 @@ class AppRouter { Uri.base.removeFragment(); } + String? _redirect(BuildContext context, GoRouterState state) { + final isAuthenticated = _firebaseAuth.currentUser != null; + final isOnLogin = state.matchedLocation.startsWith('/login'); + + if (!isAuthenticated && !isOnLogin) { + return '/login'; + } + if (isAuthenticated && isOnLogin) { + return '/'; + } + return null; + } + GoRouter initWithRoute(String route) { _goRouter = GoRouter.routingConfig( routingConfig: _routingConfiguration, initialLocation: route, + refreshListenable: _refreshStream, ); return _goRouter!; } GoRouter get goRouter { - _goRouter ??= GoRouter.routingConfig(routingConfig: _routingConfiguration); + _goRouter ??= GoRouter.routingConfig( + routingConfig: _routingConfiguration, + refreshListenable: _refreshStream, + ); return _goRouter!; } @@ -82,6 +108,7 @@ class AppRouter { void dispose() { goRouter.dispose(); _routingConfiguration.dispose(); + _refreshStream.dispose(); } } diff --git a/lib/ui/ui_module.dart b/lib/ui/ui_module.dart index ea7166f..f3e94a5 100644 --- a/lib/ui/ui_module.dart +++ b/lib/ui/ui_module.dart @@ -1 +1,3 @@ -export 'app.dart'; \ No newline at end of file +export 'app.dart'; +export 'auth/auth_module.dart'; +export 'go_router_refresh_stream.dart'; diff --git a/macos/Flutter/Flutter-Debug.xcconfig b/macos/Flutter/Flutter-Debug.xcconfig index c2efd0b..4b81f9b 100644 --- a/macos/Flutter/Flutter-Debug.xcconfig +++ b/macos/Flutter/Flutter-Debug.xcconfig @@ -1 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/Flutter-Release.xcconfig b/macos/Flutter/Flutter-Release.xcconfig index c2efd0b..5caa9d1 100644 --- a/macos/Flutter/Flutter-Release.xcconfig +++ b/macos/Flutter/Flutter-Release.xcconfig @@ -1 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift index cccf817..7b9be20 100644 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -5,6 +5,10 @@ import FlutterMacOS import Foundation +import firebase_auth +import firebase_core func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + FLTFirebaseAuthPlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseAuthPlugin")) + FLTFirebaseCorePlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseCorePlugin")) } diff --git a/macos/Podfile b/macos/Podfile new file mode 100644 index 0000000..ff5ddb3 --- /dev/null +++ b/macos/Podfile @@ -0,0 +1,42 @@ +platform :osx, '10.15' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_macos_podfile_setup + +target 'Runner' do + use_frameworks! + + flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_macos_build_settings(target) + end +end diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj index 62a3985..10c8a92 100644 --- a/macos/Runner.xcodeproj/project.pbxproj +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -42,6 +42,7 @@ BE5EA95BDB3A5D168156BE2D /* devDebug.xcconfig in Resources */ = {isa = PBXBuildFile; fileRef = 0CD8A358BF59C4930FC4441A /* devDebug.xcconfig */; }; D090A77B27F0541E6CEC8397 /* devProfile.xcconfig in Resources */ = {isa = PBXBuildFile; fileRef = B1211E7A6801AA541E10950C /* devProfile.xcconfig */; }; E7BE2D14C5581EFD2B14A21F /* recetteProfile.xcconfig in Resources */ = {isa = PBXBuildFile; fileRef = 69CCFA0AB5F8FE01769885E8 /* recetteProfile.xcconfig */; }; + F1206ED12720276AB5873339 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = FDDDCCC809A71BA33B96C373 /* GoogleService-Info.plist */; }; FA407AE44D2A5F8666010668 /* preprodProfile.xcconfig in Resources */ = {isa = PBXBuildFile; fileRef = C3D5C87248F720665F6F5E95 /* preprodProfile.xcconfig */; }; FCB93B201C550F619B24EC74 /* devRelease.xcconfig in Resources */ = {isa = PBXBuildFile; fileRef = EC71552C44ABDBABB62DCFA7 /* devRelease.xcconfig */; }; FE7EFF4526BB52604CCBA098 /* prodRelease.xcconfig in Resources */ = {isa = PBXBuildFile; fileRef = AA55FD046322E0DCE07F01DD /* prodRelease.xcconfig */; }; @@ -113,6 +114,7 @@ BE373AECD8821209F9B58D6E /* recetteRelease.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = recetteRelease.xcconfig; path = Runner/Configs/recetteRelease.xcconfig; sourceTree = ""; }; C3D5C87248F720665F6F5E95 /* preprodProfile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = preprodProfile.xcconfig; path = Runner/Configs/preprodProfile.xcconfig; sourceTree = ""; }; EC71552C44ABDBABB62DCFA7 /* devRelease.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = devRelease.xcconfig; path = Runner/Configs/devRelease.xcconfig; sourceTree = ""; }; + FDDDCCC809A71BA33B96C373 /* GoogleService-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; name = "GoogleService-Info.plist"; path = "Runner/GoogleService-Info.plist"; sourceTree = ""; }; FFEDE441C41BAF5E67C68C4E /* preprodDebug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = preprodDebug.xcconfig; path = Runner/Configs/preprodDebug.xcconfig; sourceTree = ""; }; /* End PBXFileReference section */ @@ -179,6 +181,7 @@ 21AA6EF95339E88977E3358F /* testDebug.xcconfig */, 3966216FD083E6C2061CBBD2 /* testProfile.xcconfig */, 80653814337EAA21BDF7FF8E /* testRelease.xcconfig */, + FDDDCCC809A71BA33B96C373 /* GoogleService-Info.plist */, ); sourceTree = ""; }; @@ -357,6 +360,7 @@ 784B2D9E45B94F3AE3ABF55D /* testDebug.xcconfig in Resources */, 6E4898DD2140BA9018D6A68D /* testProfile.xcconfig in Resources */, 726814B08FFA11C34A6C44D2 /* testRelease.xcconfig in Resources */, + F1206ED12720276AB5873339 /* GoogleService-Info.plist in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/macos/Runner/GoogleService-Info.plist b/macos/Runner/GoogleService-Info.plist new file mode 100644 index 0000000..4ca763a --- /dev/null +++ b/macos/Runner/GoogleService-Info.plist @@ -0,0 +1,30 @@ + + + + + API_KEY + AIzaSyCT5QclXtOTZQG00LXXCBoBXJeIUKe3p2o + GCM_SENDER_ID + 575974943870 + PLIST_VERSION + 1 + BUNDLE_ID + pro.listo.flutterStarterKit + PROJECT_ID + ff-kit + STORAGE_BUCKET + ff-kit.firebasestorage.app + IS_ADS_ENABLED + + IS_ANALYTICS_ENABLED + + IS_APPINVITE_ENABLED + + IS_GCM_ENABLED + + IS_SIGNIN_ENABLED + + GOOGLE_APP_ID + 1:575974943870:ios:7d87f82d470fc9368e3c2f + + \ No newline at end of file diff --git a/pubspec.lock b/pubspec.lock index ca33ad9..3233194 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -9,6 +9,22 @@ packages: url: "https://pub.dev" source: hosted version: "93.0.0" + _flutterfire_internals: + dependency: transitive + description: + name: _flutterfire_internals + sha256: ff0a84a2734d9e1089f8aedd5c0af0061b82fb94e95260d943404e0ef2134b11 + url: "https://pub.dev" + source: hosted + version: "1.3.59" + adaptive_number: + dependency: transitive + description: + name: adaptive_number + sha256: "3a567544e9b5c9c803006f51140ad544aedc79604fd4f3f2c1380003f97c1d77" + url: "https://pub.dev" + source: hosted + version: "1.0.0" analyzer: dependency: transitive description: @@ -193,6 +209,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.8" + dart_jsonwebtoken: + dependency: transitive + description: + name: dart_jsonwebtoken + sha256: "00a0812d2aeaeb0d30bcbc4dd3cee57971dbc0ab2216adf4f0247f37793f15ef" + url: "https://pub.dev" + source: hosted + version: "2.17.0" dart_style: dependency: transitive description: @@ -241,6 +265,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.2" + ed25519_edwards: + dependency: transitive + description: + name: ed25519_edwards + sha256: "6ce0112d131327ec6d42beede1e5dfd526069b18ad45dcf654f15074ad9276cd" + url: "https://pub.dev" + source: hosted + version: "0.3.1" encrypt: dependency: transitive description: @@ -249,6 +281,14 @@ packages: url: "https://pub.dev" source: hosted version: "5.0.3" + equatable: + dependency: transitive + description: + name: equatable + sha256: "3e0141505477fd8ad55d6eb4e7776d3fe8430be8e497ccb1521370c3f21a3e2b" + url: "https://pub.dev" + source: hosted + version: "2.0.8" fake_async: dependency: transitive description: @@ -273,6 +313,62 @@ packages: url: "https://pub.dev" source: hosted version: "7.0.1" + firebase_auth: + dependency: "direct main" + description: + name: firebase_auth + sha256: "0fed2133bee1369ee1118c1fef27b2ce0d84c54b7819a2b17dada5cfec3b03ff" + url: "https://pub.dev" + source: hosted + version: "5.7.0" + firebase_auth_mocks: + dependency: "direct main" + description: + name: firebase_auth_mocks + sha256: "3d4442f2856c03917777e5ddf6bb7ff5fb53e9b04426d1e1146b339bd3f19892" + url: "https://pub.dev" + source: hosted + version: "0.14.1" + firebase_auth_platform_interface: + dependency: transitive + description: + name: firebase_auth_platform_interface + sha256: "871c9df4ec9a754d1a793f7eb42fa3b94249d464cfb19152ba93e14a5966b386" + url: "https://pub.dev" + source: hosted + version: "7.7.3" + firebase_auth_web: + dependency: transitive + description: + name: firebase_auth_web + sha256: d9ada769c43261fd1b18decf113186e915c921a811bd5014f5ea08f4cf4bc57e + url: "https://pub.dev" + source: hosted + version: "5.15.3" + firebase_core: + dependency: "direct main" + description: + name: firebase_core + sha256: "7be63a3f841fc9663342f7f3a011a42aef6a61066943c90b1c434d79d5c995c5" + url: "https://pub.dev" + source: hosted + version: "3.15.2" + firebase_core_platform_interface: + dependency: transitive + description: + name: firebase_core_platform_interface + sha256: "0ecda14c1bfc9ed8cac303dd0f8d04a320811b479362a9a4efb14fd331a473ce" + url: "https://pub.dev" + source: hosted + version: "6.0.3" + firebase_core_web: + dependency: transitive + description: + name: firebase_core_web + sha256: "0ed0dc292e8f9ac50992e2394e9d336a0275b6ae400d64163fdf0a8a8b556c37" + url: "https://pub.dev" + source: hosted + version: "2.24.1" fixnum: dependency: transitive description: @@ -640,6 +736,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.0" + mock_exceptions: + dependency: transitive + description: + name: mock_exceptions + sha256: "6e3e623712d2c6106ffe9e14732912522b565ddaa82a8dcee6cd4441b5984056" + url: "https://pub.dev" + source: hosted + version: "0.8.2" nested: dependency: transitive description: @@ -680,6 +784,14 @@ packages: url: "https://pub.dev" source: hosted version: "7.0.2" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" pointycastle: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 27b343c..e429fa2 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -28,6 +28,9 @@ dependencies: freezed_annotation: ^3.1.0 transparent_image: ^2.0.1 go_router: ^17.1.0 + firebase_core: ^3.13.0 + firebase_auth: ^5.7.0 + firebase_auth_mocks: ^0.14.1 dev_dependencies: flutter_test: sdk: flutter diff --git a/skills-lock.json b/skills-lock.json new file mode 100644 index 0000000..a4634db --- /dev/null +++ b/skills-lock.json @@ -0,0 +1,55 @@ +{ + "version": 1, + "skills": { + "developing-genkit-dart": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "aa92490e4db5038730c629477ad968796f329040433625cf9b7bb13e26a859e3" + }, + "developing-genkit-js": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "2fa9adb27f7cfc4635decebea65222cd56e36b5de34781f7862be888504c04f4" + }, + "firebase-ai-logic": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "3b3d8994f2ac2e747a1f203488844a7e17b8a25c38e636b221903ae90e3b7c32" + }, + "firebase-app-hosting-basics": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "7f0e0330510b4e6b06bcede472cebb183a491b8a0098f92d7563454c40d78050" + }, + "firebase-auth-basics": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "ff79d278c0968f297d60f37532c32fd3b8bd9aad9c64b9f354585c701e80112a" + }, + "firebase-basics": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "1a63ad98e772cbe4cded7eb8d83d0f8722f13f7b1a47087a8aa59a4080fc82bb" + }, + "firebase-data-connect": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "e7e35c29c4851d495a7417c4331666119d2492e914a08a8d006f1471a554e09f" + }, + "firebase-firestore-enterprise-native-mode": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "528bd602aa93a4409842a4e6f9888b8438521953253b0a629aeaf10603823bf9" + }, + "firebase-firestore-standard": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "ab2332607f40ae408e9c56e177b02fad55e071bfac4c2035a16ce0787768953e" + }, + "firebase-hosting-basics": { + "source": "firebase/agent-skills", + "sourceType": "github", + "computedHash": "fb86fd4035e8e6379931faeb443557ac6f2e43fde04b397433f287e69b6532a9" + } + } +} diff --git a/specs/001-firebase-auth/checklists/requirements.md b/specs/001-firebase-auth/checklists/requirements.md new file mode 100644 index 0000000..ec7eb5f --- /dev/null +++ b/specs/001-firebase-auth/checklists/requirements.md @@ -0,0 +1,39 @@ +# Specification Quality Checklist: Authentication System with Firebase Auth + +**Purpose**: Validate specification completeness and quality before proceeding to planning +**Created**: 2026-04-05 +**Feature**: [spec.md](../spec.md) + +## Content Quality + +- [x] No implementation details (languages, frameworks, APIs) +- [x] Focused on user value and business needs +- [x] Written for non-technical stakeholders +- [x] All mandatory sections completed + +## Requirement Completeness + +- [x] No [NEEDS CLARIFICATION] markers remain +- [x] Requirements are testable and unambiguous +- [x] Success criteria are measurable +- [x] Success criteria are technology-agnostic (no implementation details) +- [x] All acceptance scenarios are defined +- [x] Edge cases are identified +- [x] Scope is clearly bounded +- [x] Dependencies and assumptions identified + +## Feature Readiness + +- [x] All functional requirements have clear acceptance criteria +- [x] User scenarios cover primary flows +- [x] Feature meets measurable outcomes defined in Success Criteria +- [x] No implementation details leak into specification + +## Notes + +- All items pass validation. +- Feature description: "Firebase Auth" was mentioned in user input, but the spec + intentionally avoids prescribing implementation details. The planning phase + will map requirements to the Firebase Auth SDK. +- Email/password is the only auth method for v1 (documented in Assumptions). +- Social auth providers explicitly deferred to future iteration. diff --git a/specs/001-firebase-auth/contracts/auth-repository.md b/specs/001-firebase-auth/contracts/auth-repository.md new file mode 100644 index 0000000..869c6ac --- /dev/null +++ b/specs/001-firebase-auth/contracts/auth-repository.md @@ -0,0 +1,61 @@ +# Contract: AuthRepository + +**Layer**: `domain/` (abstract) → `data/` (implementation) + +## Interface + +``` +AuthRepository +├── signUp(email, password) → Stream +├── signIn(email, password) → Stream +├── signOut() → Stream +├── sendPasswordResetEmail(email) → Stream +└── watchAuthState() → Stream +``` + +## Method Contracts + +### signUp(email, password) + +- **Input**: Valid email (String), password meeting complexity rules (String) +- **Output**: Stream emitting the newly created `AuthUser` +- **Errors**: `AuthErrorType.emailAlreadyInUse`, `AuthErrorType.weakPassword`, + `AuthErrorType.invalidEmail`, `AuthErrorType.networkError` +- **Side effect**: User is automatically signed in after creation + +### signIn(email, password) + +- **Input**: Email (String), password (String) +- **Output**: Stream emitting the authenticated `AuthUser` +- **Errors**: `AuthErrorType.invalidCredentials` (covers both wrong + password and non-existent account), `AuthErrorType.networkError`, + `AuthErrorType.tooManyRequests` + +### signOut() + +- **Input**: None +- **Output**: Stream emitting void on completion +- **Errors**: `AuthErrorType.networkError` +- **Side effect**: Local session cleared, `watchAuthState()` emits `null` + +### sendPasswordResetEmail(email) + +- **Input**: Email (String) +- **Output**: Stream emitting void on completion +- **Errors**: `AuthErrorType.networkError` +- **Note**: MUST NOT reveal whether email exists (`FR-005`) + +### watchAuthState() + +- **Input**: None +- **Output**: Continuous stream — emits `AuthUser` when signed in, + `null` when signed out or session expired +- **Lifecycle**: Active for app duration, typically subscribed once + at startup + +## Error Contract + +All methods that can fail MUST emit an error on the stream +of type `AuthException` containing: +- `type`: `AuthErrorType` enum value +- `message`: User-friendly localized message diff --git a/specs/001-firebase-auth/contracts/auth-routes.md b/specs/001-firebase-auth/contracts/auth-routes.md new file mode 100644 index 0000000..5bff162 --- /dev/null +++ b/specs/001-firebase-auth/contracts/auth-routes.md @@ -0,0 +1,43 @@ +# Contract: Authentication Routes + +**Layer**: `ui/` — registered via `AuthModule.configure()` + +## Routes + +| Path | Page | Auth Required | Description | +|------|------|---------------|-------------| +| `/login` | LoginPage | No | Sign-in + sign-up entry point | +| `/login/forgot-password` | ForgotPasswordPage | No | Password reset form | + +## Redirect Rules + +| Condition | Current Route | Redirect To | +|-----------|---------------|-------------| +| User is NOT authenticated | Any protected route | `/login` | +| User IS authenticated | `/login` or `/login/*` | `/` | +| User IS authenticated | Any protected route | (no redirect) | + +## Navigation Flows + +### Sign-Up Flow +``` +/login → (sign-up tab) → submit → success → / (home) + → error → stay on /login +``` + +### Sign-In Flow +``` +/login → (sign-in tab) → submit → success → / (home) + → error → stay on /login +``` + +### Password Reset Flow +``` +/login → "Forgot password" → /login/forgot-password + → submit email → confirmation shown → back to /login +``` + +### Sign-Out Flow +``` +(any page) → sign-out action → /login +``` diff --git a/specs/001-firebase-auth/data-model.md b/specs/001-firebase-auth/data-model.md new file mode 100644 index 0000000..d695f90 --- /dev/null +++ b/specs/001-firebase-auth/data-model.md @@ -0,0 +1,111 @@ +# Data Model: Authentication System with Firebase Auth + +**Branch**: `001-firebase-auth` | **Date**: 2026-04-05 + +## Entities + +### AuthUser (Domain Entity) + +Represents an authenticated user in the domain layer. + +| Field | Type | Description | +|-------|------|-------------| +| `uid` | `String` | Unique identifier from Firebase | +| `email` | `String` | User's email address | +| `displayName` | `String?` | Optional display name | +| `isEmailVerified` | `bool` | Whether email has been verified | + +**Freezed**: Yes — immutable value object. + +**Factory**: `AuthUser.fromDto(AuthUserDto dto)` for +data→domain conversion. + +### AuthUserDto (Data Layer DTO) + +Thin wrapper around Firebase `User` for the data layer. + +| Field | Type | Source | +|-------|------|--------| +| `uid` | `String` | `User.uid` | +| `email` | `String?` | `User.email` | +| `displayName` | `String?` | `User.displayName` | +| `isEmailVerified` | `bool` | `User.emailVerified` | + +**Note**: This DTO is constructed directly from the Firebase +`User` object in the repository, not from JSON serialization. +No `*.g.dart` generation needed. + +### AuthErrorType (Domain Enum) + +Categorizes authentication failures. + +| Value | Firebase Code(s) | User-Facing Meaning | +|-------|-------------------|---------------------| +| `invalidCredentials` | `wrong-password`, `user-not-found` | Email or password incorrect | +| `emailAlreadyInUse` | `email-already-in-use` | Account already exists | +| `weakPassword` | `weak-password` | Password too simple | +| `invalidEmail` | `invalid-email` | Email format invalid | +| `networkError` | `network-request-failed` | No internet connection | +| `tooManyRequests` | `too-many-requests` | Rate limited | +| `unknown` | (all others) | Unexpected error | + +### AuthState (BLoC State) + +| State | Fields | When | +|-------|--------|------| +| `AuthInitial` | none | App just started, checking auth | +| `AuthAuthenticated` | `AuthUser user` | User signed in | +| `AuthUnauthenticated` | none | No active session | +| `AuthLoading` | none | Sign-in/sign-up in progress | +| `AuthError` | `AuthErrorType type, String message` | Operation failed | + +**Freezed**: Yes — union type. + +## Relationships + +``` +FirebaseAuth.User (external) + │ + ▼ (constructed in AuthRepositoryImpl) + AuthUserDto (data layer) + │ + ▼ (AuthUser.fromDto) + AuthUser (domain entity) + │ + ▼ (via Use Case → Interactor) + AuthState.authenticated(user) (UI layer) +``` + +## Validation Rules + +- Email: validated by `FR-002` (format check before submission); + Firebase also validates server-side. +- Password: minimum 8 characters, at least 1 uppercase, 1 lowercase, + 1 digit (`FR-003`). Validated client-side before Firebase call. +- Error messages: MUST NOT reveal whether an email exists in the + system (`FR-005`). `wrong-password` and `user-not-found` both + map to `invalidCredentials`. + +## State Transitions + +``` +AuthInitial + │ + ├─ authStateChanges() emits User → AuthAuthenticated + └─ authStateChanges() emits null → AuthUnauthenticated + +AuthUnauthenticated + │ + ├─ SignInRequested → AuthLoading → AuthAuthenticated (success) + ├─ SignInRequested → AuthLoading → AuthError (failure) + ├─ SignUpRequested → AuthLoading → AuthAuthenticated (success) + └─ SignUpRequested → AuthLoading → AuthError (failure) + +AuthAuthenticated + │ + └─ SignOutRequested → AuthUnauthenticated + +AuthError + │ + └─ (user retries) → AuthLoading → ... +``` diff --git a/specs/001-firebase-auth/plan.md b/specs/001-firebase-auth/plan.md new file mode 100644 index 0000000..817f2ee --- /dev/null +++ b/specs/001-firebase-auth/plan.md @@ -0,0 +1,144 @@ +# Implementation Plan: Authentication System with Firebase Auth + +**Branch**: `001-firebase-auth` | **Date**: 2026-04-05 | **Spec**: [spec.md](spec.md) +**Input**: Feature specification from `/specs/001-firebase-auth/spec.md` + +## Summary + +Add email/password authentication using Firebase Auth, following the +existing Clean Architecture pattern. The feature includes sign-up, +sign-in, sign-out, password reset, session persistence, and +go_router-based route protection. All Firebase SDK interactions are +isolated in the `data/` layer behind an abstract repository. + +## Technical Context + +**Language/Version**: Dart 3.10+ / Flutter >=3.10.2 +**Primary Dependencies**: `firebase_core`, `firebase_auth`, +`flutter_bloc`, `go_router`, `get_it` + `injectable`, `freezed` +**Storage**: Firebase Auth (remote) — no local storage needed +(Firebase SDK handles token persistence) +**Testing**: `bdd_widget_test` (Gherkin), `firebase_auth_mocks` +**Target Platform**: Android, iOS, Web, macOS +**Project Type**: Mobile app (Flutter starter kit) +**Performance Goals**: Sign-in/sign-up complete in <2s (network dependent) +**Constraints**: Online required for auth operations, token refresh +handled by Firebase SDK (~1h tokens) +**Scale/Scope**: 5 screens (login, sign-up tab, sign-in tab, +forgot password, home redirect) + +## Constitution Check + +*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.* + +| Principle | Status | Notes | +|-----------|--------|-------| +| I. Layer Isolation via Module Exports | PASS | All new files exported via `*_module.dart`. No cross-layer imports. | +| II. Anti-Corruption Layer | PASS | `AuthUserDto` in `data/`, `AuthUser.fromDto()` in `domain/`. BLoC uses `AuthUser` entity only. Async flow uses `Stream`. | +| III. BLoC Screen Architecture | PASS | Auth feature follows `feature_name/{view/, bloc, event, state, interactor, module}` pattern. Routes registered via `UIModule.configure()`. | +| IV. Code Generation Discipline | PASS | `AuthUser` and `AuthState` use Freezed. `build_runner` required after changes. DI annotations follow convention. | +| V. Testing Discipline | PASS | `firebase_auth_mocks` for test environment. BDD features planned. Coverage targets apply. | + +**Gate result**: PASS — proceed to implementation. + +## Project Structure + +### Documentation (this feature) + +```text +specs/001-firebase-auth/ +├── plan.md # This file +├── research.md # Phase 0 output +├── data-model.md # Phase 1 output +├── quickstart.md # Phase 1 output +├── contracts/ +│ ├── auth-repository.md +│ └── auth-routes.md +├── checklists/ +│ └── requirements.md +└── tasks.md # Phase 2 output (/speckit.tasks) +``` + +### Source Code (repository root) + +```text +lib/ +├── core/ +│ ├── di/ +│ │ ├── auth/ +│ │ │ ├── auth_module.dart # Abstract auth service interface +│ │ │ ├── auth_module_impl.dart # FirebaseAuth registration (non-test) +│ │ │ ├── auth_module_stub.dart # MockFirebaseAuth registration (test) +│ │ │ └── auth_core_module.dart # Barrel export +│ │ └── di_module.dart # Updated: export auth_core_module +│ └── core_module.dart +├── data/ +│ ├── dto/ +│ │ ├── auth_user_dto.dart # DTO wrapping Firebase User +│ │ └── dto_module.dart # Updated: export auth_user_dto +│ ├── repositories/ +│ │ ├── auth_repository_impl.dart # AuthRepository implementation +│ │ └── repositories_module.dart # Updated: export auth_repository_impl +│ └── data_module.dart +├── domain/ +│ ├── entities/ +│ │ ├── auth_user.dart # Freezed entity + fromDto +│ │ ├── auth_error_type.dart # Error enum +│ │ ├── auth_exception.dart # Typed exception +│ │ └── entities_module.dart # Updated: export auth entities +│ ├── usecases/ +│ │ ├── auth/ +│ │ │ ├── sign_in_use_case.dart # @singleton +│ │ │ ├── sign_up_use_case.dart # @singleton +│ │ │ ├── sign_out_use_case.dart # @singleton +│ │ │ ├── reset_password_use_case.dart # @singleton +│ │ │ ├── watch_auth_state_use_case.dart # @singleton +│ │ │ └── auth_usecases_module.dart # Barrel export +│ │ └── usecases_module.dart # Updated: export auth_usecases_module +│ └── domain_module.dart +├── ui/ +│ ├── auth/ +│ │ ├── view/ +│ │ │ ├── components/ +│ │ │ │ ├── auth_email_field.dart +│ │ │ │ ├── auth_password_field.dart +│ │ │ │ └── auth_submit_button.dart +│ │ │ ├── login_page.dart # BlocProvider init +│ │ │ ├── login_view.dart # Sign-in/sign-up tabs +│ │ │ └── forgot_password_view.dart +│ │ ├── auth_bloc.dart +│ │ ├── auth_event.dart +│ │ ├── auth_state.dart # Freezed union +│ │ ├── auth_interactor.dart # @singleton ACL +│ │ └── auth_module.dart # UIModule, route registration +│ ├── router.dart # Updated: add redirect + refreshListenable +│ └── ui_module.dart +├── main.dart # Updated: add Firebase.initializeApp() +└── injection.dart +``` + +**Structure Decision**: Flutter mobile app — all code under `lib/` +following the existing 4-layer Clean Architecture. Auth feature adds +files in each layer, following existing naming and barrel export +conventions. + +### Test Structure + +```text +test/ +├── gherkin/ +│ ├── features/ +│ │ ├── auth_sign_up.feature +│ │ ├── auth_sign_in.feature +│ │ └── auth_sign_out.feature +│ └── steps/ +│ ├── (existing steps...) +│ └── (new auth-specific steps) +└── mocks/ + └── api/ + └── (existing mocks) +``` + +## Complexity Tracking + +> No Constitution Check violations — table not needed. diff --git a/specs/001-firebase-auth/quickstart.md b/specs/001-firebase-auth/quickstart.md new file mode 100644 index 0000000..fd674bf --- /dev/null +++ b/specs/001-firebase-auth/quickstart.md @@ -0,0 +1,80 @@ +# Quickstart: Authentication System with Firebase Auth + +**Branch**: `001-firebase-auth` + +## Prerequisites + +1. Flutter SDK installed (version >=3.10.2) +2. Firebase project created with Authentication enabled + (Email/Password provider activated) +3. FlutterFire CLI installed: `dart pub global activate flutterfire_cli` +4. `google-services.json` (Android) and `GoogleService-Info.plist` + (iOS) configured per flavor + +## Setup + +```bash +# 1. Switch to the feature branch +git checkout 001-firebase-auth + +# 2. Install dependencies +flutter pub get + +# 3. Generate code (DI, Freezed, etc.) +dart run build_runner build --delete-conflicting-outputs + +# 4. Run the app (dev flavor) +flutter run --flavor dev -t lib/main_dev.dart +``` + +## Verify It Works + +### Sign-Up +1. Launch the app — you should be redirected to `/login` +2. Switch to the "Sign Up" tab +3. Enter a valid email and a password (8+ chars, mixed case, 1 digit) +4. Tap "Create Account" +5. You should land on the home screen + +### Sign-In +1. Sign out (if signed in) +2. Enter the credentials from step 3 above +3. Tap "Sign In" +4. You should land on the home screen + +### Password Reset +1. On the login screen, tap "Forgot password" +2. Enter the email from sign-up +3. You should see a confirmation message +4. Check email for the reset link + +### Session Persistence +1. Sign in +2. Force-close the app +3. Reopen — you should land directly on the home screen + +### Sign-Out +1. While authenticated, trigger the sign-out action +2. You should be redirected to `/login` +3. Pressing back should NOT return to the home screen + +## Run Tests + +```bash +# All tests +flutter test + +# Analyze (zero warnings required) +flutter analyze +``` + +## Troubleshooting + +- **`Firebase not initialized`**: Ensure `Firebase.initializeApp()` + runs in `main.dart` before `configureDependencies()`. +- **`No Firebase App '[DEFAULT]' has been created`**: Run + `flutterfire configure` to generate `firebase_options.dart`. +- **Build errors after adding files**: Run + `dart run build_runner build --delete-conflicting-outputs`. +- **DI resolution fails**: Ensure new classes have `@singleton` or + `@injectable` annotations and `build_runner` has been re-run. diff --git a/specs/001-firebase-auth/research.md b/specs/001-firebase-auth/research.md new file mode 100644 index 0000000..b78848d --- /dev/null +++ b/specs/001-firebase-auth/research.md @@ -0,0 +1,117 @@ +# Research: Authentication System with Firebase Auth + +**Branch**: `001-firebase-auth` | **Date**: 2026-04-05 + +## R1: Firebase Auth Flutter SDK + +**Decision**: Use `firebase_auth` (latest) with `firebase_core` (latest). + +**Rationale**: Official Flutter plugin for Firebase Authentication. +Provides all required methods: `createUserWithEmailAndPassword`, +`signInWithEmailAndPassword`, `signOut`, `sendPasswordResetEmail`. +Exposes `authStateChanges()` stream for reactive auth state. +Token refresh is handled automatically by the SDK (~1 hour tokens). + +**Alternatives considered**: +- `supabase_flutter`: Full backend alternative, but user specified + Firebase Auth. +- Custom JWT auth: Unnecessary complexity when Firebase handles + token lifecycle. + +## R2: Firebase Initialization Strategy + +**Decision**: Call `Firebase.initializeApp()` in `lib/main.dart` +after `WidgetsFlutterBinding.ensureInitialized()` and before +`configureDependencies()`. Use `DefaultFirebaseOptions.currentPlatform` +from the existing `firebase_options.dart`. + +**Rationale**: Firebase must initialize before any service is used. +The project already has `firebase_options.dart` generated by FlutterFire +CLI. Placing init before DI ensures `FirebaseAuth.instance` is +available when DI resolves singletons. + +**Alternatives considered**: +- Per-flavor Firebase options files: Not needed since FlutterFire CLI + generates platform-specific options. Flavor-specific Firebase + projects can be configured via `flutterfire configure` per flavor. +- Lazy initialization: Risky — any access before init throws. + +## R3: Auth State in go_router + +**Decision**: Create a `GoRouterRefreshStream` adapter that converts +`FirebaseAuth.instance.authStateChanges()` into a `ChangeNotifier`. +Pass it as `refreshListenable` on the `GoRouter` constructor. Add a +global `redirect` callback to guard routes. + +**Rationale**: go_router's `refreshListenable` re-evaluates redirects +on each auth state change. This pattern is well-documented and avoids +polling. The redirect callback checks `FirebaseAuth.instance.currentUser` +and routes to `/login` or `/` accordingly. + +**Alternatives considered**: +- Per-route guards: More granular but harder to maintain and violates + the "no central route file" principle less cleanly. +- BLoC-driven navigation: Adds coupling between BLoC and router that + complicates testing. + +## R4: Layer Architecture for Auth + +**Decision**: Follow the existing Clean Architecture pattern: + +| Layer | Component | Responsibility | +|-------|-----------|----------------| +| `core/` | `AuthModule` (abstract + impl) | Register `FirebaseAuth` in DI, `GoRouterRefreshStream` | +| `data/` | `AuthRepositoryImpl`, `AuthUserDto` | Wrap `FirebaseAuth` calls, convert Firebase `User` to DTO | +| `domain/` | `AuthUser` entity, Use Cases, abstract `AuthRepository` | Business logic, `fromDto` conversion | +| `ui/` | Auth BLoC, Login/SignUp pages, `AuthModule` | UI state, screens, route registration | + +**Rationale**: Matches the existing project patterns exactly. Each +layer only imports its immediate dependency via `*_module.dart`. +The `data/` layer wraps Firebase SDK calls so `domain/` and `ui/` +never touch Firebase directly. + +**Alternatives considered**: +- Direct `FirebaseAuth` usage in BLoC: Violates layer separation + (Constitution Principle I). +- Repository in `domain/`: Violates the Anti-Corruption Layer + principle — concrete implementations belong in `data/`. + +## R5: Testing Strategy + +**Decision**: Use `firebase_auth_mocks` package for unit/BDD tests. +Register `MockFirebaseAuth` via injectable's `@test` environment. + +**Rationale**: `firebase_auth_mocks` provides `MockFirebaseAuth` with +`authStateChanges()` stream simulation and configurable `MockUser`. +The project already uses environment-based DI (`@test` registers +`ApiModuleStub`); the same pattern works for auth. + +**Alternatives considered**: +- Manual mocking with `mockito`: More boilerplate, less reliable for + stream-based auth state testing. +- `firebase_auth_platform_interface` fakes: Lower-level, harder to + set up, intended for plugin development. + +## R6: Auth Error Handling + +**Decision**: Map `FirebaseAuthException.code` to a domain +`AuthError` enum in the `data/` layer. The repository catches +Firebase exceptions and returns typed errors to the domain layer. + +**Rationale**: Prevents Firebase-specific error codes from leaking +into `domain/` or `ui/`. Maps codes like `email-already-in-use`, +`wrong-password`, `user-not-found`, `weak-password` to +domain-meaningful values. Security requirement FR-005 mandates +generic error messages — the mapping layer enforces this. + +**Key error codes**: +- `email-already-in-use` → `AuthErrorType.emailAlreadyInUse` +- `wrong-password` / `user-not-found` → `AuthErrorType.invalidCredentials` +- `weak-password` → `AuthErrorType.weakPassword` +- `invalid-email` → `AuthErrorType.invalidEmail` +- `network-request-failed` → `AuthErrorType.networkError` +- `too-many-requests` → `AuthErrorType.tooManyRequests` + +**Alternatives considered**: +- Passing raw exception strings: Violates Anti-Corruption Layer + (Constitution Principle II). diff --git a/specs/001-firebase-auth/spec.md b/specs/001-firebase-auth/spec.md new file mode 100644 index 0000000..f9c3bb6 --- /dev/null +++ b/specs/001-firebase-auth/spec.md @@ -0,0 +1,232 @@ +# Feature Specification: Authentication System with Firebase Auth + +**Feature Branch**: `001-firebase-auth` +**Created**: 2026-04-05 +**Status**: Draft +**Input**: User description: "Authentication system with Firebase Auth" + +## User Scenarios & Testing *(mandatory)* + +### User Story 1 - Email/Password Sign-Up (Priority: P1) + +A new user opens the application for the first time and wants to +create an account. They provide their email address and a password, +receive a confirmation, and are granted access to the app. + +**Why this priority**: Account creation is the entry point to the +entire application. Without sign-up, no other authenticated feature +can be used. + +**Independent Test**: Can be fully tested by launching the app, +navigating to the sign-up screen, entering valid credentials, and +confirming the user lands on the authenticated home screen. + +**Acceptance Scenarios**: + +1. **Given** the user is on the sign-up screen, **When** they enter + a valid email and a password meeting complexity requirements and + submit, **Then** their account is created and they are redirected + to the home screen. +2. **Given** the user is on the sign-up screen, **When** they enter + an email already associated with an existing account, **Then** + they see an error message indicating the email is already in use. +3. **Given** the user is on the sign-up screen, **When** they enter + a password that does not meet complexity requirements, **Then** + they see a specific error describing the password policy. +4. **Given** the user is on the sign-up screen, **When** they enter + an invalid email format, **Then** they see an error indicating + the email format is incorrect. + +--- + +### User Story 2 - Email/Password Sign-In (Priority: P1) + +A returning user opens the application and wants to sign in with +their existing email and password to access their content. + +**Why this priority**: Sign-in is equally critical to sign-up — +returning users must be able to access the app. Tied with P1 as +both form the core authentication loop. + +**Independent Test**: Can be tested by signing in with a previously +created account and verifying the user reaches the authenticated +home screen. + +**Acceptance Scenarios**: + +1. **Given** the user is on the sign-in screen, **When** they enter + valid credentials, **Then** they are authenticated and redirected + to the home screen. +2. **Given** the user is on the sign-in screen, **When** they enter + an incorrect password, **Then** they see an error message + indicating invalid credentials (without revealing which field is + wrong). +3. **Given** the user is on the sign-in screen, **When** they enter + an email that does not correspond to any account, **Then** they + see a generic "invalid credentials" error. + +--- + +### User Story 3 - Password Reset (Priority: P2) + +A user who has forgotten their password wants to recover access to +their account by requesting a password reset email. + +**Why this priority**: Password recovery is essential for user +retention but secondary to the core sign-in/sign-up flow. + +**Independent Test**: Can be tested by requesting a password reset, +verifying the confirmation message appears, and confirming no error +occurs for a valid email. + +**Acceptance Scenarios**: + +1. **Given** the user is on the sign-in screen, **When** they tap + "Forgot password" and enter their registered email, **Then** + they see a confirmation that a reset email has been sent. +2. **Given** the user enters an email not associated with any + account, **Then** they still see the same confirmation message + (to prevent email enumeration). +3. **Given** the user has received the reset email, **When** they + follow the link and set a new password, **Then** they can sign + in with the new password. + +--- + +### User Story 4 - Sign-Out (Priority: P2) + +An authenticated user wants to sign out of the application to +secure their session or switch accounts. + +**Why this priority**: Sign-out completes the authentication +lifecycle and is required for multi-user or shared-device scenarios. + +**Independent Test**: Can be tested by signing in, tapping sign-out, +and verifying the user is redirected to the sign-in screen and +cannot access authenticated content. + +**Acceptance Scenarios**: + +1. **Given** the user is authenticated, **When** they tap "Sign out", + **Then** their session is terminated and they are redirected to + the sign-in screen. +2. **Given** the user has signed out, **When** they press the back + button, **Then** they cannot access any authenticated screen. + +--- + +### User Story 5 - Persistent Session (Priority: P3) + +A user who previously signed in closes and reopens the application. +They expect to remain signed in without re-entering their +credentials. + +**Why this priority**: Session persistence improves user experience +significantly but is not required for the core authentication flow +to function. + +**Independent Test**: Can be tested by signing in, force-closing +the app, reopening it, and verifying the user lands on the home +screen without being asked to sign in again. + +**Acceptance Scenarios**: + +1. **Given** the user is authenticated and closes the app, **When** + they reopen the app, **Then** they are automatically taken to + the home screen without signing in again. +2. **Given** the user's session has expired or been revoked, **When** + they reopen the app, **Then** they are redirected to the sign-in + screen. + +--- + +### Edge Cases + +- What happens when the user loses network connectivity during + sign-up or sign-in? The system MUST display a clear offline error + and allow retry when connectivity is restored. +- What happens when the user submits the sign-up form multiple times + rapidly? The system MUST prevent duplicate account creation by + disabling the submit button after the first tap. +- What happens when Firebase Auth service is temporarily unavailable? + The system MUST display a generic service error and suggest the + user try again later. +- What happens when the user's authentication token expires while + they are actively using the app? The system MUST attempt a silent + token refresh; if it fails, redirect to sign-in. + +## Requirements *(mandatory)* + +### Functional Requirements + +- **FR-001**: System MUST allow users to create an account using + an email address and password. +- **FR-002**: System MUST validate email format before submission. +- **FR-003**: System MUST enforce password complexity rules + (minimum 8 characters, at least one uppercase letter, one + lowercase letter, and one digit). +- **FR-004**: System MUST allow users to sign in with an existing + email and password. +- **FR-005**: System MUST display user-friendly error messages for + all authentication failures without revealing sensitive details + (e.g., whether an email exists in the system). +- **FR-006**: System MUST allow users to request a password reset + via email. +- **FR-007**: System MUST allow authenticated users to sign out, + clearing their local session. +- **FR-008**: System MUST persist the user's session across app + restarts until explicit sign-out or session expiry. +- **FR-009**: System MUST redirect unauthenticated users to the + sign-in screen when they attempt to access protected routes. +- **FR-010**: System MUST silently refresh authentication tokens + when they are near expiry, without interrupting the user. +- **FR-011**: System MUST handle network errors gracefully during + all authentication operations, displaying appropriate feedback. + +### Key Entities + +- **User**: Represents an authenticated user. Key attributes: + unique identifier, email address, display name (optional), + authentication status, last sign-in timestamp. +- **AuthSession**: Represents the current authentication state. + Key attributes: authentication token, refresh token, expiry + timestamp, sign-in method used. +- **AuthError**: Represents an authentication failure. Key + attributes: error type (invalid credentials, network error, + account exists, weak password), user-facing message. + +## Success Criteria *(mandatory)* + +### Measurable Outcomes + +- **SC-001**: Users can complete account creation (sign-up) in + under 60 seconds from opening the sign-up screen. +- **SC-002**: Users can sign in to an existing account in under + 30 seconds from opening the sign-in screen. +- **SC-003**: 95% of returning users are automatically signed in + when reopening the app (session persistence). +- **SC-004**: Password reset email is received within 2 minutes + of the user's request. +- **SC-005**: All authentication error messages are understandable + to non-technical users (no raw error codes or stack traces). +- **SC-006**: The authentication flow works correctly across all + application flavors (prod, preprod, recette, integration, dev, + test). + +## Assumptions + +- Users have a stable internet connection for initial sign-up and + sign-in operations (offline-first authentication is out of scope). +- Firebase Auth is already configured in the Firebase project for + all required flavors (prod, dev, test, etc.) with appropriate + `google-services.json` / `GoogleService-Info.plist` files. +- Email/password is the only authentication method for v1. Social + providers (Google, Apple, etc.) are out of scope and may be added + in a future iteration. +- Email verification after sign-up is not required for v1. Users + can access the app immediately after creating their account. +- The application already has a home screen or landing page to + redirect authenticated users to. +- Password complexity rules follow the project's standard (8+ + characters, mixed case, at least one digit). No additional + organization-specific policies apply. diff --git a/specs/001-firebase-auth/tasks.md b/specs/001-firebase-auth/tasks.md new file mode 100644 index 0000000..e9bf109 --- /dev/null +++ b/specs/001-firebase-auth/tasks.md @@ -0,0 +1,286 @@ +# Tasks: Authentication System with Firebase Auth + +**Input**: Design documents from `/specs/001-firebase-auth/` +**Prerequisites**: plan.md (required), spec.md (required), research.md, data-model.md, contracts/ + +## Format: `[ID] [P?] [Story] Description` + +- **[P]**: Can run in parallel (different files, no dependencies) +- **[Story]**: Which user story this task belongs to (e.g., US1, US2, US3) +- Include exact file paths in descriptions + +## Phase 1: Setup + +**Purpose**: Add Firebase dependencies and initialize Firebase in the app + +- [x] T001 Add `firebase_core` and `firebase_auth` to dependencies in `pubspec.yaml` +- [x] T002 Add `firebase_auth_mocks` to dev_dependencies in `pubspec.yaml` +- [x] T003 Add `Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform)` to `lib/main.dart` between `WidgetsFlutterBinding.ensureInitialized()` and `configureDependencies()` +- [x] T004 Run `flutter pub get` to install new dependencies + +--- + +## Phase 2: Foundational (Blocking Prerequisites) + +**Purpose**: Core auth infrastructure that MUST be complete before ANY user story + +**CRITICAL**: No user story work can begin until this phase is complete + +- [x] T005 [P] Create `AuthErrorType` enum in `lib/domain/entities/auth_error_type.dart` with values: `invalidCredentials`, `emailAlreadyInUse`, `weakPassword`, `invalidEmail`, `networkError`, `tooManyRequests`, `unknown` +- [x] T006 [P] Create `AuthException` class in `lib/domain/entities/auth_exception.dart` with `AuthErrorType type` and `String message` fields +- [x] T007 [P] Create `AuthUser` Freezed entity in `lib/domain/entities/auth_user.dart` with fields: `uid` (String), `email` (String), `displayName` (String?), `isEmailVerified` (bool); include `factory AuthUser.fromDto(AuthUserDto dto)` +- [x] T008 [P] Create `AuthUserDto` class in `lib/data/dto/auth_user_dto.dart` wrapping Firebase `User` fields: `uid`, `email`, `displayName`, `isEmailVerified` +- [x] T009 Update `lib/domain/entities/entities_module.dart` to export `auth_user.dart`, `auth_error_type.dart`, `auth_exception.dart` +- [x] T010 Update `lib/data/dto/dto_module.dart` to export `auth_user_dto.dart` +- [x] T011 Create abstract `AuthRepository` interface in `lib/data/repositories/auth_repository.dart` with methods: `signUp(email, password) → Stream`, `signIn(email, password) → Stream`, `signOut() → Stream`, `sendPasswordResetEmail(email) → Stream`, `watchAuthState() → Stream` +- [x] T012 Create `AuthRepositoryImpl` in `lib/data/repositories/auth_repository_impl.dart` implementing `AuthRepository`, annotated `@injectable` with `@factoryMethod`, wrapping `FirebaseAuth` calls. Map `FirebaseAuthException.code` to `AuthErrorType`. Convert Firebase `User` to `AuthUserDto` then `AuthUser.fromDto()` +- [x] T013 Update `lib/data/repositories/repositories_module.dart` to export `auth_repository.dart` and `auth_repository_impl.dart` +- [x] T014 Create abstract `AuthModule` in `lib/core/di/auth/auth_module.dart` exposing `FirebaseAuth` instance access +- [x] T015 [P] Create `AuthModuleImpl` in `lib/core/di/auth/auth_module_impl.dart` registered as `@Singleton(as: AuthModule)` for `@dev`, `@integration`, `@recette`, `@preprod`, `@prod` environments, providing `FirebaseAuth.instance` +- [x] T016 [P] Create `AuthModuleStub` in `lib/core/di/auth/auth_module_stub.dart` registered as `@Singleton(as: AuthModule)` for `@test` environment, providing `MockFirebaseAuth` +- [x] T017 Create `lib/core/di/auth/auth_core_module.dart` barrel export for auth_module, auth_module_impl, auth_module_stub +- [x] T018 Update `lib/core/di/di_module.dart` to export `auth/auth_core_module.dart` +- [x] T019 Create `GoRouterRefreshStream` class in `lib/ui/router.dart` (or a new file `lib/ui/go_router_refresh_stream.dart`) — a `ChangeNotifier` that subscribes to a `Stream` and calls `notifyListeners()` on each event +- [x] T020 Run `dart run build_runner build --delete-conflicting-outputs` to generate Freezed and Injectable code +- [x] T021 Run `flutter analyze` and fix any warnings to zero + +**Checkpoint**: Foundation ready — user story implementation can now begin + +--- + +## Phase 3: User Story 1 — Email/Password Sign-Up (Priority: P1) + +**Goal**: New users can create an account with email and password and land on the home screen + +**Independent Test**: Launch app → navigate to sign-up → enter valid credentials → verify home screen reached + +### Implementation for User Story 1 + +- [x] T022 [US1] Create `SignUpUseCase` in `lib/domain/usecases/auth/sign_up_use_case.dart` as `@singleton`, injecting `AuthRepository`, exposing `Stream call(String email, String password)` with client-side password validation (8+ chars, mixed case, 1 digit) +- [x] T023 [US1] Create `lib/domain/usecases/auth/auth_usecases_module.dart` barrel export for all auth use cases +- [x] T024 [US1] Update `lib/domain/usecases/usecases_module.dart` to export `auth/auth_usecases_module.dart` +- [x] T025 [US1] Create `AuthEvent` Freezed events in `lib/ui/auth/auth_event.dart`: `SignUpRequested(email, password)`, `SignInRequested(email, password)`, `SignOutRequested`, `ResetPasswordRequested(email)`, `AuthStateChanged(AuthUser?)` +- [x] T026 [US1] Create `AuthState` Freezed union in `lib/ui/auth/auth_state.dart`: `AuthInitial`, `AuthLoading`, `AuthAuthenticated(AuthUser)`, `AuthUnauthenticated`, `AuthError(AuthErrorType, String)` +- [x] T027 [US1] Create `AuthInteractor` in `lib/ui/auth/auth_interactor.dart` as `@singleton`, injecting all auth use cases, exposing methods that delegate to use cases +- [x] T028 [US1] Create `AuthBloc` in `lib/ui/auth/auth_bloc.dart` taking `AuthInteractor`, handling `SignUpRequested` → `AuthLoading` → `AuthAuthenticated`/`AuthError` +- [x] T029 [P] [US1] Create `AuthEmailField` stateless widget in `lib/ui/auth/view/components/auth_email_field.dart` — email text field with format validation +- [x] T030 [P] [US1] Create `AuthPasswordField` stateless widget in `lib/ui/auth/view/components/auth_password_field.dart` — password field with visibility toggle and complexity hint +- [x] T031 [P] [US1] Create `AuthSubmitButton` stateless widget in `lib/ui/auth/view/components/auth_submit_button.dart` — submit button that disables during loading state +- [x] T032 [US1] Create `LoginPage` in `lib/ui/auth/view/login_page.dart` — initializes `AuthBloc` via `BlocProvider.create` with `AuthInteractor` from `getIt` +- [x] T033 [US1] Create `LoginView` in `lib/ui/auth/view/login_view.dart` — sign-in and sign-up tabs using `BlocBuilder`, composing email field, password field, submit button. Show error messages from `AuthError` state +- [x] T034 [US1] Create `AuthModule` (UI) in `lib/ui/auth/auth_module.dart` implementing `UIModule`, registering `/login` route pointing to `LoginPage` via `_appRouter.addRoute(...)` +- [x] T035 [US1] Update `AppRouter` in `lib/ui/router.dart` to add `refreshListenable: GoRouterRefreshStream(authStateChanges)` and a global `redirect` callback: unauthenticated users → `/login`, authenticated users on `/login` → `/` +- [x] T036 [US1] Run `dart run build_runner build --delete-conflicting-outputs` +- [x] T037 [US1] Run `flutter analyze` and verify zero warnings +- [x] T038 [US1] Run `flutter test` and verify all existing tests still pass + +**Checkpoint**: User Story 1 complete — sign-up works end-to-end, route protection active + +--- + +## Phase 4: User Story 2 — Email/Password Sign-In (Priority: P1) + +**Goal**: Returning users can sign in with existing credentials + +**Independent Test**: Sign out → enter existing credentials on sign-in tab → verify home screen reached + +### Implementation for User Story 2 + +- [x] T039 [US2] Create `SignInUseCase` in `lib/domain/usecases/auth/sign_in_use_case.dart` as `@singleton`, injecting `AuthRepository`, exposing `Stream call(String email, String password)` +- [x] T040 [US2] Update `lib/domain/usecases/auth/auth_usecases_module.dart` to export `sign_in_use_case.dart` +- [x] T041 [US2] Update `AuthInteractor` in `lib/ui/auth/auth_interactor.dart` to add sign-in delegation method +- [x] T042 [US2] Add `SignInRequested` event handling in `AuthBloc` at `lib/ui/auth/auth_bloc.dart` → `AuthLoading` → `AuthAuthenticated`/`AuthError` +- [x] T043 [US2] Update `LoginView` in `lib/ui/auth/view/login_view.dart` to dispatch `SignInRequested` event from sign-in tab submit +- [x] T044 [US2] Run `dart run build_runner build --delete-conflicting-outputs` +- [x] T045 [US2] Run `flutter analyze` and `flutter test` + +**Checkpoint**: User Stories 1 AND 2 complete — sign-up and sign-in both work independently + +--- + +## Phase 5: User Story 3 — Password Reset (Priority: P2) + +**Goal**: Users who forgot their password can request a reset email + +**Independent Test**: On login screen → tap "Forgot password" → enter email → verify confirmation message + +### Implementation for User Story 3 + +- [x] T046 [US3] Create `ResetPasswordUseCase` in `lib/domain/usecases/auth/reset_password_use_case.dart` as `@singleton`, injecting `AuthRepository`, exposing `Stream call(String email)` +- [x] T047 [US3] Update `lib/domain/usecases/auth/auth_usecases_module.dart` to export `reset_password_use_case.dart` +- [x] T048 [US3] Update `AuthInteractor` in `lib/ui/auth/auth_interactor.dart` to add reset password delegation +- [x] T049 [US3] Create `ForgotPasswordView` in `lib/ui/auth/view/forgot_password_view.dart` — email field + submit, shows confirmation message on success, uses `BlocBuilder` +- [x] T050 [US3] Add `ResetPasswordRequested` event handling in `AuthBloc` at `lib/ui/auth/auth_bloc.dart` +- [x] T051 [US3] Update `AuthModule` (UI) in `lib/ui/auth/auth_module.dart` to register `/login/forgot-password` route pointing to a page wrapping `ForgotPasswordView` +- [x] T052 [US3] Update `LoginView` in `lib/ui/auth/view/login_view.dart` to add "Forgot password" link navigating to `/login/forgot-password` +- [x] T053 [US3] Run `dart run build_runner build --delete-conflicting-outputs` +- [x] T054 [US3] Run `flutter analyze` and `flutter test` + +**Checkpoint**: User Stories 1, 2, and 3 complete — sign-up, sign-in, and password reset all work + +--- + +## Phase 6: User Story 4 — Sign-Out (Priority: P2) + +**Goal**: Authenticated users can sign out and are redirected to login + +**Independent Test**: Sign in → trigger sign-out → verify redirect to `/login` → verify back button does not return to home + +### Implementation for User Story 4 + +- [x] T055 [US4] Create `SignOutUseCase` in `lib/domain/usecases/auth/sign_out_use_case.dart` as `@singleton`, injecting `AuthRepository`, exposing `Stream call()` +- [x] T056 [US4] Update `lib/domain/usecases/auth/auth_usecases_module.dart` to export `sign_out_use_case.dart` +- [x] T057 [US4] Update `AuthInteractor` in `lib/ui/auth/auth_interactor.dart` to add sign-out delegation +- [x] T058 [US4] Add `SignOutRequested` event handling in `AuthBloc` at `lib/ui/auth/auth_bloc.dart` +- [x] T059 [US4] Add a sign-out trigger to the home screen or app shell (e.g., an action in `AppBar` or a settings menu). Location depends on existing UI — add to the `ShellRoute` builder in `lib/ui/router.dart` or to a dedicated settings feature +- [x] T060 [US4] Run `dart run build_runner build --delete-conflicting-outputs` +- [x] T061 [US4] Run `flutter analyze` and `flutter test` + +**Checkpoint**: User Stories 1–4 complete — full auth lifecycle except session persistence + +--- + +## Phase 7: User Story 5 — Persistent Session (Priority: P3) + +**Goal**: Returning users are automatically signed in when reopening the app + +**Independent Test**: Sign in → force-close app → reopen → verify landing on home screen without sign-in + +### Implementation for User Story 5 + +- [x] T062 [US5] Create `WatchAuthStateUseCase` in `lib/domain/usecases/auth/watch_auth_state_use_case.dart` as `@singleton`, injecting `AuthRepository`, exposing `Stream call()` +- [x] T063 [US5] Update `lib/domain/usecases/auth/auth_usecases_module.dart` to export `watch_auth_state_use_case.dart` +- [x] T064 [US5] Update `AuthInteractor` in `lib/ui/auth/auth_interactor.dart` to expose `watchAuthState` stream +- [x] T065 [US5] Update `AuthBloc` in `lib/ui/auth/auth_bloc.dart` to subscribe to `watchAuthState` on initialization, emitting `AuthAuthenticated` or `AuthUnauthenticated` based on stream events. This handles both app-start session check and token expiry/revocation +- [x] T066 [US5] Verify that `GoRouterRefreshStream` in `lib/ui/router.dart` correctly triggers redirect re-evaluation on auth state changes (session restore and expiry) +- [x] T067 [US5] Run `dart run build_runner build --delete-conflicting-outputs` +- [x] T068 [US5] Run `flutter analyze` and `flutter test` + +**Checkpoint**: All user stories complete — full authentication system functional + +--- + +## Phase 8: Polish & Cross-Cutting Concerns + +**Purpose**: Quality improvements that affect multiple user stories + +- [x] T069 [P] Verify all `*_module.dart` barrel exports are complete and no cross-layer imports exist (Constitution Principle I) +- [x] T070 [P] Verify no DTOs leak into `domain/` or `ui/` layers (Constitution Principle II) +- [x] T071 [P] Verify all async flows use `Stream`, not `Future` (Constitution Principle II) +- [x] T072 Create BDD feature file `test/gherkin/features/auth_sign_up.feature` with Gherkin scenarios from spec.md US1 +- [x] T073 Create BDD feature file `test/gherkin/features/auth_sign_in.feature` with Gherkin scenarios from spec.md US2 +- [x] T074 Create BDD feature file `test/gherkin/features/auth_sign_out.feature` with Gherkin scenarios from spec.md US4 +- [x] T075 Create step implementations for auth BDD tests in `test/gherkin/steps/` +- [x] T076 Run `flutter test` — all tests MUST pass +- [x] T077 Run `flutter analyze` — zero warnings +- [ ] T078 Run quickstart.md validation (manual walkthrough of all flows) + +--- + +## Dependencies & Execution Order + +### Phase Dependencies + +- **Setup (Phase 1)**: No dependencies — start immediately +- **Foundational (Phase 2)**: Depends on Setup — BLOCKS all user stories +- **User Story 1 (Phase 3)**: Depends on Foundational +- **User Story 2 (Phase 4)**: Depends on Foundational. Shares BLoC/UI from US1, so execute after US1 +- **User Story 3 (Phase 5)**: Depends on Foundational. Extends login UI from US1, so execute after US1 +- **User Story 4 (Phase 6)**: Depends on Foundational. Extends BLoC from US1, so execute after US1 +- **User Story 5 (Phase 7)**: Depends on Foundational. Extends BLoC and router from US1, so execute after US1 +- **Polish (Phase 8)**: Depends on all user stories being complete + +### User Story Dependencies + +- **US1 (Sign-Up)**: Creates the auth BLoC, login UI, and route protection — serves as the foundation for all other stories +- **US2 (Sign-In)**: Extends US1's BLoC and login view. Can start after US1 +- **US3 (Password Reset)**: Extends US1's login view and BLoC. Can start after US1. Independent of US2 +- **US4 (Sign-Out)**: Extends US1's BLoC. Can start after US1. Independent of US2 and US3 +- **US5 (Session Persistence)**: Extends US1's BLoC and router. Can start after US1. Independent of US2–US4 + +### Within Each User Story + +- Use cases before BLoC event handlers +- BLoC before UI views +- Module exports updated after each new file +- `build_runner` after Freezed/Injectable changes +- `flutter analyze` and `flutter test` at end of each phase + +### Parallel Opportunities + +- T005, T006, T007, T008 (domain entities + DTO) — all different files +- T015, T016 (auth module impl + stub) — different files +- T029, T030, T031 (UI components) — all stateless widgets, different files +- T069, T070, T071 (verification tasks) — independent checks +- US2, US3, US4, US5 can all run in parallel AFTER US1 completes (if multiple developers available) + +--- + +## Parallel Example: Foundational Phase + +```bash +# Launch all entity/DTO tasks together: +Task: "Create AuthErrorType enum in lib/domain/entities/auth_error_type.dart" +Task: "Create AuthException class in lib/domain/entities/auth_exception.dart" +Task: "Create AuthUser Freezed entity in lib/domain/entities/auth_user.dart" +Task: "Create AuthUserDto in lib/data/dto/auth_user_dto.dart" + +# Then launch auth module impl + stub together: +Task: "Create AuthModuleImpl in lib/core/di/auth/auth_module_impl.dart" +Task: "Create AuthModuleStub in lib/core/di/auth/auth_module_stub.dart" +``` + +## Parallel Example: User Story 1 + +```bash +# Launch all UI components together: +Task: "Create AuthEmailField in lib/ui/auth/view/components/auth_email_field.dart" +Task: "Create AuthPasswordField in lib/ui/auth/view/components/auth_password_field.dart" +Task: "Create AuthSubmitButton in lib/ui/auth/view/components/auth_submit_button.dart" +``` + +--- + +## Implementation Strategy + +### MVP First (User Story 1 Only) + +1. Complete Phase 1: Setup +2. Complete Phase 2: Foundational (CRITICAL — blocks all stories) +3. Complete Phase 3: User Story 1 (Sign-Up) +4. **STOP and VALIDATE**: Test sign-up end-to-end, verify route protection +5. Deploy/demo if ready — users can create accounts + +### Incremental Delivery + +1. Setup + Foundational → Foundation ready +2. Add US1 (Sign-Up) → Test → Deploy/Demo (MVP!) +3. Add US2 (Sign-In) → Test → Deploy/Demo (returning users) +4. Add US3 (Password Reset) + US4 (Sign-Out) → Test → Deploy/Demo (full lifecycle) +5. Add US5 (Session Persistence) → Test → Deploy/Demo (polish) +6. BDD tests + verification → Production ready + +### Parallel Team Strategy + +With multiple developers after Foundational phase: + +1. Team completes Setup + Foundational together +2. Developer A: User Story 1 (required first — creates shared BLoC/UI) +3. Once US1 is done, in parallel: + - Developer A: User Story 2 + - Developer B: User Story 3 + - Developer C: User Story 4 + - Developer D: User Story 5 +4. Final: BDD tests and polish + +--- + +## Notes + +- [P] tasks = different files, no dependencies +- [Story] label maps task to specific user story for traceability +- Each user story is independently testable once US1 provides the base +- Verify tests pass after each phase before moving to next +- Commit after each task or logical group +- All async domain→UI flows MUST use `Stream` (Constitution Principle II) +- All new files MUST be exported via `*_module.dart` (Constitution Principle I) diff --git a/test/gherkin/features/auth_sign_in.feature b/test/gherkin/features/auth_sign_in.feature new file mode 100644 index 0000000..4b275ed --- /dev/null +++ b/test/gherkin/features/auth_sign_in.feature @@ -0,0 +1,16 @@ +Feature: Email/Password Sign-In + + Scenario: Successful sign-in with valid credentials + Given the user is on the sign-in screen + When they enter valid credentials + Then they are authenticated and redirected to the home screen + + Scenario: Sign-in with incorrect password + Given the user is on the sign-in screen + When they enter an incorrect password + Then they see an error message indicating invalid credentials + + Scenario: Sign-in with non-existent email + Given the user is on the sign-in screen + When they enter an email that does not correspond to any account + Then they see a generic invalid credentials error diff --git a/test/gherkin/features/auth_sign_out.feature b/test/gherkin/features/auth_sign_out.feature new file mode 100644 index 0000000..ea16e23 --- /dev/null +++ b/test/gherkin/features/auth_sign_out.feature @@ -0,0 +1,11 @@ +Feature: Sign-Out + + Scenario: Successful sign-out + Given the user is authenticated + When they tap sign out + Then their session is terminated and they are redirected to the sign-in screen + + Scenario: Back button after sign-out + Given the user has signed out + When they press the back button + Then they cannot access any authenticated screen diff --git a/test/gherkin/features/auth_sign_up.feature b/test/gherkin/features/auth_sign_up.feature new file mode 100644 index 0000000..015214d --- /dev/null +++ b/test/gherkin/features/auth_sign_up.feature @@ -0,0 +1,21 @@ +Feature: Email/Password Sign-Up + + Scenario: Successful sign-up with valid credentials + Given the user is on the sign-up screen + When they enter a valid email and a password meeting complexity requirements and submit + Then their account is created and they are redirected to the home screen + + Scenario: Sign-up with existing email + Given the user is on the sign-up screen + When they enter an email already associated with an existing account + Then they see an error message indicating the email is already in use + + Scenario: Sign-up with weak password + Given the user is on the sign-up screen + When they enter a password that does not meet complexity requirements + Then they see a specific error describing the password policy + + Scenario: Sign-up with invalid email format + Given the user is on the sign-up screen + When they enter an invalid email format + Then they see an error indicating the email format is incorrect diff --git a/test/gherkin/steps/auth_steps.dart b/test/gherkin/steps/auth_steps.dart new file mode 100644 index 0000000..00965ab --- /dev/null +++ b/test/gherkin/steps/auth_steps.dart @@ -0,0 +1,73 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +// Sign-Up steps + +Future theUserIsOnTheSignUpScreen(WidgetTester tester) async { + // Navigate to sign-up tab + final signUpTab = find.text('Sign Up'); + if (signUpTab.evaluate().isNotEmpty) { + await tester.tap(signUpTab); + await tester.pumpAndSettle(); + } +} + +Future theyEnterAValidEmailAndPasswordAndSubmit( + WidgetTester tester) async { + await tester.enterText( + find.byType(TextFormField).first, + 'test@example.com', + ); + await tester.enterText( + find.byType(TextFormField).last, + 'Password1', + ); + await tester.tap(find.text('Create Account')); + await tester.pumpAndSettle(); +} + +// Sign-In steps + +Future theUserIsOnTheSignInScreen(WidgetTester tester) async { + final signInTab = find.text('Sign In'); + if (signInTab.evaluate().isNotEmpty) { + await tester.tap(signInTab); + await tester.pumpAndSettle(); + } +} + +Future theyEnterValidCredentialsAndSubmit(WidgetTester tester) async { + await tester.enterText( + find.byType(TextFormField).first, + 'test@example.com', + ); + await tester.enterText( + find.byType(TextFormField).last, + 'Password1', + ); + await tester.tap(find.text('Sign In')); + await tester.pumpAndSettle(); +} + +// Sign-Out steps + +Future theUserIsAuthenticated(WidgetTester tester) async { + // Verify user is on home screen + expect(find.text('Home'), findsOneWidget); +} + +Future theyTapSignOut(WidgetTester tester) async { + await tester.tap(find.byIcon(Icons.logout)); + await tester.pumpAndSettle(); +} + +// Assertions + +Future theyAreRedirectedToTheHomeScreen(WidgetTester tester) async { + expect(find.text('Welcome!'), findsOneWidget); +} + +Future theyAreRedirectedToTheSignInScreen(WidgetTester tester) async { + expect(find.text('Welcome'), findsOneWidget); + expect(find.text('Sign In'), findsOneWidget); +} diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc index 8b6d468..d141b74 100644 --- a/windows/flutter/generated_plugin_registrant.cc +++ b/windows/flutter/generated_plugin_registrant.cc @@ -6,6 +6,12 @@ #include "generated_plugin_registrant.h" +#include +#include void RegisterPlugins(flutter::PluginRegistry* registry) { + FirebaseAuthPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseAuthPluginCApi")); + FirebaseCorePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseCorePluginCApi")); } diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake index b93c4c3..29944d5 100644 --- a/windows/flutter/generated_plugins.cmake +++ b/windows/flutter/generated_plugins.cmake @@ -3,6 +3,8 @@ # list(APPEND FLUTTER_PLUGIN_LIST + firebase_auth + firebase_core ) list(APPEND FLUTTER_FFI_PLUGIN_LIST