diff --git a/documentation/CLAUDE.md b/documentation/CLAUDE.md index 1a791f9..3e2e7f0 100644 --- a/documentation/CLAUDE.md +++ b/documentation/CLAUDE.md @@ -1,22 +1,9 @@ # Claude MCPs Quick Guide -This project uses Model Context Protocols (MCPs) to enhance development. +This project is configured for Claude development but no specific MCP servers are currently selected. -## BrowserMCP -- **Key**: browsermcp -- **Setup Command**: `claude mcp add browsermcp -- npx -y @browsermcp/mcp@latest` -- **Documentation**: https://docs.browsermcp.io +## What are MCP Servers? +Model Context Protocols (MCPs) enhance Claude's capabilities by providing access to external tools and services. -## Context7 -- **Key**: context7 -- **Setup Command**: `claude mcp add --transport http context7 https://mcp.context7.com/mcp` -- **Documentation**: https://context7.com - -## Quick Setup -1. BrowserMCP: `claude mcp add browsermcp -- npx -y @browsermcp/mcp@latest` -2. Context7: `claude mcp add --transport http context7 https://mcp.context7.com/mcp` - -## Tips -- Make sure Claude Desktop is installed and configured -- Restart Claude Desktop after adding new MCP servers -- Check the documentation links for detailed usage instructions +## Getting Started +Add MCP servers to enhance your development workflow with additional capabilities. diff --git a/documentation/app_flowchart.md b/documentation/app_flowchart.md new file mode 100644 index 0000000..cfb1cb2 --- /dev/null +++ b/documentation/app_flowchart.md @@ -0,0 +1,31 @@ +flowchart TD + Home[Home Page] --> Search[Search Repositories] + Search --> SearchAPI[Call API github search] + SearchAPI --> GitHubOcto[Octokit Query GitHub] + GitHubOcto --> SearchAPI + SearchAPI --> DisplayResults[Display Results] + DisplayResults --> RepoSelect[Select Repository] + RepoSelect --> DetailPage[Repository Detail Page] + DetailPage --> AnalyzeAPI[Call API github analyze] + AnalyzeAPI --> GitHubOcto + GitHubOcto --> AnalyzeAPI + AnalyzeAPI --> DisplayAnalysis[Display Analysis] + DetailPage --> AIChat[AI Powered Chat] + AIChat --> ChatAPI[Call API ai chat] + ChatAPI --> VercelAI[Vercel AI SDK] + VercelAI --> ChatAPI + ChatAPI --> AIChat + Home --> Favorites[Favorites Page] + Favorites --> FavAPI[Call API github favorites] + FavAPI --> SupabaseDB[Supabase Data Store] + SupabaseDB --> FavAPI + FavAPI --> Favorites + Home --> Dashboard[Dashboard Page] + Dashboard --> StatsAPI[Call API dashboard stats] + StatsAPI --> SupabaseDB + SupabaseDB --> StatsAPI + StatsAPI --> Dashboard + Home --> Auth[User Authentication] + Auth --> ClerkAuth[Clerk Auth Service] + ClerkAuth --> Auth + Auth --> Home \ No newline at end of file diff --git a/documentation/backend_structure_document.md b/documentation/backend_structure_document.md index 1b0b5c1..28d2987 100644 --- a/documentation/backend_structure_document.md +++ b/documentation/backend_structure_document.md @@ -1,146 +1,253 @@ # Backend Structure Document -This document outlines the backend setup for the CodeGuide Starter Kit Lite v2. It explains how each piece fits together so that anyone—even without a deep technical background—can understand the architecture, databases, APIs, hosting, and infrastructure components. +This document outlines the complete backend setup for the `git-search` application. It covers the overall architecture, database design, APIs, hosting, infrastructure, security, and maintenance practices in clear, everyday language. ## 1. Backend Architecture -**Overview:** -- The backend is built on Next.js (App Router) running serverless functions. -- Each API route lives under `src/app/api/` and handles a single concern (for example, chat or data access). -- Business logic is organized into small modules under `src/lib/` (e.g., Supabase client setup, environment checks, AI utilities). - -**Design Patterns and Frameworks:** -- Next.js App Router for file-based routing and serverless functions. -- Functional programming style: each route exports a handler function. -- Dependency injection via environment variables (API keys, database URLs). -- Middleware (`middleware.ts`) to protect routes with Clerk authentication. - -**Scalability, Maintainability, and Performance:** -- Serverless functions auto-scale with demand—no manual server management. -- Modular code organization makes it easy to add, update, or remove features. -- Vercel’s global edge network ensures low latency for users worldwide. -- Caching strategies (cache headers, SWR on the client) help reduce repeated data fetching. +The backend of `git-search` is built with a modern serverless approach, leveraging Next.js’s App Router for both page rendering and API routes. Here’s how it’s organized and why it works: + +• Design Patterns & Frameworks + - **Next.js 15 (App Router):** Handles server-side rendering (SSR), static site generation (SSG), and API routes in one framework. API routes are treated as serverless functions that scale automatically. + - **TypeScript:** Applies type safety across the entire codebase, reducing bugs and improving developer productivity. + - **Layered Structure:** Separates code into directories (`app`, `components`, `hooks`, `lib`, `types`) for clear concerns: + • `app/`: Pages, layouts, and API endpoints. + • `components/`: Reusable UI elements. + • `hooks/`: Custom React hooks for data fetching. + • `lib/`: Utility functions and external client configurations (Supabase, Octokit). + • `types/`: Shared TypeScript interfaces. + +• Scalability & Performance + - **Serverless Functions:** Each API route scales independently on Vercel. + - **Stateless Design:** Functions don’t hold session data in memory; user sessions are managed by Clerk and Supabase. + - **Edge Caching & CDN:** Vercel’s global network caches static assets and serverless responses, reducing latency. + - **Database Connection Pooling:** Supabase’s managed PostgreSQL handles connections efficiently under load. + +• Maintainability + - **Modular Code:** Clear folder structure makes it easy to locate and update features. + - **Environment Validation:** At startup, the app checks that critical environment variables are present. + - **Migrations:** Supabase SQL migration files track all database schema changes. + +**Key Backend Tech Stack** +- Next.js 15 (App Router) +- TypeScript +- Clerk (authentication) +- Supabase (PostgreSQL + RLS) +- Octokit (GitHub API client) +- Vercel AI SDK +- Docker (dev container) ## 2. Database Management -**Database Technology:** -- Type: SQL (relational) -- System: Supabase (hosted PostgreSQL with real-time and authentication layers) +The project uses Supabase’s managed PostgreSQL service as its primary data store. Here’s how data is handled: -**How Data Is Structured and Accessed:** -- Data lives in tables inside Supabase. -- Row Level Security (RLS) policies ensure users only see their own data. -- Server-side code uses the Supabase client library (`@supabase/supabase-js`) for CRUD operations. -- Client-side code can also fetch or subscribe to real-time updates when needed. +• Database Type & System + - **SQL Database:** PostgreSQL hosted by Supabase. + - **Managed Service:** Automatic backups, high availability, and performance tuning provided by Supabase. -**Data Management Practices:** -- Migrations and schema changes live in the `supabase/` folder. -- Environment variable checks prevent missing or misconfigured keys. -- Zod schemas validate incoming data before writing to the database. +• Data Organization & Access + - **Tables:** Stores user-specific data such as favorites, chat histories, and search logs. + - **Row-Level Security (RLS):** Ensures each user only sees their own data based on policies defined per table. + - **Migrations:** All schema changes are scripted as SQL files under the `supabase/` folder, ensuring version control. + +• Data Practices + - **Environment Isolation:** Separate development, staging, and production databases. + - **Backups & Point-in-Time Recovery:** Supabase automatically backs up data and allows recovery to any point in time. + - **Connection Pooling:** Supabase pools database connections to handle spikes in traffic without exhausting resources. ## 3. Database Schema -Below is the main schema for storing AI chat history. It uses PostgreSQL syntax. +Below is a human-friendly overview of the main tables, followed by SQL definitions for PostgreSQL. + +### Human-Readable Table Descriptions + +1. **users** + Holds basic profile data for each authenticated user. User IDs originate from Clerk. + - Fields: id, email, created_at + +2. **favorites** + Tracks which GitHub repositories a user has favorited. + - Fields: id, user_id, repo_id, repo_name, added_at + +3. **featured_repositories** + Lists a curated set of repositories to highlight on the home page. + - Fields: id, repo_id, repo_name, description, featured_at + +4. **search_history** + Logs each user’s search queries for analytics and dashboard charts. + - Fields: id, user_id, query_text, searched_at + +5. **chat_history** + Records AI chat interactions per repository per user. + - Fields: id, user_id, repo_id, user_message, ai_response, chatted_at + +### PostgreSQL Schema Definitions ```sql --- Table to group messages into conversations (optional) -CREATE TABLE conversations ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - user_id UUID NOT NULL, -- references auth.users - title TEXT, -- optional summary - created_at TIMESTAMPTZ NOT NULL DEFAULT now() +-- 1. Users +CREATE TABLE users ( + id TEXT PRIMARY KEY, + email TEXT NOT NULL UNIQUE, + created_at TIMESTAMP WITH TIME ZONE DEFAULT now() ); --- Table to store individual chat messages -CREATE TABLE messages ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - conversation_id UUID REFERENCES conversations(id) ON DELETE CASCADE, - user_id UUID NOT NULL, -- references auth.users - role TEXT NOT NULL CHECK (role IN ('user','assistant')), - content TEXT NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT now() +-- 2. Favorites +CREATE TABLE favorites ( + id BIGSERIAL PRIMARY KEY, + user_id TEXT REFERENCES users(id) ON DELETE CASCADE, + repo_id TEXT NOT NULL, + repo_name TEXT NOT NULL, + added_at TIMESTAMP WITH TIME ZONE DEFAULT now() ); --- Example RLS policy: only allow users to see their own messages -ALTER TABLE messages ENABLE ROW LEVEL SECURITY; -CREATE POLICY "Users can access their own messages" ON messages - FOR SELECT USING (user_id = auth.uid()); -``` +-- 3. Featured Repositories +CREATE TABLE featured_repositories ( + id BIGSERIAL PRIMARY KEY, + repo_id TEXT NOT NULL, + repo_name TEXT NOT NULL, + description TEXT, + featured_at TIMESTAMP WITH TIME ZONE DEFAULT now() +); -If you’re not using conversations, you can omit the `conversations` table and let each message stand alone. +-- 4. Search History +CREATE TABLE search_history ( + id BIGSERIAL PRIMARY KEY, + user_id TEXT REFERENCES users(id) ON DELETE CASCADE, + query_text TEXT NOT NULL, + searched_at TIMESTAMP WITH TIME ZONE DEFAULT now() +); + +-- 5. Chat History +CREATE TABLE chat_history ( + id BIGSERIAL PRIMARY KEY, + user_id TEXT REFERENCES users(id) ON DELETE CASCADE, + repo_id TEXT NOT NULL, + user_message TEXT NOT NULL, + ai_response TEXT NOT NULL, + chatted_at TIMESTAMP WITH TIME ZONE DEFAULT now() +); +``` ## 4. API Design and Endpoints -**Approach:** REST-style endpoints built as Next.js serverless functions. All endpoints live under `src/app/api/`. +The backend exposes a set of RESTful API endpoints under `/api` to support frontend actions. All routes live in `src/app/api/`. -**Key Endpoints:** +• GitHub Integration + - **GET /api/github/search** + • Purpose: Search GitHub repositories by keywords. + • Process: Uses Octokit to call GitHub REST API and returns results. -- **POST /api/chat** - Purpose: Accepts a list of prior messages and a new user prompt, forwards to the Vercel AI SDK, streams AI responses back to the client, and optionally stores the conversation in Supabase. + - **GET /api/github/repository/[id]** + • Purpose: Fetch detailed metadata for a single repository. + • Process: Uses Octokit and formats the response. -- **GET /api/chat/history?conversationId=...** - Purpose: Returns the saved message history for a given conversation (if implemented). + - **POST /api/github/analyze** + • Purpose: Trigger an in-depth analysis (commit history, file tree). + • Process: Combines multiple GitHub API calls and returns structured data. -- **GET /api/user/profile** - Purpose: Returns basic user information from Clerk (via middleware) or Supabase if extended user data is stored there. +• Favorites Management + - **GET /api/github/favorites** + • Purpose: List the user’s favorited repositories. + • Process: Queries the `favorites` table in Supabase. -Each endpoint: -- Checks authentication via Clerk middleware. -- Validates input with Zod. -- Interacts with Supabase and/or Vercel AI SDK. -- Returns JSON with clear status codes (200 for success, 4xx for client errors). + - **POST /api/github/favorites** + • Purpose: Add a repository to favorites. + • Payload: `{ repo_id, repo_name }` + • Process: Inserts a row into `favorites` with the current user. + + - **DELETE /api/github/favorites** + • Purpose: Remove a repository from favorites. + • Payload: `{ favorite_id }` + • Process: Deletes the corresponding row. + +• AI-Powered Chat + - **POST /api/chat** + • Purpose: Send user questions and get AI-driven insights on a repository. + • Payload: `{ repo_id, message }` + • Process: Forwards to Vercel AI SDK, stores conversation in `chat_history`, returns AI response. + +• Dashboard & Analytics + - **GET /api/dashboard/stats** + • Purpose: Retrieve user-specific metrics (search counts, favorite counts). + • Process: Aggregates data from `search_history`, `favorites`, and `chat_history` tables. + +• Featured Repositories + - **GET /api/repositories/featured** + • Purpose: Fetch the curated list of featured repositories. + • Process: Reads from `featured_repositories` table. + +Authentication guards all endpoints dealing with user data. Clerk issues a user token that the Next.js middleware verifies before proceeding. ## 5. Hosting Solutions -**Primary Hosting:** Vercel -- Automatically builds and deploys the Next.js application on every git push. -- Runs serverless functions for API routes—no need to manage servers. -- Built-in CDN for static assets (images, CSS, JS). +• Vercel (Primary Platform) + - Hosts the Next.js application and API routes as serverless functions. + - Offers automatic SSL, global CDN, and instant rollbacks. + - Scales on demand—no manual server management needed. -**Development Environment:** -- Docker setup via `.devcontainer/` for consistent local development. -- `devcontainer.json` defines Node version, extensions, and environment variable requirements. +• Supabase (Database) + - Managed PostgreSQL with built-in authentication hooks and Row-Level Security. + - Provides real-time capabilities if the app grows to need live updates. -**Benefits:** -- Zero-config auto-scaling and global edge network for fast response times. -- Pay-as-you-go pricing—only pay for what you use. -- Simple environment variable management in the Vercel dashboard. +• Docker Dev Container + - Ensures every developer has a consistent local environment. + - Mirrors production Node.js and tooling versions. ## 6. Infrastructure Components -- **Load Balancer / Edge Network:** Provided by Vercel—distributes requests globally for low latency. -- **CDN:** Vercel CDN caches static and dynamic content at edge locations. -- **Caching Mechanisms:** - • Next.js `cache-control` headers - • Client-side SWR (stale-while-revalidate) for data fetching -- **Database Hosting:** Supabase managed PostgreSQL with read replicas and automatic backups. -- **Authentication Service:** Clerk’s hosted service handles sign-up, sign-in, and session management. +• Load Balancing & Routing + - Vercel handles traffic distribution across serverless functions behind the scenes. + +• Caching + - **Vercel Edge Cache:** Caches static assets and SSR responses at edge locations. + - **In-Memory/Database Side:** Supabase caches query plans and uses PostgreSQL’s shared buffer. + +• Content Delivery Network (CDN) + - Vercel’s built-in CDN distributes static files and API route responses globally. -Together, these components ensure a smooth, fast experience for end users and an easy-to-manage infrastructure for developers. +• Connection Pooling & Queuing + - **Supabase Pooling:** Prevents database overload. + - **Vercel Functions:** Queue up function invocations when under heavy load. ## 7. Security Measures -- **Authentication:** Clerk protects routes and issues session tokens/cookies. -- **Authorization:** Supabase Row Level Security (RLS) ensures users only access their own rows. -- **Data Encryption:** - • TLS in transit (HTTPS everywhere) - • Encryption at rest on the database provider’s side -- **Input Validation:** Zod schemas on all API inputs to prevent malicious payloads. -- **Environment Variables:** Secrets never checked into source control; managed via Vercel dashboard or local `.env` files. -- **HTTP Security Headers:** Configurable via Next.js custom headers (e.g., CSP, HSTS) if needed. +• Authentication & Authorization + - **Clerk:** Manages sign-up, sign-in, and session tokens. + - **Next.js Middleware:** Verifies Clerk session on protected routes and API endpoints. + - **Row-Level Security (RLS):** Enforced at the database level so each user can only read/write their own rows. + +• Data Encryption + - **In Transit:** HTTPS everywhere (Vercel + Supabase). + - **At Rest:** Supabase encrypts the database storage. + +• Environment Validation + - Startup script checks for required environment variables—prevents misconfiguration in production. + +• Best Practices + - Secrets (API keys, database URLs) stored in environment variables, never in code. + - Rate limiting (to be added) for external GitHub API calls to avoid abuse. ## 8. Monitoring and Maintenance -- **Performance Monitoring:** - • Vercel Analytics to track edge function performance and page load times. - • Supabase dashboard for database performance and query statistics. -- **Error Tracking:** Integration with Sentry or Logflare to capture unhandled exceptions in serverless routes. -- **Logging:** Console logs in Next.js functions appear in Vercel’s Logs panel. -- **Migrations:** Supabase migrations stored in `supabase/migrations/`. Run `supabase db push` or `supabase db migrate` as part of CI. -- **CI/CD:** - • GitHub (or GitLab) integration triggers Vercel builds on each push. - • Optional GitHub Actions for linting, type checking, and testing before merge. +• Logging & Alerts + - **Vercel Dashboard Logs:** Real-time logs for serverless function errors and performance metrics. + - **Supabase Monitoring:** Tracks database performance, errors, and query statistics. + +• Performance Monitoring + - **Vercel Analytics:** Measures page load times, response times, and bandwidth usage. + - **Next.js Telemetry:** Optional opt-in metrics about build and runtime performance. + +• Maintenance Strategies + - **Database Migrations:** All schema changes go through versioned SQL files. + - **Automated Backups:** Handled by Supabase with point-in-time recovery windows. + - **Dependency Updates:** Regularly run dependency checks and patch critical vulnerabilities. ## 9. Conclusion and Overall Backend Summary -The backend of CodeGuide Starter Kit Lite v2 is built for clarity, performance, and easy scaling. By combining Next.js serverless functions, Supabase for a managed PostgreSQL database with real-time features, Clerk for secure user authentication, and the Vercel AI SDK for seamless AI chat integration, we’ve created a robust foundation. Automated hosting on Vercel and clear modular code practices make maintenance straightforward, while RLS, HTTPS, and input validation ensure user data stays safe. This backend setup aligns tightly with the project goal of delivering a modern, extensible starter kit that developers can pick up and build on immediately. \ No newline at end of file +The `git-search` backend is a cohesive, serverless system built around Next.js API routes and a managed PostgreSQL database. It leverages modern tools—Clerk for auth, Supabase for data, Vercel for hosting—and follows best practices for scalability, security, and maintainability. Key strengths include: + +- **Auto-Scaling Serverless Functions:** Ensures the API handles bursts of traffic without manual intervention. +- **Row-Level Security:** Provides strong data isolation per user. +- **Clear Modular Structure:** Facilitates quick onboarding and feature expansion. +- **Global Performance:** CDN, caching, and SSR keep response times low worldwide. + +This setup aligns perfectly with the project goal: offering users fast, secure, and insightful interactions with GitHub repositories, while keeping the infrastructure simple to operate and evolve. \ No newline at end of file diff --git a/documentation/feature/enhance-landing-page-ui/CLAUDE.md b/documentation/feature/enhance-landing-page-ui/CLAUDE.md new file mode 100644 index 0000000..3e2e7f0 --- /dev/null +++ b/documentation/feature/enhance-landing-page-ui/CLAUDE.md @@ -0,0 +1,9 @@ +# Claude MCPs Quick Guide + +This project is configured for Claude development but no specific MCP servers are currently selected. + +## What are MCP Servers? +Model Context Protocols (MCPs) enhance Claude's capabilities by providing access to external tools and services. + +## Getting Started +Add MCP servers to enhance your development workflow with additional capabilities. diff --git a/documentation/feature/enhance-landing-page-ui/app_flowchart.md b/documentation/feature/enhance-landing-page-ui/app_flowchart.md new file mode 100644 index 0000000..cfb1cb2 --- /dev/null +++ b/documentation/feature/enhance-landing-page-ui/app_flowchart.md @@ -0,0 +1,31 @@ +flowchart TD + Home[Home Page] --> Search[Search Repositories] + Search --> SearchAPI[Call API github search] + SearchAPI --> GitHubOcto[Octokit Query GitHub] + GitHubOcto --> SearchAPI + SearchAPI --> DisplayResults[Display Results] + DisplayResults --> RepoSelect[Select Repository] + RepoSelect --> DetailPage[Repository Detail Page] + DetailPage --> AnalyzeAPI[Call API github analyze] + AnalyzeAPI --> GitHubOcto + GitHubOcto --> AnalyzeAPI + AnalyzeAPI --> DisplayAnalysis[Display Analysis] + DetailPage --> AIChat[AI Powered Chat] + AIChat --> ChatAPI[Call API ai chat] + ChatAPI --> VercelAI[Vercel AI SDK] + VercelAI --> ChatAPI + ChatAPI --> AIChat + Home --> Favorites[Favorites Page] + Favorites --> FavAPI[Call API github favorites] + FavAPI --> SupabaseDB[Supabase Data Store] + SupabaseDB --> FavAPI + FavAPI --> Favorites + Home --> Dashboard[Dashboard Page] + Dashboard --> StatsAPI[Call API dashboard stats] + StatsAPI --> SupabaseDB + SupabaseDB --> StatsAPI + StatsAPI --> Dashboard + Home --> Auth[User Authentication] + Auth --> ClerkAuth[Clerk Auth Service] + ClerkAuth --> Auth + Auth --> Home \ No newline at end of file diff --git a/documentation/feature/enhance-landing-page-ui/backend_structure_document.md b/documentation/feature/enhance-landing-page-ui/backend_structure_document.md new file mode 100644 index 0000000..28d2987 --- /dev/null +++ b/documentation/feature/enhance-landing-page-ui/backend_structure_document.md @@ -0,0 +1,253 @@ +# Backend Structure Document + +This document outlines the complete backend setup for the `git-search` application. It covers the overall architecture, database design, APIs, hosting, infrastructure, security, and maintenance practices in clear, everyday language. + +## 1. Backend Architecture + +The backend of `git-search` is built with a modern serverless approach, leveraging Next.js’s App Router for both page rendering and API routes. Here’s how it’s organized and why it works: + +• Design Patterns & Frameworks + - **Next.js 15 (App Router):** Handles server-side rendering (SSR), static site generation (SSG), and API routes in one framework. API routes are treated as serverless functions that scale automatically. + - **TypeScript:** Applies type safety across the entire codebase, reducing bugs and improving developer productivity. + - **Layered Structure:** Separates code into directories (`app`, `components`, `hooks`, `lib`, `types`) for clear concerns: + • `app/`: Pages, layouts, and API endpoints. + • `components/`: Reusable UI elements. + • `hooks/`: Custom React hooks for data fetching. + • `lib/`: Utility functions and external client configurations (Supabase, Octokit). + • `types/`: Shared TypeScript interfaces. + +• Scalability & Performance + - **Serverless Functions:** Each API route scales independently on Vercel. + - **Stateless Design:** Functions don’t hold session data in memory; user sessions are managed by Clerk and Supabase. + - **Edge Caching & CDN:** Vercel’s global network caches static assets and serverless responses, reducing latency. + - **Database Connection Pooling:** Supabase’s managed PostgreSQL handles connections efficiently under load. + +• Maintainability + - **Modular Code:** Clear folder structure makes it easy to locate and update features. + - **Environment Validation:** At startup, the app checks that critical environment variables are present. + - **Migrations:** Supabase SQL migration files track all database schema changes. + +**Key Backend Tech Stack** +- Next.js 15 (App Router) +- TypeScript +- Clerk (authentication) +- Supabase (PostgreSQL + RLS) +- Octokit (GitHub API client) +- Vercel AI SDK +- Docker (dev container) + +## 2. Database Management + +The project uses Supabase’s managed PostgreSQL service as its primary data store. Here’s how data is handled: + +• Database Type & System + - **SQL Database:** PostgreSQL hosted by Supabase. + - **Managed Service:** Automatic backups, high availability, and performance tuning provided by Supabase. + +• Data Organization & Access + - **Tables:** Stores user-specific data such as favorites, chat histories, and search logs. + - **Row-Level Security (RLS):** Ensures each user only sees their own data based on policies defined per table. + - **Migrations:** All schema changes are scripted as SQL files under the `supabase/` folder, ensuring version control. + +• Data Practices + - **Environment Isolation:** Separate development, staging, and production databases. + - **Backups & Point-in-Time Recovery:** Supabase automatically backs up data and allows recovery to any point in time. + - **Connection Pooling:** Supabase pools database connections to handle spikes in traffic without exhausting resources. + +## 3. Database Schema + +Below is a human-friendly overview of the main tables, followed by SQL definitions for PostgreSQL. + +### Human-Readable Table Descriptions + +1. **users** + Holds basic profile data for each authenticated user. User IDs originate from Clerk. + - Fields: id, email, created_at + +2. **favorites** + Tracks which GitHub repositories a user has favorited. + - Fields: id, user_id, repo_id, repo_name, added_at + +3. **featured_repositories** + Lists a curated set of repositories to highlight on the home page. + - Fields: id, repo_id, repo_name, description, featured_at + +4. **search_history** + Logs each user’s search queries for analytics and dashboard charts. + - Fields: id, user_id, query_text, searched_at + +5. **chat_history** + Records AI chat interactions per repository per user. + - Fields: id, user_id, repo_id, user_message, ai_response, chatted_at + +### PostgreSQL Schema Definitions + +```sql +-- 1. Users +CREATE TABLE users ( + id TEXT PRIMARY KEY, + email TEXT NOT NULL UNIQUE, + created_at TIMESTAMP WITH TIME ZONE DEFAULT now() +); + +-- 2. Favorites +CREATE TABLE favorites ( + id BIGSERIAL PRIMARY KEY, + user_id TEXT REFERENCES users(id) ON DELETE CASCADE, + repo_id TEXT NOT NULL, + repo_name TEXT NOT NULL, + added_at TIMESTAMP WITH TIME ZONE DEFAULT now() +); + +-- 3. Featured Repositories +CREATE TABLE featured_repositories ( + id BIGSERIAL PRIMARY KEY, + repo_id TEXT NOT NULL, + repo_name TEXT NOT NULL, + description TEXT, + featured_at TIMESTAMP WITH TIME ZONE DEFAULT now() +); + +-- 4. Search History +CREATE TABLE search_history ( + id BIGSERIAL PRIMARY KEY, + user_id TEXT REFERENCES users(id) ON DELETE CASCADE, + query_text TEXT NOT NULL, + searched_at TIMESTAMP WITH TIME ZONE DEFAULT now() +); + +-- 5. Chat History +CREATE TABLE chat_history ( + id BIGSERIAL PRIMARY KEY, + user_id TEXT REFERENCES users(id) ON DELETE CASCADE, + repo_id TEXT NOT NULL, + user_message TEXT NOT NULL, + ai_response TEXT NOT NULL, + chatted_at TIMESTAMP WITH TIME ZONE DEFAULT now() +); +``` + +## 4. API Design and Endpoints + +The backend exposes a set of RESTful API endpoints under `/api` to support frontend actions. All routes live in `src/app/api/`. + +• GitHub Integration + - **GET /api/github/search** + • Purpose: Search GitHub repositories by keywords. + • Process: Uses Octokit to call GitHub REST API and returns results. + + - **GET /api/github/repository/[id]** + • Purpose: Fetch detailed metadata for a single repository. + • Process: Uses Octokit and formats the response. + + - **POST /api/github/analyze** + • Purpose: Trigger an in-depth analysis (commit history, file tree). + • Process: Combines multiple GitHub API calls and returns structured data. + +• Favorites Management + - **GET /api/github/favorites** + • Purpose: List the user’s favorited repositories. + • Process: Queries the `favorites` table in Supabase. + + - **POST /api/github/favorites** + • Purpose: Add a repository to favorites. + • Payload: `{ repo_id, repo_name }` + • Process: Inserts a row into `favorites` with the current user. + + - **DELETE /api/github/favorites** + • Purpose: Remove a repository from favorites. + • Payload: `{ favorite_id }` + • Process: Deletes the corresponding row. + +• AI-Powered Chat + - **POST /api/chat** + • Purpose: Send user questions and get AI-driven insights on a repository. + • Payload: `{ repo_id, message }` + • Process: Forwards to Vercel AI SDK, stores conversation in `chat_history`, returns AI response. + +• Dashboard & Analytics + - **GET /api/dashboard/stats** + • Purpose: Retrieve user-specific metrics (search counts, favorite counts). + • Process: Aggregates data from `search_history`, `favorites`, and `chat_history` tables. + +• Featured Repositories + - **GET /api/repositories/featured** + • Purpose: Fetch the curated list of featured repositories. + • Process: Reads from `featured_repositories` table. + +Authentication guards all endpoints dealing with user data. Clerk issues a user token that the Next.js middleware verifies before proceeding. + +## 5. Hosting Solutions + +• Vercel (Primary Platform) + - Hosts the Next.js application and API routes as serverless functions. + - Offers automatic SSL, global CDN, and instant rollbacks. + - Scales on demand—no manual server management needed. + +• Supabase (Database) + - Managed PostgreSQL with built-in authentication hooks and Row-Level Security. + - Provides real-time capabilities if the app grows to need live updates. + +• Docker Dev Container + - Ensures every developer has a consistent local environment. + - Mirrors production Node.js and tooling versions. + +## 6. Infrastructure Components + +• Load Balancing & Routing + - Vercel handles traffic distribution across serverless functions behind the scenes. + +• Caching + - **Vercel Edge Cache:** Caches static assets and SSR responses at edge locations. + - **In-Memory/Database Side:** Supabase caches query plans and uses PostgreSQL’s shared buffer. + +• Content Delivery Network (CDN) + - Vercel’s built-in CDN distributes static files and API route responses globally. + +• Connection Pooling & Queuing + - **Supabase Pooling:** Prevents database overload. + - **Vercel Functions:** Queue up function invocations when under heavy load. + +## 7. Security Measures + +• Authentication & Authorization + - **Clerk:** Manages sign-up, sign-in, and session tokens. + - **Next.js Middleware:** Verifies Clerk session on protected routes and API endpoints. + - **Row-Level Security (RLS):** Enforced at the database level so each user can only read/write their own rows. + +• Data Encryption + - **In Transit:** HTTPS everywhere (Vercel + Supabase). + - **At Rest:** Supabase encrypts the database storage. + +• Environment Validation + - Startup script checks for required environment variables—prevents misconfiguration in production. + +• Best Practices + - Secrets (API keys, database URLs) stored in environment variables, never in code. + - Rate limiting (to be added) for external GitHub API calls to avoid abuse. + +## 8. Monitoring and Maintenance + +• Logging & Alerts + - **Vercel Dashboard Logs:** Real-time logs for serverless function errors and performance metrics. + - **Supabase Monitoring:** Tracks database performance, errors, and query statistics. + +• Performance Monitoring + - **Vercel Analytics:** Measures page load times, response times, and bandwidth usage. + - **Next.js Telemetry:** Optional opt-in metrics about build and runtime performance. + +• Maintenance Strategies + - **Database Migrations:** All schema changes go through versioned SQL files. + - **Automated Backups:** Handled by Supabase with point-in-time recovery windows. + - **Dependency Updates:** Regularly run dependency checks and patch critical vulnerabilities. + +## 9. Conclusion and Overall Backend Summary + +The `git-search` backend is a cohesive, serverless system built around Next.js API routes and a managed PostgreSQL database. It leverages modern tools—Clerk for auth, Supabase for data, Vercel for hosting—and follows best practices for scalability, security, and maintainability. Key strengths include: + +- **Auto-Scaling Serverless Functions:** Ensures the API handles bursts of traffic without manual intervention. +- **Row-Level Security:** Provides strong data isolation per user. +- **Clear Modular Structure:** Facilitates quick onboarding and feature expansion. +- **Global Performance:** CDN, caching, and SSR keep response times low worldwide. + +This setup aligns perfectly with the project goal: offering users fast, secure, and insightful interactions with GitHub repositories, while keeping the infrastructure simple to operate and evolve. \ No newline at end of file diff --git a/documentation/feature/enhance-landing-page-ui/frontend_guidelines_document.md b/documentation/feature/enhance-landing-page-ui/frontend_guidelines_document.md new file mode 100644 index 0000000..ff591ae --- /dev/null +++ b/documentation/feature/enhance-landing-page-ui/frontend_guidelines_document.md @@ -0,0 +1,149 @@ +# Frontend Guideline Document + +This document outlines the frontend setup for the **git-search** application. It covers the architecture, design principles, styling, component structure, state management, routing, performance strategies, testing, and a summary. The goal is to give anyone—technical or not—a clear picture of how the frontend is built and why it works the way it does. + +## 1. Frontend Architecture + +### Frameworks and Libraries +- **Next.js 15 (App Router)**: Provides page routing, server-side rendering (SSR), static site generation (SSG), and built-in API routes. Its file-based routing keeps things simple. +- **TypeScript**: Adds type safety, reducing runtime errors and improving code readability. +- **React Server Components**: Used for data fetching on the server, which shrinks the client bundle and boosts performance. +- **Tailwind CSS v4**: A utility-first CSS framework for rapid, consistent styling without writing custom CSS. +- **shadcn/ui**: A set of accessible, customizable UI components built on Radix UI and styled by Tailwind. +- **next-themes**: Manages light/dark mode toggles. +- **Clerk**: Handles user authentication, sign-up, sign-in, and session management. +- **Supabase (PostgreSQL)**: Our managed database, complete with real-time features and row-level security (RLS). +- **Vercel AI SDK**: Connects to AI models (OpenAI, Anthropic Claude) for chat-based insights. +- **Octokit**: Official GitHub API client for interacting with GitHub’s REST API. +- **Vercel**: Deployment platform with seamless Next.js support. +- **Docker (.devcontainer)**: Ensures a consistent development environment across machines. + +### Scalability, Maintainability, Performance +- **Server Components & API Routes** keep heavy data work on the server, shrinking frontend bundles and speeding up load times. +- **TypeScript** and clear folder structure (`app/`, `components/`, `hooks/`, `lib/`, `types/`) help teams scale without confusion. +- **Utility-first CSS** (Tailwind) avoids large custom stylesheets and unused CSS, making style maintenance easy. +- **Managed Services** (Clerk, Supabase, Vercel) offload infrastructure concerns, letting us focus on app features. + +## 2. Design Principles + +### Usability +- Clear and consistent navigation (search bar always visible, simple page layouts). +- Immediate feedback for user actions (loading spinners, toast messages). + +### Accessibility +- All interactive elements use semantic HTML and ARIA attributes when needed. +- Color contrasts meet WCAG AA guidelines. +- Keyboard-friendly components (dialogs, dropdowns) via `shadcn/ui`. + +### Responsiveness +- Mobile-first design ensures layouts and components adapt from small to large screens. +- Tailwind breakpoints manage layout shifts smoothly. + +### Application in UI +- Buttons, cards, dialogs follow a consistent look-and-feel. +- Form inputs and error states are uniform across pages. +- Loading and error states use shared components for predictability. + +## 3. Styling and Theming + +### Styling Approach +- **Utility-first CSS** with Tailwind (no BEM or SMACSS). We rely on Tailwind’s classes for margins, paddings, typography, and colors. +- Global styles (Tailwind base, components, utilities) are imported in `globals.css`. + +### Theming +- **next-themes** handles theme context (`light` and `dark`). We wrap the root layout in a `ThemeProvider`. +- Theme toggle is a shared component (`ThemeToggle`) that switches classes on ``. + +### Visual Style +- **Overall Feel**: Modern flat design with subtle glassmorphism touches on select cards (slightly blurred translucent backgrounds) to highlight AI chat and featured repositories. + +### Color Palette +- Primary: #3B82F6 (blue-500) +- Secondary: #6366F1 (indigo-500) +- Accent: #F59E0B (amber-500) +- Background Light: #F9FAFB (gray-50) +- Background Dark: #111827 (gray-900) +- Surface Light: #FFFFFF (white) +- Surface Dark: #1F2937 (gray-800) +- Text Light: #111827 (gray-900) +- Text Dark: #F3F4F6 (gray-100) + +### Fonts +- **Primary Font**: Inter, sans-serif +- **Fallbacks**: system-ui, -apple-system, BlinkMacSystemFont + +## 4. Component Structure + +### Organization +- `src/components/`: Reusable React components. + - `ui/`: shadcn/ui primitives (buttons, inputs, dialogs). + - App-specific components (`Chat`, `ThemeToggle`, `RepositoryCard`). +- `src/app/`: Next.js app router (pages, layouts, API routes). +- `src/hooks/`: Custom hooks (`useRepositorySearch`, `useDashboardStats`). +- `src/lib/`: Client configs and utilities (Supabase client, `env-check`). +- `src/types/`: TypeScript interfaces and types. + +### Benefits of Component-Based Architecture +- **Reusability**: Build once, use everywhere (e.g., `Button`, `Card`). +- **Isolation**: Changes in one component rarely affect others. +- **Clarity**: Easy to locate and update specific UI parts. + +## 5. State Management + +### Approaches and Libraries +- **React Query** (via a `QueryProvider`): Manages server state (data fetching, caching, background updates). +- **React Context**: Shares theme and auth state (through Clerk’s provider and `next-themes`). +- **Local State**: `useState` and `useReducer` for component-specific states (form inputs, modal open/close). + +### Data Flow +1. Component calls a custom hook (e.g., `useRepositorySearch`). +2. Hook uses React Query to fetch from an internal API route. +3. React Query caches and shares data across components. +4. UI components read query data and show loading/error states automatically. + +## 6. Routing and Navigation + +### Routing +- **Next.js App Router**: File-based routing (`src/app/page.tsx`, `src/app/search/page.tsx`, etc.). +- Dynamic segments (`[slug]`) for repository detail pages. + +### Protected Routes +- **Middleware** (`middleware.ts`): Checks Clerk session and redirects unauthorized users away from `/dashboard` or `/favorites`. + +### Navigation Structure +- Top-level menu or header with links to Home, Search, Dashboard, Favorites. +- `next/link` ensures client-side transitions. +- Breadcrumbs on detail pages for easy back navigation. + +## 7. Performance Optimization + +- **Server Components** reduce client JS bundle size. +- **SSR/SSG**: Pre-renders key pages for instant load. +- **Code Splitting**: Next.js automatically splits by route. +- **Lazy Loading**: Dynamic `import()` for heavy components (e.g., AI chat panel). +- **Image Optimization**: Next.js `Image` component auto-optimizes images. +- **Tailwind Purge**: Removes unused CSS in production builds. +- **Caching**: React Query caches API responses. Consider adding Redis or edge caching for GitHub data in the future. + +## 8. Testing and Quality Assurance + +### Testing Strategies +- **Unit Tests**: Jest or Vitest + React Testing Library for components, hooks, and utilities. +- **Integration Tests**: API route tests to simulate GitHub and Supabase interactions (using mocks). +- **End-to-End (E2E) Tests**: Playwright or Cypress to cover core user flows (search, login, favorite). + +### Tools and Configuration +- **ESLint** with a shared config (`eslint.config.mjs`) for linting rules. +- **Prettier** (`.prettierrc`) for consistent formatting. +- **TypeScript** (`tsconfig.json`) to catch type errors early. +- **Git Hooks** (via Husky or simple npm scripts) to run linters and tests before commits. + +## 9. Conclusion and Overall Frontend Summary + +The **git-search** frontend is built with a modern, scalable stack centered on Next.js and TypeScript. We prioritize: +- **Performance**: Server components, SSR/SSG, code splitting. +- **Maintainability**: Clear folder structure, TypeScript, utility-first styling. +- **Accessibility**: Semantic HTML, ARIA attributes, accessible UI components. +- **User Experience**: Responsive design, theming, fast feedback. + +By following these guidelines—consistent design principles, component-based architecture, robust state management, and thorough testing—we ensure the frontend remains reliable, easy to extend, and aligned with user needs as the application grows. diff --git a/documentation/feature/enhance-landing-page-ui/project_requirements_document.md b/documentation/feature/enhance-landing-page-ui/project_requirements_document.md new file mode 100644 index 0000000..25a2c0b --- /dev/null +++ b/documentation/feature/enhance-landing-page-ui/project_requirements_document.md @@ -0,0 +1,83 @@ +# Project Requirements Document (PRD) + +## 1. Project Overview + +**git-search** is a full-stack web application built with Next.js that lets developers and curious users search, explore, and analyze GitHub repositories in a single, user-friendly interface. Beyond simple keyword lookups, it offers in-depth repository metrics (commit history, file structure, contributor stats) and an AI-powered chat assistant that can explain code patterns, suggest improvements, and answer natural-language questions about any repo. Users can sign up to personalize their experience, save favorite repositories, and monitor their activity on a custom dashboard. + +The project exists to bridge the gap between raw GitHub data and meaningful insights. Instead of jumping between pages on GitHub and separate analytics tools, users can stay in one place to discover projects, dive deep into their health and trends, and get AI-driven explanations. Key success criteria include fast search response times, accurate repository analysis, reliable AI chat interactions, secure and seamless authentication, and an intuitive UI with both light and dark themes. + +## 2. In-Scope vs. Out-of-Scope + +**In-Scope (Version 1):** +- GitHub repository search by keyword, topic, or criteria. +- Detailed repository analysis (commit history, file tree, contributor stats, code metrics). +- AI-powered chat interface for natural-language insights (using OpenAI and Anthropic Claude via Vercel AI SDK). +- User authentication (sign-up/sign-in) and session management via Clerk. +- Favorites management: add/remove bookmarks stored in Supabase with Row-Level Security. +- Personalized dashboard showing search history, favorites count, recent AI chats, and basic usage stats. +- Light and dark theme toggling using next-themes. +- Serverless API routes for search, analysis, AI chat, favorites, and dashboard stats. + +**Out-of-Scope (Phase 1):** +- Direct pull request creation or issue management on GitHub. +- In-browser code editing or live previews of repository code. +- Enterprise or on-premises deployment support. +- Mobile-specific native apps (iOS/Android) or PWA offline support. +- Advanced analytics (e.g., graph visualizations, time-series comparisons) beyond basic stats. +- Third-party integrations beyond GitHub and AI models (e.g., Jira, Slack). + +## 3. User Flow + +A new visitor lands on the homepage, which prominently features a search bar. They type keywords and hit “Search.” Behind the scenes, the frontend calls the `/api/github/search` endpoint, which uses Octokit to fetch matching repositories. Results appear in a paginated list with repo name, description, star count, and a “View Details” button. The user clicks a repo, and the app navigates to `/repository/[slug]`, where detailed stats (commit history, file structure, contributor breakdown) are displayed server-side for performance. + +If the visitor wants to save a repo, they click “Sign Up,” complete the Clerk-powered authentication flow, and return to the repo page. Logged-in users can favorite repositories, which triggers a POST to `/api/github/favorites`. Their favorites list is visible under `/favorites`, and their dashboard at `/dashboard` shows saved repos, search usage patterns, and recent AI chats. On any repo page, users can open the chat widget, type questions (“How many contributors were active last month?”), and receive AI-generated insights, powered by the Vercel AI SDK. + +## 4. Core Features + +- **Authentication**: Clerk handles user sign-up, sign-in, and session management. Protects `/dashboard` and `/favorites` with middleware. +- **Search Module**: Frontend component and `/api/github/search` route that queries GitHub via Octokit and returns paginated results. +- **Repository Analysis**: Detailed view powered by `/api/github/repository/[id]` and `/api/github/analyze` routes fetching commit history, file tree, and statistics. +- **AI Chat Interface**: Reusable React component that sends user prompts to Vercel AI SDK, selectable between OpenAI and Anthropic Claude models, and displays responses conversationally. +- **Favorites Management**: Protected API routes to add/remove favorites in Supabase, leveraging RLS to isolate each user’s data. +- **Dashboard & Analytics**: Aggregates user activity via `/api/dashboard/stats` (search count, favorites count, recent chats) and displays charts or summary cards. +- **Theming**: Global light/dark mode toggle using next-themes, persisted in `localStorage`. +- **API Layer**: Next.js serverless routes under `src/app/api` for all back-end interactions (GitHub, Supabase, AI). + +## 5. Tech Stack & Tools + +- Frontend: Next.js 15 (App Router), React 18 Server and Client Components, TypeScript. +- Styling & UI: Tailwind CSS v4, shadcn/ui (Radix UI + Tailwind), next-themes. +- Authentication: Clerk.js. +- Database: Supabase (PostgreSQL) with Row-Level Security for favorites. +- AI Integration: Vercel AI SDK connecting to OpenAI GPT-4 and Anthropic Claude. +- GitHub API: Octokit REST client. +- Deployment: Vercel serverless platform. +- Development Environment: Docker devcontainer, VS Code with ESLint & Prettier, optional Cursor or Windsurf plugins for AI-powered coding assistance. + +## 6. Non-Functional Requirements + +- **Performance:** Page load under 2 seconds on a 3G connection. Search results returned in under 1 second. AI chat responses in under 1.5 seconds. +- **Scalability:** Support up to 5,000 daily users without manual scaling; leverage Vercel auto-scaling and Supabase managed infrastructure. +- **Security:** HTTPS everywhere; Clerk session tokens with HTTP-only cookies; Supabase RLS enforced; OWASP Top 10 mitigations in API routes. +- **Compliance:** GDPR-compatible data storage; clear privacy policy; opt-out for analytics. +- **Usability & Accessibility:** WCAG 2.1 AA standards; keyboard navigable; ARIA attributes on custom components; color contrast checks. + +## 7. Constraints & Assumptions + +- **GitHub API Rate Limits:** 5,000 requests/hour per OAuth app. Assume caching or rate-limiting logic is needed. +- **AI Model Availability:** Dependent on OpenAI/Anthropic quotas and response times. Assume keys and quotas are provisioned. +- **Environment Variables:** Validated at startup via `lib/env-check.ts`. Must include GitHub token, Clerk credentials, Supabase URL/key, AI API keys. +- **Next.js App Router:** Requires Node.js 18+ and Vercel platform features. +- **User Base:** Primarily English-speaking developers/researchers. + +## 8. Known Issues & Potential Pitfalls + +- **API Rate Limiting:** Exceeding GitHub limits may lead to 403 errors. Mitigation: implement server-side caching (in-memory or Redis) for repeated queries. +- **AI Model Cost & Latency:** Heavy chat usage can incur high costs and slower responses. Mitigation: add usage quotas per user and fallback static suggestions when AI delays. +- **Data Consistency:** Concurrent favorites operations could conflict. Mitigation: use Supabase transactions and optimistic UI updates. +- **SSR vs. CSR Data Fetching:** Over-fetching in Server Components may slow page builds. Mitigation: split heavy data calls to client components or use incremental static regeneration (ISR). +- **Environment Drift:** Developers may miss environment variable updates. Mitigation: include comprehensive `.env.example` and pre-launch environment checks. + +--- + +This PRD provides a clear, unambiguous reference for the AI model and subsequent technical documents, ensuring every feature, flow, and constraint is fully specified for implementation. \ No newline at end of file diff --git a/documentation/feature/enhance-landing-page-ui/security_guideline_document.md b/documentation/feature/enhance-landing-page-ui/security_guideline_document.md new file mode 100644 index 0000000..a91370d --- /dev/null +++ b/documentation/feature/enhance-landing-page-ui/security_guideline_document.md @@ -0,0 +1,117 @@ +# Git-Search Security Guidelines + +This document provides actionable, project-specific security guidance for the **git-search** repository, following “secure by design” principles. It covers authentication, data protection, API hardening, deployment, and ongoing practices to ensure robust security throughout the application lifecycle. + +--- + +## 1. Security by Design & Governance + +- Embed security reviews in every sprint: include threat modeling when adding new features (e.g., AI chat, favorites). +- Define security owners for authentication, data handling, and deployment pipelines. +- Enforce least privilege at every layer: code, database, cloud functions. +- Automate checks using CI/CD: linting, SCA (Software Composition Analysis), static analysis (e.g., ESLint with security rules, Snyk). + +## 2. Authentication & Access Control + +1. **Clerk Configuration** + - Enforce strong password complexity and rotation policies. + - Enable multi-factor authentication (MFA) for all user accounts. + - Validate JWTs server-side: check `alg`, `iss`, `aud`, and expiration (`exp`). + +2. **Session & Cookie Security** + - Use `Secure`, `HttpOnly`, and `SameSite=Strict` on session cookies. + - Implement idle and absolute session timeouts; provide explicit logout endpoint. + - Protect API routes against session fixation by regenerating session IDs on login. + +3. **Role-Based Access Control (RBAC)** + - Define roles (e.g., `guest`, `user`, `admin`) and map permissions explicitly in middleware (`src/middleware.ts`). + - Enforce server-side checks on all protected routes: `/dashboard`, `/favorites`, `/api/github/favorites`. + - Use Supabase Row-Level Security (RLS) to isolate user data; review policies regularly. + +## 3. Input Validation & Output Encoding + +- Use a runtime schema library (e.g., Zod) to validate all API inputs: + * Query parameters (`/api/github/search?query=`) + * Dynamic path segments (`/[owner]/[repo]`) + * Request bodies for chat, favorites, and analysis endpoints. +- Sanitize outputs rendered in React components; avoid `dangerouslySetInnerHTML`. When necessary, whitelist tags and attributes. +- Prevent injection in Supabase queries by using the official client library and parameterized calls—never concatenate SQL strings. +- Validate and whitelist redirect URLs to avoid open-redirect attacks. + +## 4. Data Protection & Privacy + +- Enforce TLS 1.2+ on all Next.js serverless functions and web traffic. Do not allow HTTP. +- **Environment secrets**: + * Store Clerk API keys, Supabase credentials, and GitHub tokens in Vercel Environment Variables or a secrets manager (e.g., AWS Secrets Manager, Vault). + * Use `lib/env-check.ts` to fail startup if required variables are missing. +- Avoid logging sensitive PII or raw tokens. Mask or redact values in logs. +- For personally identifiable information (e.g., user email), comply with GDPR/CCPA: + * Provide deletion endpoints. + * Log consent. + +## 5. API & Service Security + +1. **Rate Limiting & Throttling** + - Implement per-IP and per-user rate limits on critical endpoints (`/api/github/*`, `/api/chat`). + - Use an in-memory or Redis cache layer for ephemeral rate counters. + +2. **CORS Configuration** + - Restrict `Access-Control-Allow-Origin` to your production and staging domains only. + +3. **Least Privilege for API Keys** + - Create a GitHub App or fine-scoped personal access token limited to read-only repository search and metadata. + - Scope Supabase service roles to only the required tables and operations. + +4. **API Versioning** + - Prefix internal API routes with version numbers (e.g., `/api/v1/github/search`) to manage future changes securely. + +## 6. Web Application Security Hygiene + +- **Content Security Policy (CSP):** + * Default to `self` for scripts, styles, and connect endpoints. + * Allow only the AI service domains (OpenAI, Anthropic) and GitHub API in `connect-src`. +- **Security Headers:** + * `Strict-Transport-Security: max-age=63072000; includeSubDomains; preload` + * `X-Frame-Options: DENY` + * `X-Content-Type-Options: nosniff` + * `Referrer-Policy: no-referrer-when-downgrade` +- **CSRF Protection:** + * Use anti-CSRF tokens (synchronizer token pattern) on state-changing forms and fetch calls. +- **Subresource Integrity (SRI):** + * When loading third-party scripts (e.g., analytics), include integrity hashes and `crossorigin` attributes. + +## 7. Infrastructure & Configuration Management + +- **Vercel & Docker**: + * Disable Next.js debugger and verbose logs in production builds (`NODE_ENV=production`). + * Limit serverless function timeouts to prevent DoS amplification. +- **Server Hardening**: + * Disable unnecessary ports and services on any custom servers. + * Use up-to-date TLS cipher suites (ECDHE, AES-GCM) and disable TLS 1.0/1.1. +- **File Permissions**: + * Ensure uploaded files (if any) are stored outside the webroot with restricted filesystem permissions. + +## 8. Dependency Management + +- Maintain `package-lock.json` to freeze known-good versions. +- Regularly run automated vulnerability scans (e.g., `npm audit`, Snyk) and update dependencies. +- Vet all major framework upgrades (Next.js, Tailwind, Clerk, Supabase, Octokit) for breaking changes and security fixes. +- Remove unused packages to minimize attack surface. + +## 9. DevOps & CI/CD Security + +- Enforce branch protection and require PR reviews before merging. +- Integrate static analysis tools: + * ESLint with security plugins (e.g., eslint-plugin-security). + * Secrets scanning in CI (e.g., GitHub Secret Scanning). +- Automate deployments only from the `main` branch; require successful tests and security checks. + +## 10. Monitoring, Logging & Incident Response + +- Integrate an error-tracking service (Sentry, LogRocket) for both serverless functions and client-side exceptions. +- Log all authentication events (login, logout, token refresh), but avoid storing raw tokens. +- Define an incident response plan: triage, notification, and post-mortem for security events. + +--- + +By following these project-tailored guidelines, the **git-search** application will maintain strong defenses against common threats, safeguard user data, and uphold best practices for secure web development. Regularly revisit this document as the codebase and threat landscape evolve. diff --git a/documentation/feature/enhance-landing-page-ui/setup.md b/documentation/feature/enhance-landing-page-ui/setup.md new file mode 100644 index 0000000..3c3cf78 --- /dev/null +++ b/documentation/feature/enhance-landing-page-ui/setup.md @@ -0,0 +1,23 @@ +# Project Setup Instructions + +This project includes a tasks.json file that outlines the implementation tasks for this project. + +## Project Implementation + +1. Review the tasks.json file to understand the project requirements and implementation steps +2. Follow the tasks in sequence to implement the project features +3. Each task contains details about what needs to be implemented +4. Move the CLAUDE.md file to your project root for easy reference on using Claude MCPs +5. Set up MCP integrations to enhance your development experience (see below) + +## Next Steps + +- Refer to the tasks.json file for detailed implementation tasks +- Review the other documentation files to understand the project requirements +- Start implementing based on the provided specifications + +## MCP Integrations (Step 5) + +No specific MCP servers are configured for this project. You can add MCP servers later to enhance your development experience. + +For general MCP information, visit the Claude documentation. diff --git a/documentation/feature/enhance-landing-page-ui/tasks.json b/documentation/feature/enhance-landing-page-ui/tasks.json new file mode 100644 index 0000000..7a947f3 --- /dev/null +++ b/documentation/feature/enhance-landing-page-ui/tasks.json @@ -0,0 +1,65 @@ +{ + "tasks": [ + { + "id": 1, + "title": "Initialize Next.js Project with Core Tooling", + "status": "pending", + "details": "- Scaffold a new Next.js 15 project using the App Router and TypeScript.\n- Integrate Tailwind CSS v4 and configure with shadcn/ui (Radix UI + Tailwind).\n- Add next-themes for light/dark mode support.\n- Set up ESLint, Prettier, and VS Code settings for code quality.\n- Create a Docker devcontainer for consistent development environments.\n- Add a comprehensive `.env.example` file and implement `lib/env-check.ts` for environment variable validation at startup.\n- Ensure the project is ready for further feature development and adheres to the specified tech stack.", + "priority": "high", + "description": "Set up the foundational Next.js 15 project structure with TypeScript, Tailwind CSS v4, shadcn/ui, next-themes, and essential development tooling.", + "dependencies": [], + "testStrategy": "- Run the development server and verify the default Next.js page loads.\n- Confirm Tailwind and shadcn/ui styles render correctly.\n- Switch between light and dark themes and verify persistence.\n- Lint and format code to ensure ESLint and Prettier are active.\n- Validate environment variable checks by running with missing/invalid variables." + }, + { + "id": 2, + "title": "Implement Dummy Landing Page UI", + "status": "pending", + "details": "- Build a landing page at `/` using Next.js App Router.\n- Use shadcn/ui components and Tailwind CSS for layout and styling.\n- Include a prominent search bar (non-functional for now), project branding, and a brief description.\n- Add light/dark theme toggle using next-themes.\n- Ensure WCAG 2.1 AA accessibility, keyboard navigation, and ARIA attributes.\n- Prepare for future integration of authentication and search features.", + "priority": "high", + "description": "Create a visually appealing, accessible dummy landing page as the initial homepage for git-search.", + "dependencies": [ + 1 + ], + "testStrategy": "- Load the landing page and verify layout, branding, and dummy search bar are present.\n- Test keyboard navigation and screen reader accessibility.\n- Toggle between light and dark modes and confirm UI updates.\n- Validate responsive design on multiple screen sizes." + }, + { + "id": 3, + "title": "Integrate Clerk Authentication (Sign Up/Sign In)", + "status": "pending", + "details": "- Install and configure Clerk.js with required environment variables.\n- Implement sign-up and sign-in UI flows using Clerk components.\n- Protect `/dashboard` and `/favorites` routes with Clerk middleware.\n- Ensure session management and secure HTTP-only cookies.\n- Prepare for future integration with Supabase and personalized features.", + "priority": "medium", + "description": "Set up Clerk.js for user authentication, enabling sign-up and sign-in flows, and protect relevant routes.", + "dependencies": [ + 1, + 2 + ], + "testStrategy": "- Register a new user and sign in/out, verifying session persistence.\n- Attempt to access protected routes without authentication and confirm redirection.\n- Check that session tokens are stored securely.\n- Validate error handling for failed authentication attempts." + }, + { + "id": 4, + "title": "Set Up Supabase Backend for Favorites", + "status": "pending", + "details": "- Create a Supabase project and configure PostgreSQL schema for favorites.\n- Enable Row-Level Security (RLS) to isolate user data.\n- Add Supabase client to the Next.js project and configure with environment variables.\n- Prepare API routes for adding/removing favorites (implementation in future tasks).\n- Document schema and RLS policies for future reference.", + "priority": "medium", + "description": "Configure Supabase PostgreSQL with Row-Level Security for storing user favorites, and connect it to the Next.js app.", + "dependencies": [ + 1, + 3 + ], + "testStrategy": "- Connect to Supabase from the Next.js app and verify connectivity.\n- Test RLS by attempting to access another user's favorites (should be denied).\n- Validate schema by inserting and querying dummy favorite records.\n- Ensure environment variables are loaded and validated at startup." + }, + { + "id": 5, + "title": "Prepare API Layer Structure and Environment Validation", + "status": "pending", + "details": "- Create `src/app/api` directory for all future serverless API routes (search, analysis, AI chat, favorites, dashboard stats).\n- Implement a shared environment validation utility (`lib/env-check.ts`) that runs at startup and on API route invocation.\n- Ensure all required environment variables (GitHub token, Clerk credentials, Supabase URL/key, AI API keys) are checked and errors are surfaced early.\n- Document the API route structure and validation process for the team.", + "priority": "medium", + "description": "Establish the folder structure and boilerplate for serverless API routes, and ensure robust environment variable validation.", + "dependencies": [ + 1 + ], + "testStrategy": "- Start the app with missing/invalid environment variables and confirm errors are thrown.\n- Access a dummy API route and verify environment validation runs.\n- Check that the API folder structure matches the PRD requirements.\n- Review documentation for clarity and completeness." + } + ], + "expanded_tasks": [] +} \ No newline at end of file diff --git a/documentation/frontend_guidelines_document.md b/documentation/frontend_guidelines_document.md index 0a2be8b..ff591ae 100644 --- a/documentation/frontend_guidelines_document.md +++ b/documentation/frontend_guidelines_document.md @@ -1,146 +1,149 @@ # Frontend Guideline Document -## 1. Frontend Architecture +This document outlines the frontend setup for the **git-search** application. It covers the architecture, design principles, styling, component structure, state management, routing, performance strategies, testing, and a summary. The goal is to give anyone—technical or not—a clear picture of how the frontend is built and why it works the way it does. -### 1.1 Overview -Our frontend is built as a modern Next.js application (v15) using the App Router. We use TypeScript for type safety and clarity. Styling comes from Tailwind CSS v4, and we layer on headless components from shadcn/ui (New York style). Authentication is handled by Clerk, data lives in Supabase (with Row Level Security), and AI features are powered by the Vercel AI SDK (supporting OpenAI and Anthropic Claude). We manage themes using next-themes and state with React Context. A handful of utility libraries (clsx, date-fns, zod, and more) support specialized features. +## 1. Frontend Architecture -### 1.2 Why This Architecture Works -- **Scalability**: Next.js’s file-based routing and API routes let us grow pages and serverless endpoints without complex wiring. Supabase handles scaling the database, and Vercel AI SDK abstracts AI model interactions. -- **Maintainability**: TypeScript plus a clear folder structure (`app/`, `components/`, `lib/`, etc.) keeps code predictable. shadcn/ui components are headless and composable, so we avoid one-off styles. -- **Performance**: We use server-side rendering (SSR) where needed, static generation for public pages, and dynamic imports for large components. Tailwind’s tree-shaking strips unused CSS. Next.js image and script optimizations ensure fast loads. +### Frameworks and Libraries +- **Next.js 15 (App Router)**: Provides page routing, server-side rendering (SSR), static site generation (SSG), and built-in API routes. Its file-based routing keeps things simple. +- **TypeScript**: Adds type safety, reducing runtime errors and improving code readability. +- **React Server Components**: Used for data fetching on the server, which shrinks the client bundle and boosts performance. +- **Tailwind CSS v4**: A utility-first CSS framework for rapid, consistent styling without writing custom CSS. +- **shadcn/ui**: A set of accessible, customizable UI components built on Radix UI and styled by Tailwind. +- **next-themes**: Manages light/dark mode toggles. +- **Clerk**: Handles user authentication, sign-up, sign-in, and session management. +- **Supabase (PostgreSQL)**: Our managed database, complete with real-time features and row-level security (RLS). +- **Vercel AI SDK**: Connects to AI models (OpenAI, Anthropic Claude) for chat-based insights. +- **Octokit**: Official GitHub API client for interacting with GitHub’s REST API. +- **Vercel**: Deployment platform with seamless Next.js support. +- **Docker (.devcontainer)**: Ensures a consistent development environment across machines. + +### Scalability, Maintainability, Performance +- **Server Components & API Routes** keep heavy data work on the server, shrinking frontend bundles and speeding up load times. +- **TypeScript** and clear folder structure (`app/`, `components/`, `hooks/`, `lib/`, `types/`) help teams scale without confusion. +- **Utility-first CSS** (Tailwind) avoids large custom stylesheets and unused CSS, making style maintenance easy. +- **Managed Services** (Clerk, Supabase, Vercel) offload infrastructure concerns, letting us focus on app features. ## 2. Design Principles -### 2.1 Usability -- We keep interfaces clean and consistent: buttons look and behave the same everywhere. -- Form flows (like sign-up and AI chat) guide users with clear labels, inline validation, and helpful error messages. +### Usability +- Clear and consistent navigation (search bar always visible, simple page layouts). +- Immediate feedback for user actions (loading spinners, toast messages). -### 2.2 Accessibility (A11y) -- All interactive elements (buttons, links, inputs) have proper ARIA roles and labels. -- We maintain color contrast ratios above WCAG AA standards. -- Keyboard navigation is fully supported, and focus states are visible. +### Accessibility +- All interactive elements use semantic HTML and ARIA attributes when needed. +- Color contrasts meet WCAG AA guidelines. +- Keyboard-friendly components (dialogs, dropdowns) via `shadcn/ui`. -### 2.3 Responsiveness -- We use Tailwind’s responsive utilities (`sm:`, `md:`, `lg:`) to adapt layouts from mobile to desktop. -- Components flex and wrap naturally (using Flexbox and CSS Grid) so content never overflows. +### Responsiveness +- Mobile-first design ensures layouts and components adapt from small to large screens. +- Tailwind breakpoints manage layout shifts smoothly. -### 2.4 Consistency -- A shared design system (shadcn/ui + theme tokens) ensures spacing, typography, and color usage align across the app. +### Application in UI +- Buttons, cards, dialogs follow a consistent look-and-feel. +- Form inputs and error states are uniform across pages. +- Loading and error states use shared components for predictability. ## 3. Styling and Theming -### 3.1 Styling Approach -- We follow a utility-first approach with Tailwind CSS v4. -- Custom properties (CSS variables) define primary colors, spacing, and fonts. -- For component-level logic (like conditional classes), we use the `clsx` library. - -### 3.2 CSS Methodology -- We don’t adopt BEM or SMACSS explicitly; instead, Tailwind’s atomic classes keep styles modular. -- global styles (e.g., resets) live in `globals.css`, and theme variables in `:root` selectors. - -### 3.3 Theming -- next-themes manages a light and dark theme. -- We define theme tokens (`--color-bg`, `--color-text`, etc.) and update them at runtime. -- The `ThemeToggle` component switches themes and persists the choice in `localStorage`. - -### 3.4 Visual Style -- Overall style: Modern flat design with subtle glassmorphism accents (semi-transparent panels with soft shadows). -- UI components from shadcn/ui ensure a minimal, elegant look. - -### 3.5 Color Palette -| Token | Light Hex | Dark Hex | Usage | -| -------------- | --------- | --------- | ---------------- | -| --color-primary| #1E3A8A | #93C5FD | Buttons, links | -| --color-secondary| #64748B | #475569 | Cards, backgrounds| -| --color-accent | #9333EA | #A78BFA | Highlights | -| --color-bg | #FFFFFF | #0F172A | Page background | -| --color-text | #111827 | #F1F5F9 | Main text | -| --color-danger | #DC2626 | #FCA5A5 | Errors, alerts | - -### 3.6 Typography -- Primary font: Inter (system fallback: -apple-system, BlinkMacSystemFont, sans-serif) -- Headings and body share the same font, with size scale defined in Tailwind config (e.g., `text-xl`, `text-2xl`). +### Styling Approach +- **Utility-first CSS** with Tailwind (no BEM or SMACSS). We rely on Tailwind’s classes for margins, paddings, typography, and colors. +- Global styles (Tailwind base, components, utilities) are imported in `globals.css`. -## 4. Component Structure +### Theming +- **next-themes** handles theme context (`light` and `dark`). We wrap the root layout in a `ThemeProvider`. +- Theme toggle is a shared component (`ThemeToggle`) that switches classes on ``. + +### Visual Style +- **Overall Feel**: Modern flat design with subtle glassmorphism touches on select cards (slightly blurred translucent backgrounds) to highlight AI chat and featured repositories. + +### Color Palette +- Primary: #3B82F6 (blue-500) +- Secondary: #6366F1 (indigo-500) +- Accent: #F59E0B (amber-500) +- Background Light: #F9FAFB (gray-50) +- Background Dark: #111827 (gray-900) +- Surface Light: #FFFFFF (white) +- Surface Dark: #1F2937 (gray-800) +- Text Light: #111827 (gray-900) +- Text Dark: #F3F4F6 (gray-100) + +### Fonts +- **Primary Font**: Inter, sans-serif +- **Fallbacks**: system-ui, -apple-system, BlinkMacSystemFont -### 4.1 Organization -- `src/components/ui/`: shadcn/ui wrapper components and shared UI bits. -- `src/components/`: app-specific components (Chat, ThemeToggle, SetupGuide, etc.). -- `src/app/`: page layouts, route files, and API routes. +## 4. Component Structure -### 4.2 Reusability -- Each component has its own folder with a single TSX file and optional styles or tests. -- Props are fully typed; side effects (hooks) are separated into `src/lib/` when shared. +### Organization +- `src/components/`: Reusable React components. + - `ui/`: shadcn/ui primitives (buttons, inputs, dialogs). + - App-specific components (`Chat`, `ThemeToggle`, `RepositoryCard`). +- `src/app/`: Next.js app router (pages, layouts, API routes). +- `src/hooks/`: Custom hooks (`useRepositorySearch`, `useDashboardStats`). +- `src/lib/`: Client configs and utilities (Supabase client, `env-check`). +- `src/types/`: TypeScript interfaces and types. -### 4.3 Benefits of Component-Based Architecture -- Changes in one component don’t ripple unpredictably. -- Composable pieces speed up new feature development. -- Easier to test and document in isolation. +### Benefits of Component-Based Architecture +- **Reusability**: Build once, use everywhere (e.g., `Button`, `Card`). +- **Isolation**: Changes in one component rarely affect others. +- **Clarity**: Easy to locate and update specific UI parts. ## 5. State Management -### 5.1 Local and Shared State -- Local UI state lives in component state (`useState`, `useReducer`). -- Shared data (user session, theme) lives in React Context providers under `src/app/layout.tsx`. +### Approaches and Libraries +- **React Query** (via a `QueryProvider`): Manages server state (data fetching, caching, background updates). +- **React Context**: Shares theme and auth state (through Clerk’s provider and `next-themes`). +- **Local State**: `useState` and `useReducer` for component-specific states (form inputs, modal open/close). -### 5.2 Patterns and Libraries -- We rely on React Context + hooks for simple cross-component state. -- For forms, we use `react-hook-form` and schema validation with `zod`. -- For API data, we fetch directly via Supabase client or AI SDK; caching is minimal by design but can be extended with React Query if needed. +### Data Flow +1. Component calls a custom hook (e.g., `useRepositorySearch`). +2. Hook uses React Query to fetch from an internal API route. +3. React Query caches and shares data across components. +4. UI components read query data and show loading/error states automatically. ## 6. Routing and Navigation -### 6.1 Next.js App Router -- File-based routing under `src/app/`. Each folder with `page.tsx` becomes a route. -- Nested layouts (`layout.tsx`) share providers and UI structure (header, footer). +### Routing +- **Next.js App Router**: File-based routing (`src/app/page.tsx`, `src/app/search/page.tsx`, etc.). +- Dynamic segments (`[slug]`) for repository detail pages. -### 6.2 Protected Routes -- Clerk’s middleware (`middleware.ts`) guards specific paths (`/dashboard`, `/profile`). -- Unauthenticated users are automatically redirected to Clerk’s sign-in page. +### Protected Routes +- **Middleware** (`middleware.ts`): Checks Clerk session and redirects unauthorized users away from `/dashboard` or `/favorites`. -### 6.3 Navigation Components -- We use shadcn/ui Nav components and `next/link` for internal navigation. -- Mobile menus use `cmdk` or custom popovers for a smooth experience. +### Navigation Structure +- Top-level menu or header with links to Home, Search, Dashboard, Favorites. +- `next/link` ensures client-side transitions. +- Breadcrumbs on detail pages for easy back navigation. ## 7. Performance Optimization -### 7.1 Code Splitting & Lazy Loading -- Dynamic imports (`next/dynamic`) for heavy or rarely used components (e.g., chat transcript viewer). -- Inline critical CSS via Tailwind’s JIT engine. - -### 7.2 Asset Optimization -- Next.js Image component handles image resizing and lazy loading. -- SVG icons (via lucide-react) are inlined for faster paint. - -### 7.3 Caching and Server-Side Rendering -- Public pages use static generation (`export const revalidate`). -- Private pages use SSR with Clerk session checks. -- HTTP caching headers set in Next.js config where appropriate. +- **Server Components** reduce client JS bundle size. +- **SSR/SSG**: Pre-renders key pages for instant load. +- **Code Splitting**: Next.js automatically splits by route. +- **Lazy Loading**: Dynamic `import()` for heavy components (e.g., AI chat panel). +- **Image Optimization**: Next.js `Image` component auto-optimizes images. +- **Tailwind Purge**: Removes unused CSS in production builds. +- **Caching**: React Query caches API responses. Consider adding Redis or edge caching for GitHub data in the future. ## 8. Testing and Quality Assurance -### 8.1 Unit Testing -- Jest + React Testing Library for components and hooks. -- We mock Supabase client and Clerk session in tests. +### Testing Strategies +- **Unit Tests**: Jest or Vitest + React Testing Library for components, hooks, and utilities. +- **Integration Tests**: API route tests to simulate GitHub and Supabase interactions (using mocks). +- **End-to-End (E2E) Tests**: Playwright or Cypress to cover core user flows (search, login, favorite). -### 8.2 Integration Testing -- React Testing Library to simulate user flows (sign-in, chat messages). -- Zod schemas are tested to ensure proper validation. - -### 8.3 End-to-End Testing -- Playwright or Cypress for full scenarios: sign-in, theme toggle, AI chat cycle. - -### 8.4 Linting & Formatting -- ESLint (with TypeScript rules) enforces code style and catches errors early. -- Prettier handles consistent formatting. -- Husky + lint-staged run checks on pre-commit. +### Tools and Configuration +- **ESLint** with a shared config (`eslint.config.mjs`) for linting rules. +- **Prettier** (`.prettierrc`) for consistent formatting. +- **TypeScript** (`tsconfig.json`) to catch type errors early. +- **Git Hooks** (via Husky or simple npm scripts) to run linters and tests before commits. ## 9. Conclusion and Overall Frontend Summary -This frontend setup combines Next.js, TypeScript, Tailwind CSS v4, shadcn/ui, Clerk, Supabase, and the Vercel AI SDK into a cohesive developer experience. It emphasizes: -- **Scalability** through modular, file-based structure. -- **Maintainability** with clear patterns, typed components, and headless UI. -- **Performance** via SSR, code splitting, and optimized assets. -- **Accessibility and Usability** with consistent design tokens and ARIA-compliant components. -By following these guidelines, teams can confidently extend the starter kit, add new features, and maintain a high-quality, performant, and user-friendly application. \ No newline at end of file +The **git-search** frontend is built with a modern, scalable stack centered on Next.js and TypeScript. We prioritize: +- **Performance**: Server components, SSR/SSG, code splitting. +- **Maintainability**: Clear folder structure, TypeScript, utility-first styling. +- **Accessibility**: Semantic HTML, ARIA attributes, accessible UI components. +- **User Experience**: Responsive design, theming, fast feedback. + +By following these guidelines—consistent design principles, component-based architecture, robust state management, and thorough testing—we ensure the frontend remains reliable, easy to extend, and aligned with user needs as the application grows. diff --git a/documentation/project_requirements_document.md b/documentation/project_requirements_document.md index ea4f740..25a2c0b 100644 --- a/documentation/project_requirements_document.md +++ b/documentation/project_requirements_document.md @@ -2,170 +2,82 @@ ## 1. Project Overview -The **CodeGuide Starter Kit Lite v2** is a ready-to-go Next.js starter template aimed at giving developers a kick-start when building modern web applications. It combines authentication, database, AI, UI components, and theming into one opinionated, well-structured codebase. Instead of wiring up Clerk, Supabase, Tailwind, shadcn/ui, and Vercel AI SDK from scratch, you clone this repo, set your environment variables, and you’re up and running. +**git-search** is a full-stack web application built with Next.js that lets developers and curious users search, explore, and analyze GitHub repositories in a single, user-friendly interface. Beyond simple keyword lookups, it offers in-depth repository metrics (commit history, file structure, contributor stats) and an AI-powered chat assistant that can explain code patterns, suggest improvements, and answer natural-language questions about any repo. Users can sign up to personalize their experience, save favorite repositories, and monitor their activity on a custom dashboard. -We’re building this starter kit to eliminate repetitive setup tasks and enforce best practices out of the box: secure user sign-in/sign-up, row-level security, real-time AI chat, dark-mode toggle, and a cohesive UI. **Success** looks like: -1. New users can spin up a full-stack app in under 10 minutes. -2. All core integrations work together smoothly. -3. The codebase stays clean, documented, and easy to extend. - ---- +The project exists to bridge the gap between raw GitHub data and meaningful insights. Instead of jumping between pages on GitHub and separate analytics tools, users can stay in one place to discover projects, dive deep into their health and trends, and get AI-driven explanations. Key success criteria include fast search response times, accurate repository analysis, reliable AI chat interactions, secure and seamless authentication, and an intuitive UI with both light and dark themes. ## 2. In-Scope vs. Out-of-Scope -### In-Scope (v1.0) -- User authentication with Clerk (sign-up, sign-in, middleware-protected routes). -- Database integration via Supabase (CRUD + Row Level Security). -- AI chat interface using Vercel AI SDK (OpenAI & Anthropic Claude), with real-time streaming. -- UI components from shadcn/ui (New York style) and theme support (light/dark). -- TailwindCSS v4 for styling, CSS custom properties for theming. -- Basic environment variable validation and `.env.example`. -- Clear README & setup guides (Clerk + Supabase + AI). - -### Out-of-Scope (for later phases) -- Payment processing (Stripe, PayPal). -- Mobile apps or React Native support. -- Complex data visualization beyond simple charts. -- Internationalization (i18n). -- Multi-tenant administration panel. -- Automated end-to-end testing suites (Cypress, Playwright). - ---- +**In-Scope (Version 1):** +- GitHub repository search by keyword, topic, or criteria. +- Detailed repository analysis (commit history, file tree, contributor stats, code metrics). +- AI-powered chat interface for natural-language insights (using OpenAI and Anthropic Claude via Vercel AI SDK). +- User authentication (sign-up/sign-in) and session management via Clerk. +- Favorites management: add/remove bookmarks stored in Supabase with Row-Level Security. +- Personalized dashboard showing search history, favorites count, recent AI chats, and basic usage stats. +- Light and dark theme toggling using next-themes. +- Serverless API routes for search, analysis, AI chat, favorites, and dashboard stats. + +**Out-of-Scope (Phase 1):** +- Direct pull request creation or issue management on GitHub. +- In-browser code editing or live previews of repository code. +- Enterprise or on-premises deployment support. +- Mobile-specific native apps (iOS/Android) or PWA offline support. +- Advanced analytics (e.g., graph visualizations, time-series comparisons) beyond basic stats. +- Third-party integrations beyond GitHub and AI models (e.g., Jira, Slack). ## 3. User Flow -When a user lands on the homepage, they see a brief introduction, a sign-in/sign-up prompt, and a link to the AI chat demo. Unauthenticated visitors can browse public pages and see the theme toggle, but attempts to access the chat or profile pages redirect them to Clerk’s hosted sign-in page. Once signed in, the user is redirected back to the dashboard, now fully unlocked. +A new visitor lands on the homepage, which prominently features a search bar. They type keywords and hit “Search.” Behind the scenes, the frontend calls the `/api/github/search` endpoint, which uses Octokit to fetch matching repositories. Results appear in a paginated list with repo name, description, star count, and a “View Details” button. The user clicks a repo, and the app navigates to `/repository/[slug]`, where detailed stats (commit history, file structure, contributor breakdown) are displayed server-side for performance. -On the dashboard, users see the real-time AI chat widget, powered by Vercel AI SDK. They type messages and watch AI responses stream in. A left-corner user button opens a menu to view profile info or sign out. The theme toggle switches between light and dark instantly, thanks to `next-themes`. Behind the scenes, every chat, user profile update, or demo data CRUD operation is stored in Supabase with proper Row Level Security. - ---- +If the visitor wants to save a repo, they click “Sign Up,” complete the Clerk-powered authentication flow, and return to the repo page. Logged-in users can favorite repositories, which triggers a POST to `/api/github/favorites`. Their favorites list is visible under `/favorites`, and their dashboard at `/dashboard` shows saved repos, search usage patterns, and recent AI chats. On any repo page, users can open the chat widget, type questions (“How many contributors were active last month?”), and receive AI-generated insights, powered by the Vercel AI SDK. ## 4. Core Features -- **Authentication** - - Clerk integration for sign-up, sign-in, sign-out. - - Middleware protects `/dashboard`, `/profile`. - - Clerk UI components: `SignInButton`, `SignedIn`, `SignedOut`, `UserButton`. - -- **Database Integration** - - Supabase client for server & client data fetching. - - Full CRUD support on demo tables. - - Row Level Security policies based on Clerk user ID. - -- **AI Integration** - - Vercel AI SDK configured for OpenAI & Anthropic Claude. - - Streaming chat API at `/api/chat/route.ts`. - - Clerk-protected AI endpoints. - -- **UI Components & Layout** - - Headless, accessible components from shadcn/ui. - - Prebuilt elements: buttons, cards, dialogs, inputs, navigation. - -- **Styling & Theming** - - TailwindCSS v4 with utility classes. - - CSS custom properties for colors & spacing. - - Dark mode via `next-themes`. - -- **Environment Setup** - - `.env.example` with variables for Clerk, Supabase, OpenAI, Claude. - - Runtime checks to fail fast if variables are missing. - ---- +- **Authentication**: Clerk handles user sign-up, sign-in, and session management. Protects `/dashboard` and `/favorites` with middleware. +- **Search Module**: Frontend component and `/api/github/search` route that queries GitHub via Octokit and returns paginated results. +- **Repository Analysis**: Detailed view powered by `/api/github/repository/[id]` and `/api/github/analyze` routes fetching commit history, file tree, and statistics. +- **AI Chat Interface**: Reusable React component that sends user prompts to Vercel AI SDK, selectable between OpenAI and Anthropic Claude models, and displays responses conversationally. +- **Favorites Management**: Protected API routes to add/remove favorites in Supabase, leveraging RLS to isolate each user’s data. +- **Dashboard & Analytics**: Aggregates user activity via `/api/dashboard/stats` (search count, favorites count, recent chats) and displays charts or summary cards. +- **Theming**: Global light/dark mode toggle using next-themes, persisted in `localStorage`. +- **API Layer**: Next.js serverless routes under `src/app/api` for all back-end interactions (GitHub, Supabase, AI). ## 5. Tech Stack & Tools -- **Frontend Framework:** Next.js 15 (App Router) -- **Language:** TypeScript (strict mode) -- **Styling:** TailwindCSS v4 + CSS variables -- **UI Library:** shadcn/ui (New York style) -- **Authentication:** Clerk SDK + Middleware -- **Database:** Supabase (PostgreSQL + RLS) -- **AI Integration:** Vercel AI SDK - - OpenAI models - - Anthropic Claude models -- **State Management:** React Context (minimal) -- **Theme Management:** next-themes -- **Dev Environment:** - - Docker + `.devcontainer` for VS Code - - ESLint, Prettier config included -- **Version Control:** Git (GitHub recommended) -- **Additional Libraries:** clsx, cmdk, date-fns, embla-carousel-react, input-otp, lucide-react, react-hook-form, react-resizable-panels, recharts, sonner, svix, tailwind-merge, vaul, zod - ---- +- Frontend: Next.js 15 (App Router), React 18 Server and Client Components, TypeScript. +- Styling & UI: Tailwind CSS v4, shadcn/ui (Radix UI + Tailwind), next-themes. +- Authentication: Clerk.js. +- Database: Supabase (PostgreSQL) with Row-Level Security for favorites. +- AI Integration: Vercel AI SDK connecting to OpenAI GPT-4 and Anthropic Claude. +- GitHub API: Octokit REST client. +- Deployment: Vercel serverless platform. +- Development Environment: Docker devcontainer, VS Code with ESLint & Prettier, optional Cursor or Windsurf plugins for AI-powered coding assistance. ## 6. Non-Functional Requirements -- **Performance**: - - Initial page load < 1.5s on 3G. - - AI streaming response latency < 300ms per token. - -- **Security**: - - All protected endpoints require Clerk JWT. - - Supabase RLS policies to enforce per-user data access. - - Environment secrets never exposed to client. - -- **Maintainability**: - - Well-structured file layout matching Next.js conventions. - - Inline JSDoc/TSDoc comments. - - Clear separation of concerns (UI vs. data vs. utils). - -- **Usability**: - - Zero-configuration setup after `.env` is populated. - - Accessible UI components (ARIA, keyboard nav). - -- **Scalability**: - - Modular feature folders for easy extension. - - Stateless API routes for horizontal scaling. - -- **Documentation**: - - Step-by-step README + supplementary markdown (CLAUDE.md, SUPABASE_CLERK_SETUP.md). - -- **Testing**: - - Unit tests for critical utilities (e.g., env checks, Supabase client). - - Placeholder integration tests recommended. - ---- +- **Performance:** Page load under 2 seconds on a 3G connection. Search results returned in under 1 second. AI chat responses in under 1.5 seconds. +- **Scalability:** Support up to 5,000 daily users without manual scaling; leverage Vercel auto-scaling and Supabase managed infrastructure. +- **Security:** HTTPS everywhere; Clerk session tokens with HTTP-only cookies; Supabase RLS enforced; OWASP Top 10 mitigations in API routes. +- **Compliance:** GDPR-compatible data storage; clear privacy policy; opt-out for analytics. +- **Usability & Accessibility:** WCAG 2.1 AA standards; keyboard navigable; ARIA attributes on custom components; color contrast checks. ## 7. Constraints & Assumptions -- **Third-Party Services** - - Clerk must support the chosen domain for OAuth redirect. - - Supabase project must be provisioned with correct RLS settings. - - OpenAI & Anthropic Claude API keys must be valid and unthrottled. - -- **Developer Environment** - - Node.js v18+ installed. - - Docker available if using `.devcontainer`. - -- **Assumptions** - - Users have basic Git and VS Code experience. - - No custom branding is required in v1.0. - - AI usage quotas are sufficient for demo purposes. - ---- +- **GitHub API Rate Limits:** 5,000 requests/hour per OAuth app. Assume caching or rate-limiting logic is needed. +- **AI Model Availability:** Dependent on OpenAI/Anthropic quotas and response times. Assume keys and quotas are provisioned. +- **Environment Variables:** Validated at startup via `lib/env-check.ts`. Must include GitHub token, Clerk credentials, Supabase URL/key, AI API keys. +- **Next.js App Router:** Requires Node.js 18+ and Vercel platform features. +- **User Base:** Primarily English-speaking developers/researchers. ## 8. Known Issues & Potential Pitfalls -- **API Rate Limits** - - OpenAI/Claude quotas may throttle heavy usage. - - Mitigation: implement exponential back-off and caching. - -- **RLS Misconfiguration** - - Missing or overly permissive policies can leak data. - - Mitigation: include sample SQL for strict per-user RLS rules. - -- **Environment Variable Typos** - - Typos in `.env` keys lead to confusing runtime errors. - - Mitigation: runtime guard functions that validate and log missing vars. - -- **Version Mismatch** - - Next.js, Tailwind, and shadcn/ui updates might break compatibility. - - Mitigation: lock dependencies in `package.json` and note upgrade path. - -- **CORS & Cookies** - - Clerk and Supabase require correct cookie settings on production domains. - - Mitigation: document cookie domains in setup guide. +- **API Rate Limiting:** Exceeding GitHub limits may lead to 403 errors. Mitigation: implement server-side caching (in-memory or Redis) for repeated queries. +- **AI Model Cost & Latency:** Heavy chat usage can incur high costs and slower responses. Mitigation: add usage quotas per user and fallback static suggestions when AI delays. +- **Data Consistency:** Concurrent favorites operations could conflict. Mitigation: use Supabase transactions and optimistic UI updates. +- **SSR vs. CSR Data Fetching:** Over-fetching in Server Components may slow page builds. Mitigation: split heavy data calls to client components or use incremental static regeneration (ISR). +- **Environment Drift:** Developers may miss environment variable updates. Mitigation: include comprehensive `.env.example` and pre-launch environment checks. --- -*End of PRD* \ No newline at end of file +This PRD provides a clear, unambiguous reference for the AI model and subsequent technical documents, ensuring every feature, flow, and constraint is fully specified for implementation. \ No newline at end of file diff --git a/documentation/security_guideline_document.md b/documentation/security_guideline_document.md index c3059e0..a91370d 100644 --- a/documentation/security_guideline_document.md +++ b/documentation/security_guideline_document.md @@ -1,108 +1,117 @@ -# Security Guidelines for CodeGuide Starter Kit Lite v2 - -## 1. Introduction -This document defines security requirements and best practices for the CodeGuide Starter Kit Lite v2, a Next.js 15 App Router template integrating Clerk, Supabase, Vercel AI SDK, TailwindCSS, shadcn/ui, and other third-party libraries. It guides developers to build a secure, resilient, and maintainable starter kit by design. - -## 2. Core Security Principles -- **Security by Design:** Embed security from initial design through deployment. -- **Least Privilege:** Grant only necessary permissions to services, users, and modules. -- **Defense in Depth:** Layer controls so no single failure compromises the system. -- **Fail Securely:** On errors or exceptions, avoid exposing sensitive data and maintain a secure state. -- **Keep Security Simple:** Favor clear, maintainable controls over overly complex mechanisms. -- **Secure Defaults:** Default configurations must favor security (e.g., HTTPS only, strict Content Security Policy). - -## 3. Authentication & Access Control -1. **Clerk Integration:** - - Enforce strong password policies via Clerk (minimum length, complexity, history). - - Enable Multi-Factor Authentication (MFA) for sensitive accounts or admin roles. - - Use Clerk middleware (`middleware.ts`) to protect `/dashboard`, `/profile`, `/api/*`, and any RLS-protected routes. -2. **Session Management:** - - Ensure session tokens are unpredictable and stored in Secure, HttpOnly, SameSite=Strict cookies. - - Implement idle and absolute timeouts. Invalidate sessions on logout. -3. **Role-Based Access Control (RBAC):** - - Define roles (e.g., `user`, `admin`) and enforce server-side authorization checks in API routes and server components. - - Avoid client-side role checks as the sole authorization mechanism. - -## 4. Input Handling & Output Encoding -1. **Server-Side Validation:** - - Validate every API payload (chat messages, user profiles, CRUD operations) using schemas (e.g., Zod). - - Reject or sanitize unexpected fields. -2. **Prevent Injection:** - - Use Supabase client with prepared statements under the hood (no raw SQL queries). - - Never interpolate untrusted data into SQL/JS command strings. -3. **Cross-Site Scripting (XSS):** - - Escape or sanitize all user-supplied content rendered in React (e.g., use `react-sanitize` or whitelist HTML). - - Implement a strict Content Security Policy (CSP) to restrict executable scripts. -4. **Redirect Validation:** - - If any login redirect routes accept a `redirectTo` parameter, validate it against an allow-list of internal paths. - -## 5. Data Protection & Privacy -1. **Encryption in Transit:** - - Enforce TLS 1.2+ on Vercel (HTTPS). Configure `next.config.js` to redirect all HTTP traffic to HTTPS. -2. **Encryption at Rest:** - - Rely on Supabase’s built-in disk encryption. -3. **Secrets Management:** - - Store all API keys and credentials (Clerk, Supabase, OpenAI, Anthropic) in environment variables or a secret manager (e.g., Vercel Environment Variables). - - Do not commit `.env.*` files or secrets to version control. -4. **PII Handling:** - - Only capture necessary user data. Mask or redact sensitive fields in logs. - - Comply with GDPR/CCPA around user data deletion and export upon request. - -## 6. API & Service Security -1. **Enforce HTTPS:** - - All API endpoints (`/api/chat`, Supabase endpoints) must be accessed only over TLS. -2. **Rate Limiting & Throttling:** - - Implement edge rate limiting on chat API (e.g., Vercel Edge Middleware or third-party package) to mitigate brute-force or DoS attempts. -3. **CORS Configuration:** - - Restrict cross-origin requests in `next.config.js` or API route middleware to only your deployed front-end origins. -4. **Minimal Data Exposure:** - - API responses should include only necessary fields. Avoid returning internal IDs, secrets, or stack traces. - -## 7. Web Application Security Hygiene -1. **CSRF Protection:** - - For any state-changing POST/PUT/DELETE endpoints, implement anti-CSRF tokens (Next.js built-in or `csurf`). -2. **Security Headers:** - - Configure in `next.config.js` or custom server headers: - - `Content-Security-Policy` (restrict scripts, styles, frames). - - `Strict-Transport-Security: max-age=63072000; includeSubDomains; preload`. - - `X-Content-Type-Options: nosniff`. - - `X-Frame-Options: DENY`. - - `Referrer-Policy: strict-origin-when-cross-origin`. -3. **Secure Cookies:** - - Set `Secure`, `HttpOnly`, and `SameSite=Strict` for session cookies. -4. **Subresource Integrity (SRI):** - - If loading any third-party scripts or styles via CDN, use integrity hashes. - -## 8. Infrastructure & Configuration Management -1. **Production vs. Development:** - - Disable Next.js’s React developer tools and verbose logging in production. - - Ensure `NODE_ENV=production` on deployment. -2. **Server Hardening:** - - On any custom servers, disable unused ports and services, enforce OS-level permissions. -3. **Environment Variable Checks:** - - Implement runtime checks (in `lib/env.ts`) to fail build/start if required vars are missing. -4. **TLS Configuration:** - - Use Vercel’s managed certificates or enforce Let’s Encrypt with strong cipher suites. - -## 9. Dependency Management -1. **Secure Dependencies:** - - Vet all npm packages (shadcn/ui, clsx, date-fns, etc.) for active maintenance and known vulnerabilities. -2. **Lockfiles & SCA Tools:** - - Commit `package-lock.json` or `yarn.lock`. - - Integrate automated vulnerability scanning (e.g., GitHub Dependabot, Snyk). -3. **Minimize Footprint:** - - Remove unused dependencies; audit transitive dependencies regularly. - -## 10. Monitoring & Incident Response -- **Logging & Alerts:** - - Centralize logs (Vercel logs, Supabase logs). Mask PII. - - Configure alerts for unusual authentication failures or rate-limit breaches. -- **Error Handling:** - - Catch and handle exceptions in API routes; return generic error messages to clients. - - Log detailed errors internally (without sensitive context). -- **Regular Reviews:** - - Conduct periodic security audits and dependency vulnerability checks. - - Update security policies based on new threats and project scope changes. +# Git-Search Security Guidelines + +This document provides actionable, project-specific security guidance for the **git-search** repository, following “secure by design” principles. It covers authentication, data protection, API hardening, deployment, and ongoing practices to ensure robust security throughout the application lifecycle. --- -Adherence to these guidelines will ensure that the CodeGuide Starter Kit Lite v2 is secure by default, simplifying the path for developers to build robust applications on top of it. Regularly review and update this document to incorporate emerging best practices and address newly discovered vulnerabilities. \ No newline at end of file + +## 1. Security by Design & Governance + +- Embed security reviews in every sprint: include threat modeling when adding new features (e.g., AI chat, favorites). +- Define security owners for authentication, data handling, and deployment pipelines. +- Enforce least privilege at every layer: code, database, cloud functions. +- Automate checks using CI/CD: linting, SCA (Software Composition Analysis), static analysis (e.g., ESLint with security rules, Snyk). + +## 2. Authentication & Access Control + +1. **Clerk Configuration** + - Enforce strong password complexity and rotation policies. + - Enable multi-factor authentication (MFA) for all user accounts. + - Validate JWTs server-side: check `alg`, `iss`, `aud`, and expiration (`exp`). + +2. **Session & Cookie Security** + - Use `Secure`, `HttpOnly`, and `SameSite=Strict` on session cookies. + - Implement idle and absolute session timeouts; provide explicit logout endpoint. + - Protect API routes against session fixation by regenerating session IDs on login. + +3. **Role-Based Access Control (RBAC)** + - Define roles (e.g., `guest`, `user`, `admin`) and map permissions explicitly in middleware (`src/middleware.ts`). + - Enforce server-side checks on all protected routes: `/dashboard`, `/favorites`, `/api/github/favorites`. + - Use Supabase Row-Level Security (RLS) to isolate user data; review policies regularly. + +## 3. Input Validation & Output Encoding + +- Use a runtime schema library (e.g., Zod) to validate all API inputs: + * Query parameters (`/api/github/search?query=`) + * Dynamic path segments (`/[owner]/[repo]`) + * Request bodies for chat, favorites, and analysis endpoints. +- Sanitize outputs rendered in React components; avoid `dangerouslySetInnerHTML`. When necessary, whitelist tags and attributes. +- Prevent injection in Supabase queries by using the official client library and parameterized calls—never concatenate SQL strings. +- Validate and whitelist redirect URLs to avoid open-redirect attacks. + +## 4. Data Protection & Privacy + +- Enforce TLS 1.2+ on all Next.js serverless functions and web traffic. Do not allow HTTP. +- **Environment secrets**: + * Store Clerk API keys, Supabase credentials, and GitHub tokens in Vercel Environment Variables or a secrets manager (e.g., AWS Secrets Manager, Vault). + * Use `lib/env-check.ts` to fail startup if required variables are missing. +- Avoid logging sensitive PII or raw tokens. Mask or redact values in logs. +- For personally identifiable information (e.g., user email), comply with GDPR/CCPA: + * Provide deletion endpoints. + * Log consent. + +## 5. API & Service Security + +1. **Rate Limiting & Throttling** + - Implement per-IP and per-user rate limits on critical endpoints (`/api/github/*`, `/api/chat`). + - Use an in-memory or Redis cache layer for ephemeral rate counters. + +2. **CORS Configuration** + - Restrict `Access-Control-Allow-Origin` to your production and staging domains only. + +3. **Least Privilege for API Keys** + - Create a GitHub App or fine-scoped personal access token limited to read-only repository search and metadata. + - Scope Supabase service roles to only the required tables and operations. + +4. **API Versioning** + - Prefix internal API routes with version numbers (e.g., `/api/v1/github/search`) to manage future changes securely. + +## 6. Web Application Security Hygiene + +- **Content Security Policy (CSP):** + * Default to `self` for scripts, styles, and connect endpoints. + * Allow only the AI service domains (OpenAI, Anthropic) and GitHub API in `connect-src`. +- **Security Headers:** + * `Strict-Transport-Security: max-age=63072000; includeSubDomains; preload` + * `X-Frame-Options: DENY` + * `X-Content-Type-Options: nosniff` + * `Referrer-Policy: no-referrer-when-downgrade` +- **CSRF Protection:** + * Use anti-CSRF tokens (synchronizer token pattern) on state-changing forms and fetch calls. +- **Subresource Integrity (SRI):** + * When loading third-party scripts (e.g., analytics), include integrity hashes and `crossorigin` attributes. + +## 7. Infrastructure & Configuration Management + +- **Vercel & Docker**: + * Disable Next.js debugger and verbose logs in production builds (`NODE_ENV=production`). + * Limit serverless function timeouts to prevent DoS amplification. +- **Server Hardening**: + * Disable unnecessary ports and services on any custom servers. + * Use up-to-date TLS cipher suites (ECDHE, AES-GCM) and disable TLS 1.0/1.1. +- **File Permissions**: + * Ensure uploaded files (if any) are stored outside the webroot with restricted filesystem permissions. + +## 8. Dependency Management + +- Maintain `package-lock.json` to freeze known-good versions. +- Regularly run automated vulnerability scans (e.g., `npm audit`, Snyk) and update dependencies. +- Vet all major framework upgrades (Next.js, Tailwind, Clerk, Supabase, Octokit) for breaking changes and security fixes. +- Remove unused packages to minimize attack surface. + +## 9. DevOps & CI/CD Security + +- Enforce branch protection and require PR reviews before merging. +- Integrate static analysis tools: + * ESLint with security plugins (e.g., eslint-plugin-security). + * Secrets scanning in CI (e.g., GitHub Secret Scanning). +- Automate deployments only from the `main` branch; require successful tests and security checks. + +## 10. Monitoring, Logging & Incident Response + +- Integrate an error-tracking service (Sentry, LogRocket) for both serverless functions and client-side exceptions. +- Log all authentication events (login, logout, token refresh), but avoid storing raw tokens. +- Define an incident response plan: triage, notification, and post-mortem for security events. + +--- + +By following these project-tailored guidelines, the **git-search** application will maintain strong defenses against common threats, safeguard user data, and uphold best practices for secure web development. Regularly revisit this document as the codebase and threat landscape evolve. diff --git a/documentation/setup.md b/documentation/setup.md index 9913980..3c3cf78 100644 --- a/documentation/setup.md +++ b/documentation/setup.md @@ -18,26 +18,6 @@ This project includes a tasks.json file that outlines the implementation tasks f ## MCP Integrations (Step 5) -To enhance your development experience with additional capabilities, add these MCPs: +No specific MCP servers are configured for this project. You can add MCP servers later to enhance your development experience. -### BrowserMCP Integration -```bash -claude mcp add browsermcp -- npx -y @browsermcp/mcp@latest -``` - -For detailed instructions, visit: https://docs.browsermcp.io - -### Context7 Integration -```bash -claude mcp add --transport http context7 https://mcp.context7.com/mcp -``` - -For detailed instructions, visit: https://context7.com - - -## Additional Setup Notes - -- Make sure Claude Desktop is installed and properly configured -- Restart Claude Desktop after adding new MCP servers -- Test each MCP integration to ensure it's working correctly -- Refer to the individual documentation links for advanced configuration options +For general MCP information, visit the Claude documentation. diff --git a/documentation/tasks.json b/documentation/tasks.json new file mode 100644 index 0000000..7a947f3 --- /dev/null +++ b/documentation/tasks.json @@ -0,0 +1,65 @@ +{ + "tasks": [ + { + "id": 1, + "title": "Initialize Next.js Project with Core Tooling", + "status": "pending", + "details": "- Scaffold a new Next.js 15 project using the App Router and TypeScript.\n- Integrate Tailwind CSS v4 and configure with shadcn/ui (Radix UI + Tailwind).\n- Add next-themes for light/dark mode support.\n- Set up ESLint, Prettier, and VS Code settings for code quality.\n- Create a Docker devcontainer for consistent development environments.\n- Add a comprehensive `.env.example` file and implement `lib/env-check.ts` for environment variable validation at startup.\n- Ensure the project is ready for further feature development and adheres to the specified tech stack.", + "priority": "high", + "description": "Set up the foundational Next.js 15 project structure with TypeScript, Tailwind CSS v4, shadcn/ui, next-themes, and essential development tooling.", + "dependencies": [], + "testStrategy": "- Run the development server and verify the default Next.js page loads.\n- Confirm Tailwind and shadcn/ui styles render correctly.\n- Switch between light and dark themes and verify persistence.\n- Lint and format code to ensure ESLint and Prettier are active.\n- Validate environment variable checks by running with missing/invalid variables." + }, + { + "id": 2, + "title": "Implement Dummy Landing Page UI", + "status": "pending", + "details": "- Build a landing page at `/` using Next.js App Router.\n- Use shadcn/ui components and Tailwind CSS for layout and styling.\n- Include a prominent search bar (non-functional for now), project branding, and a brief description.\n- Add light/dark theme toggle using next-themes.\n- Ensure WCAG 2.1 AA accessibility, keyboard navigation, and ARIA attributes.\n- Prepare for future integration of authentication and search features.", + "priority": "high", + "description": "Create a visually appealing, accessible dummy landing page as the initial homepage for git-search.", + "dependencies": [ + 1 + ], + "testStrategy": "- Load the landing page and verify layout, branding, and dummy search bar are present.\n- Test keyboard navigation and screen reader accessibility.\n- Toggle between light and dark modes and confirm UI updates.\n- Validate responsive design on multiple screen sizes." + }, + { + "id": 3, + "title": "Integrate Clerk Authentication (Sign Up/Sign In)", + "status": "pending", + "details": "- Install and configure Clerk.js with required environment variables.\n- Implement sign-up and sign-in UI flows using Clerk components.\n- Protect `/dashboard` and `/favorites` routes with Clerk middleware.\n- Ensure session management and secure HTTP-only cookies.\n- Prepare for future integration with Supabase and personalized features.", + "priority": "medium", + "description": "Set up Clerk.js for user authentication, enabling sign-up and sign-in flows, and protect relevant routes.", + "dependencies": [ + 1, + 2 + ], + "testStrategy": "- Register a new user and sign in/out, verifying session persistence.\n- Attempt to access protected routes without authentication and confirm redirection.\n- Check that session tokens are stored securely.\n- Validate error handling for failed authentication attempts." + }, + { + "id": 4, + "title": "Set Up Supabase Backend for Favorites", + "status": "pending", + "details": "- Create a Supabase project and configure PostgreSQL schema for favorites.\n- Enable Row-Level Security (RLS) to isolate user data.\n- Add Supabase client to the Next.js project and configure with environment variables.\n- Prepare API routes for adding/removing favorites (implementation in future tasks).\n- Document schema and RLS policies for future reference.", + "priority": "medium", + "description": "Configure Supabase PostgreSQL with Row-Level Security for storing user favorites, and connect it to the Next.js app.", + "dependencies": [ + 1, + 3 + ], + "testStrategy": "- Connect to Supabase from the Next.js app and verify connectivity.\n- Test RLS by attempting to access another user's favorites (should be denied).\n- Validate schema by inserting and querying dummy favorite records.\n- Ensure environment variables are loaded and validated at startup." + }, + { + "id": 5, + "title": "Prepare API Layer Structure and Environment Validation", + "status": "pending", + "details": "- Create `src/app/api` directory for all future serverless API routes (search, analysis, AI chat, favorites, dashboard stats).\n- Implement a shared environment validation utility (`lib/env-check.ts`) that runs at startup and on API route invocation.\n- Ensure all required environment variables (GitHub token, Clerk credentials, Supabase URL/key, AI API keys) are checked and errors are surfaced early.\n- Document the API route structure and validation process for the team.", + "priority": "medium", + "description": "Establish the folder structure and boilerplate for serverless API routes, and ensure robust environment variable validation.", + "dependencies": [ + 1 + ], + "testStrategy": "- Start the app with missing/invalid environment variables and confirm errors are thrown.\n- Access a dummy API route and verify environment validation runs.\n- Check that the API folder structure matches the PRD requirements.\n- Review documentation for clarity and completeness." + } + ], + "expanded_tasks": [] +} \ No newline at end of file diff --git a/src/app/page.tsx b/src/app/page.tsx index 1fd205d..90dedb3 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -1,7 +1,6 @@ "use client"; -// Authentication removed -import { useState } from "react"; +import { useState, useEffect } from "react"; import { Card, CardContent } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; @@ -12,10 +11,17 @@ import { FileText, Zap, Database, - Star, - GitFork, - Calendar, ExternalLink, + TrendingUp, + Users, + Clock, + Code2, + Sparkles, + ArrowRight, + CheckCircle, + BookOpen, + Brain, + Activity, } from "lucide-react"; import { ThemeToggle } from "@/components/theme-toggle"; import Link from "next/link"; @@ -26,6 +32,7 @@ import { useFeaturedRepositories } from "@/hooks/use-featured-repositories"; export default function Home() { const [searchQuery, setSearchQuery] = useState(''); + const [currentStat, setCurrentStat] = useState(0); const router = useRouter(); const { data: featuredRepositories, isLoading, error } = useFeaturedRepositories(4); @@ -36,6 +43,21 @@ export default function Home() { } }; + // Stats animation + const stats = [ + { label: "Repositories Analyzed", value: "10K+", icon: Database }, + { label: "Lines of Code Processed", value: "500M+", icon: Code2 }, + { label: "AI Insights Generated", value: "25K+", icon: Brain }, + { label: "Developers Served", value: "2K+", icon: Users }, + ]; + + useEffect(() => { + const interval = setInterval(() => { + setCurrentStat((prev) => (prev + 1) % stats.length); + }, 3000); + return () => clearInterval(interval); + }, [stats.length]); + const formatNumber = (num: number) => { if (num >= 1000000) { return (num / 1000000).toFixed(1) + 'M'; @@ -64,72 +86,224 @@ export default function Home() { return (
- {/* Hero Section */} -
-
-
+ {/* Navigation */} + -
- -

- Git Search -

-
-

- The ultimate GitHub repository directory with AI-focused statistics and comprehensive analysis -

- - {/* Search Bar */} -
-
-
- - setSearchQuery(e.target.value)} - className="pl-10 h-12 text-base" - /> + {/* Hero Section */} +
+
+ {/* Main Hero Content */} +
+
+
+
+ +
+

+ Git Search +

+
+

+ The ultimate GitHub repository directory with AI-powered insights, comprehensive analysis, and smart recommendations +

+ + {/* Value Proposition */} +
+
+ + AI-Powered Analysis +
+
+ + Real-time Metrics +
+
+ + Code Intelligence +
+
+ + Developer Insights +
-
- + {/* Enhanced Search Bar */} +
+
+
+
+
+ + setSearchQuery(e.target.value)} + className="pl-12 pr-4 h-14 text-base border-0 bg-transparent focus:ring-0 focus:outline-none" + /> +
+ +
+
+ + {/* Search Suggestions */} +
+ Popular searches: + {["React", "TypeScript", "Next.js", "Python ML", "Vue.js", "Node.js"].map((term) => ( + + ))} +
+
+ + {/* Animated Stats */} +
+ {stats.map((stat, index) => { + const Icon = stat.icon; + return ( + + +
{stat.value}
+
{stat.label}
+
+ ); + })} +
+
-
- {/* Featured Repositories - Moved to Top */} -
-
-

Featured Repositories

-

+

+ {/* How It Works Section */} +
+
+

How Git Search Works

+

+ Discover, analyze, and understand GitHub repositories like never before +

+
+ +
+ +
+
+
+ +
+

1. Search & Discover

+

+ Enter keywords, topics, or specific technologies to find relevant repositories from GitHub's vast ecosystem. +

+
+
+ + +
+
+
+ +
+

2. AI Analysis

+

+ Our AI engines analyze code structure, complexity, dependencies, and generate intelligent insights about each repository. +

+
+
+ + +
+
+
+ +
+

3. Get Insights

+

+ Access detailed metrics, documentation, token estimates, and make informed decisions about code adoption. +

+
+
+
+
+ + {/* Featured Repositories */} +
+
+
+ +

Featured Repositories

+ +
+

Popular repositories with comprehensive AI-focused analysis

-
+
{isLoading ? ( // Loading skeletons - Array.from({ length: 4 }).map((_, index) => ( - - -
- - + Array.from({ length: 3 }).map((_, index) => ( + + +
+
+
+ + +
+ +
- - - + + +
-
+
{Array.from({ length: 4 }).map((_, i) => ( - +
+ + + +
))}
@@ -138,24 +312,31 @@ export default function Home() { )) ) : error ? ( // Error state - - -

- Unable to load featured repositories. Please try again later. + + +

+ +
+

Unable to Load Repositories

+

+ We're having trouble fetching featured repositories. Please try again later.

+
) : featuredRepositories && featuredRepositories.length > 0 ? ( // Real data - featuredRepositories.map((repo) => ( - - -
-
-
+ featuredRepositories.slice(0, 3).map((repo) => ( + + +
+
+
{repo.name} @@ -163,83 +344,86 @@ export default function Home() { href={repo.repo_url} target="_blank" rel="noopener noreferrer" - className="text-gray-400 hover:text-gray-600" + className="text-gray-400 hover:text-gray-600 transition-colors" > - + -
- -
-
-
- - {formatDate(repo.updated_at)} -
+
+ + Trending
- - -
-
- -

- {repo.description || 'No description available'} -

+ +

+ {repo.description || 'No description available'} +

-
- {repo.author && ( - - {repo.author} - - )} - {repo.branch && ( - - {repo.branch} +
+ {repo.author && ( + + + {repo.author} + + )} + {repo.branch && ( + + + {repo.branch} + + )} + + + {formatDate(repo.updated_at)} - )} +
- {/* Statistics with Icons */} -
-
- -
-
- {formatNumber(repo.stats?.total_lines || 0)} -
-
Lines
-
+ + + +
+ + {/* Enhanced Statistics */} +
+
+
+
-
- -
-
- {formatNumber(repo.stats?.total_files_found || 0)} -
-
Files
-
+
+ {formatNumber(repo.stats?.total_lines || 0)}
-
- -
-
- {formatBytes(repo.stats?.estimated_size_bytes || 0)} -
-
Size
-
+
Lines of Code
+
+
+
+
-
- -
-
- {formatNumber(repo.stats?.estimated_tokens || 0)} -
-
Tokens
-
+
+ {formatNumber(repo.stats?.total_files_found || 0)} +
+
Files
+
+
+
+
+
+ {formatBytes(repo.stats?.estimated_size_bytes || 0)} +
+
Repository Size
+
+
+
+ +
+
+ {formatNumber(repo.stats?.estimated_tokens || 0)} +
+
AI Tokens
@@ -247,60 +431,215 @@ export default function Home() { )) ) : ( // No data state - - -

- No featured repositories available. Start by analyzing some repositories! + + +

+ +
+

No Featured Repositories

+

+ Start by analyzing some repositories to see them featured here!

+ + +
)}
-
+
-
-
+
- {/* Feature Cards */} -
-
-

Platform Features

-

Advanced insights and analysis tools for GitHub repositories

+ {/* Enhanced Features Section */} +
+
+

Powerful Features

+

+ Advanced insights and analysis tools that transform how you understand GitHub repositories +

-
- - -

Code Statistics

-

Lines of code, file counts, and complexity metrics

+ +
+ +
+ +
+

Code Statistics

+

+ Comprehensive metrics including lines of code, file counts, complexity analysis, and code quality indicators +

- - -

AI Token Estimates

-

Estimates for GPT-4, Claude, and Gemini models

+ +
+ +
+

AI Token Estimates

+

+ Accurate token estimates for GPT-4, Claude, Gemini, and other AI models to optimize your AI workflow costs +

- - -

Documentation

-

Auto-generated docs and architecture diagrams

+ +
+ +
+

Smart Documentation

+

+ AI-generated documentation, architecture diagrams, and comprehensive code explanations +

- - -

Tech Stack Analysis

-

Language breakdown and technology insights

+ +
+ +
+

Tech Stack Analysis

+

+ Detailed language breakdown, framework detection, dependency analysis, and technology recommendations +

-
+
+ + {/* Call to Action Section */} +
+ +
+ +
+

Ready to Explore?

+

+ Join thousands of developers who use Git Search to discover, analyze, and understand code repositories with AI-powered insights. +

+
+ + + + + + +
+
+
+
+
+ + {/* Social Proof / Stats Section */} +
+
+

Trusted by Developers Worldwide

+

+ Join our growing community of developers who rely on Git Search for code insights +

+
+ +
+ +
+ +
+

99.9%

+

Analysis Accuracy

+
+ + +
+ +
+

< 2s

+

Average Response Time

+
+ + +
+ +
+

24/7

+

Always Available

+
+
+
+ + {/* Footer */} +
); }