diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..783a84f --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,64 @@ +# Claude Code Task Management Guide + +## Documentation Available + +📚 **Project Documentation**: Check the documentation files in this directory for project-specific setup instructions and guides. +**Project Tasks**: Check the tasks directory in documentation/tasks for the list of tasks to be completed. Use the CLI commands below to interact with them. + +## MANDATORY Task Management Workflow + +🚨 **YOU MUST FOLLOW THIS EXACT WORKFLOW - NO EXCEPTIONS** 🚨 + +### **STEP 1: DISCOVER TASKS (MANDATORY)** +You MUST start by running this command to see all available tasks: +```bash +task-manager list-tasks +``` + +### **STEP 2: START EACH TASK (MANDATORY)** +Before working on any task, you MUST mark it as started: +```bash +task-manager start-task +``` + +### **STEP 3: COMPLETE OR CANCEL EACH TASK (MANDATORY)** +After finishing implementation, you MUST mark the task as completed, or cancel if you cannot complete it: +```bash +task-manager complete-task "Brief description of what was implemented" +# or +task-manager cancel-task "Reason for cancellation" +``` + +## Task Files Location + +📁 **Task Data**: Your tasks are organized in the `documentation/tasks/` directory: +- Task JSON files contain complete task information +- Use ONLY the `task-manager` commands listed above +- Follow the mandatory workflow sequence for each task + +## MANDATORY Task Workflow Sequence + +🔄 **For EACH individual task, you MUST follow this sequence:** + +1. 📋 **DISCOVER**: `task-manager list-tasks` (first time only) +2. 🚀 **START**: `task-manager start-task ` (mark as in progress) +3. 💻 **IMPLEMENT**: Do the actual coding/implementation work +4. ✅ **COMPLETE**: `task-manager complete-task "What was done"` (or cancel with `task-manager cancel-task "Reason"`) +5. 🔁 **REPEAT**: Go to next task (start from step 2) + +## Task Status Options + +- `pending` - Ready to work on +- `in_progress` - Currently being worked on +- `completed` - Successfully finished +- `blocked` - Cannot proceed (waiting for dependencies) +- `cancelled` - No longer needed + +## CRITICAL WORKFLOW RULES + +❌ **NEVER skip** the `task-manager start-task` command +❌ **NEVER skip** the `task-manager complete-task` command (use `task-manager cancel-task` if a task is not planned, not required, or you must stop it) +❌ **NEVER work on multiple tasks simultaneously** +✅ **ALWAYS complete one task fully before starting the next** +✅ **ALWAYS provide completion details in the complete command** +✅ **ALWAYS follow the exact 3-step sequence: list → start → complete (or cancel if not required)** \ No newline at end of file diff --git a/README.md b/README.md index d812370..9de3712 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# CodeGuide Starter Kit +# Codeguide Starter Fullstack A modern web application starter template built with Next.js 15, featuring authentication, database integration, and dark mode support. @@ -25,7 +25,7 @@ Before you begin, ensure you have the following: 1. **Clone the repository** ```bash git clone - cd codeguide-starter + cd codeguide-starter-fullstack ``` 2. **Install dependencies** @@ -116,7 +116,7 @@ NEXT_PUBLIC_BETTER_AUTH_URL=http://localhost:3000 ## Project Structure ``` -codeguide-starter/ +codeguide-starter-fullstack/ ├── app/ # Next.js app router pages │ ├── globals.css # Global styles with dark mode │ ├── layout.tsx # Root layout with providers @@ -230,7 +230,7 @@ npm run db:dev 1. **Clone and setup on your server:** ```bash git clone - cd codeguide-starter + cd codeguide-starter-fullstack cp .env.example .env ``` @@ -256,10 +256,10 @@ npm run db:dev 1. **Build and push image:** ```bash # Build the image - docker build -t your-registry/codeguide-starter:latest . + docker build -t your-registry/codeguide-starter-fullstack:latest . # Push to registry - docker push your-registry/codeguide-starter:latest + docker push your-registry/codeguide-starter-fullstack:latest ``` 2. **Deploy using your cloud provider's container service** @@ -326,4 +326,4 @@ This starter is optimized for AI coding agents: ## Contributing Contributions are welcome! Please feel free to submit a Pull Request. -# codeguide-starter +# codeguide-starter-fullstack diff --git a/app/layout.tsx b/app/layout.tsx index c783e79..af1e519 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -19,7 +19,7 @@ const parkinsans = Parkinsans({ }); export const metadata: Metadata = { - title: "CodeGuide Starter Kit", + title: "Codeguide Starter Fullstack", description: "A modern Next.js starter with TypeScript, TailwindCSS, shadcn/ui, Better Auth, and Drizzle ORM", }; diff --git a/app/page.tsx b/app/page.tsx index e7ebec9..d0de264 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -36,7 +36,7 @@ export default function Home() { className="rounded-xl sm:w-[60px] sm:h-[60px]" />

- CodeGuide Starter + Codeguide Starter Fullstack

diff --git a/docker-compose.yml b/docker-compose.yml index da0f731..eb61ccc 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -4,7 +4,7 @@ services: # PostgreSQL Database postgres: image: postgres:16-alpine - container_name: codeguide-postgres + container_name: codeguide-starter-fullstack-postgres restart: unless-stopped environment: POSTGRES_DB: ${POSTGRES_DB} @@ -16,14 +16,14 @@ services: - postgres_data:/var/lib/postgresql/data - ./docker/postgres/init.sql:/docker-entrypoint-initdb.d/init.sql networks: - - codeguide-network + - codeguide-starter-fullstack-network # Next.js Application app: build: context: . dockerfile: Dockerfile - container_name: codeguide-app + container_name: codeguide-starter-fullstack-app restart: unless-stopped environment: - NODE_ENV=production @@ -35,12 +35,12 @@ services: depends_on: - postgres networks: - - codeguide-network + - codeguide-starter-fullstack-network # Development database only postgres-dev: image: postgres:16-alpine - container_name: codeguide-postgres-dev + container_name: codeguide-starter-fullstack-postgres-dev restart: unless-stopped environment: POSTGRES_DB: ${POSTGRES_DB:-postgres} @@ -51,7 +51,7 @@ services: volumes: - postgres_dev_data:/var/lib/postgresql/data networks: - - codeguide-network + - codeguide-starter-fullstack-network profiles: - dev @@ -62,5 +62,5 @@ volumes: driver: local networks: - codeguide-network: + codeguide-starter-fullstack-network: driver: bridge \ No newline at end of file diff --git a/documentation/app_flow_document.md b/documentation/app_flow_document.md new file mode 100644 index 0000000..1916d04 --- /dev/null +++ b/documentation/app_flow_document.md @@ -0,0 +1,41 @@ +# App Flow Document + +## Onboarding and Sign-In/Sign-Up + +When a new visitor arrives at the application’s root URL, they land on a welcome page that offers clear buttons or links to either create an account or sign in. Clicking on the “Sign Up” link takes the visitor to a registration page where they enter their email address and choose a password. Once they submit the form, the application sends a POST request to the authentication API endpoint, which handles password hashing and user creation. If registration succeeds, the new user is automatically signed in and redirected to the dashboard. If there are validation errors, such as a password that is too short or an email already in use, the form reappears with inline messages explaining what must be corrected. + +For returning users, clicking the “Sign In” link from the welcome page or from a persistent header link opens the login form. They input their email and password, and upon submission the app sends a request to the same authentication API with login credentials. A successful login leads directly to the dashboard. If the credentials are invalid, the page reloads with a clear error message prompting the user to try again. + +Signing out is available from within the dashboard via a logout button in the main navigation or header. When clicked, the application clears the user’s session or token, and then navigates back to the welcome page. Currently, there is no built-in password recovery or reset flow in this version, so users who forget their password are prompted to contact support for assistance. + +## Main Dashboard or Home Page + +After authentication, the user lands on the dashboard, which serves as the main home page. The dashboard is wrapped in a layout that displays a header bar and a sidebar navigation tailored for logged-in users. The header bar typically shows the application’s logo on the left and a Logout link on the right. The sidebar sits on the left side of the screen and may contain links back to the dashboard’s main panel or to future features. + +The central area of the dashboard page displays data pulled from a static JSON file. This content might appear in cards or tables to give users a quick overview of information. All styling for this section comes from a dedicated theme stylesheet to keep the look consistent. Users can click items or links here, but those actions are placeholders for future dynamic data features. + +From this dashboard view, users may revisit the welcome page or any other main area by selecting navigation items in the sidebar or header. The layout ensures that the logout link remains accessible at all times, and that the user cannot leave the authenticated area without signing out manually or having their session expire. + +## Detailed Feature Flows and Page Transitions + +When a visitor lands on the root page, JavaScript on the client reads the route and displays either the welcome interface or automatically redirects them to the dashboard if a valid session exists. For new user registration, the user clicks the Sign Up link and is taken to the sign-up page. The sign-up form collects email and password fields, and on submission it triggers a client-side POST to the API route. Once the API responds with success, the client redirects the user to the dashboard page. + +Returning users choose the Sign In link and arrive at the sign-in page, which offers the same fields as the sign-up page but is wired to authenticate rather than create a new account. On form submit, the user sees a loading indication until the API confirms valid credentials. If successful, the client pushes the dashboard route and loads the dashboard layout and content. + +All authenticated pages reside under the `/dashboard` path. When the user attempts to navigate directly to `/dashboard` without a valid session, server-side redirection logic intercepts the request and sends the user back to the sign-in page. This ensures that protected content never shows to unauthorized visitors. + +Signing out happens entirely on the client side by calling an API or clearing a cookie, then navigating back to the welcome page. The client code listens for the logout action, invalidates the current session, and then reloads or reroutes the application state to the landing interface. + +## Settings and Account Management + +At present, users cannot change profile information, update their email, or configure notifications from within the interface. The only account management available is the ability to sign out from any dashboard view. In future iterations, a dedicated settings page could be added to let users update personal details or adjust preferences, but in this version, those capabilities are not provided. After signing out, users always return to the welcome page and must sign in again to regain access to the dashboard. + +## Error States and Alternate Paths + +If a user types an incorrect email or password on the sign-in page, the authentication API responds with an error status and a message. The form then displays an inline alert near the input fields explaining the issue, such as “Invalid email or password,” allowing the user to correct and resubmit. During sign up, validation errors like a missing field or weak password appear immediately under the relevant input. + +Network failures trigger a generic error notification at the top of the form, informing the user that the request could not be completed and advising them to check their connection. If the dashboard content fails to load due to a broken or missing static data file, a fallback message appears in the main panel stating that data could not be loaded and suggesting a page refresh. Trying to access a protected route without a session sends the user to the sign-in page automatically, making it clear that authentication is required. + +## Conclusion and Overall App Journey + +A typical user journey starts with visiting the application’s root URL, signing up with an email and password, then being welcomed in the dashboard area that displays sample data. Returning users go directly through the sign-in page to the dashboard. Throughout each step, clear messages guide the user in case of errors or invalid input. The layout remains consistent, with a header and navigation ensuring that users always know where they are and can sign out at any time. This flow lays the foundation for adding dynamic data, user profile management, and richer features in future releases. \ No newline at end of file diff --git a/documentation/app_flowchart.md b/documentation/app_flowchart.md new file mode 100644 index 0000000..8460af1 --- /dev/null +++ b/documentation/app_flowchart.md @@ -0,0 +1,14 @@ +flowchart TD + Start[Landing Page] + SignUpPage[Sign Up Page] + SignInPage[Sign In Page] + AuthAPI[Authentication API Endpoint] + DashboardPage[Dashboard Page] + Start -->|Select Sign Up| SignUpPage + Start -->|Select Sign In| SignInPage + SignUpPage -->|Submit Credentials| AuthAPI + SignInPage -->|Submit Credentials| AuthAPI + AuthAPI -->|Success| DashboardPage + AuthAPI -->|Error| SignUpPage + AuthAPI -->|Error| SignInPage + DashboardPage -->|Click Logout| Start \ No newline at end of file diff --git a/documentation/backend_structure_document.md b/documentation/backend_structure_document.md new file mode 100644 index 0000000..1ea043b --- /dev/null +++ b/documentation/backend_structure_document.md @@ -0,0 +1,179 @@ +# Backend Structure Document + +This document outlines the backend architecture, hosting, and infrastructure for the **codeguide-starter** project. It uses plain language so anyone can understand how the backend is set up and how it supports the application. + +## 1. Backend Architecture + +- **Framework and Design Pattern** + - We use **Next.js API Routes** to handle all server-side logic. These routes live alongside the frontend code in the same repository, making development and deployment simpler. + - The backend follows a **layered pattern**: + 1. **API Layer**: Receives requests (login, registration, data fetch). + 2. **Service Layer**: Contains the core business logic (user validation, password hashing). + 3. **Data Access Layer**: Talks to the database via a simple ORM (e.g., Prisma or TypeORM). + +- **Scalability** + - Stateless API routes can scale horizontally—new instances can spin up on demand. + - We can add caching or a message queue (e.g., Redis or RabbitMQ) without changing the core code. + +- **Maintainability** + - Code for each feature is grouped by route (authentication, dashboard). + - A service layer separates complex logic from request handling. + +- **Performance** + - Lightweight Node.js handlers keep response times low. + - Future use of database connection pooling and Redis for caching repeated queries. + +## 2. Database Management + +- **Database Choice** + - We recommend **PostgreSQL** for structured data and reliable transactions. + - In-memory caching can be added later with **Redis** for session tokens or frequently read data. + +- **Data Storage and Access** + - Use an ORM like **Prisma** or **TypeORM** to map JavaScript/TypeScript objects to database tables. + - Connection pooling ensures efficient use of database connections under load. + - Migrations track schema changes over time, keeping development, staging, and production in sync. + +- **Data Practices** + - Passwords are never stored in plain text—they are salted and hashed with **bcrypt** before saving. + - All outgoing data is typed and validated to prevent malformed records. + +## 3. Database Schema + +### Human-Readable Format + +- **Users** + - **id**: Unique identifier + - **email**: User’s email address (unique) + - **password_hash**: Securely hashed password + - **created_at**: Account creation timestamp + +- **Sessions** + - **id**: Unique session record + - **user_id**: Links to a user + - **token**: Random string for authentication + - **expires_at**: When the token stops working + - **created_at**: When the session was created + +- **DashboardItems** *(optional for dynamic data)* + - **id**: Unique record + - **title**: Item title + - **content**: Item details + - **created_at**: When the item was added + +### SQL Schema (PostgreSQL) +```sql +-- Users table +CREATE TABLE users ( + id SERIAL PRIMARY KEY, + email VARCHAR(255) UNIQUE NOT NULL, + password_hash VARCHAR(255) NOT NULL, + created_at TIMESTAMPTZ DEFAULT now() +); + +-- Sessions table +CREATE TABLE sessions ( + id SERIAL PRIMARY KEY, + user_id INT REFERENCES users(id) ON DELETE CASCADE, + token VARCHAR(255) UNIQUE NOT NULL, + expires_at TIMESTAMPTZ NOT NULL, + created_at TIMESTAMPTZ DEFAULT now() +); + +-- Dashboard items table +CREATE TABLE dashboard_items ( + id SERIAL PRIMARY KEY, + title TEXT NOT NULL, + content TEXT, + created_at TIMESTAMPTZ DEFAULT now() +); +``` + +## 4. API Design and Endpoints + +- **Approach**: We follow a **RESTful** style, grouping related endpoints under `/api` directories. + +- **Key Endpoints** + - `POST /api/auth/register` + • Accepts `{ email, password }` + • Creates a new user and issues a session token + - `POST /api/auth/login` + • Accepts `{ email, password }` + • Verifies credentials and returns a session token + - `POST /api/auth/logout` + • Invalidates the session token on the server + - `GET /api/dashboard/data` + • Requires a valid session + • Returns user-specific data or dashboard items + +- **Communication** + - Frontend sends JSON requests; backend replies with JSON and appropriate HTTP status codes. + - Protected routes check for a valid session token (in cookies or Authorization header). + +## 5. Hosting Solutions + +- **Cloud Provider**: + - **Vercel** (recommended) offers seamless Next.js deployments, auto-scaling, and built-in CDN. + - Alternatively, **Netlify** or any Node.js-capable host will work. + +- **Benefits** + - **Reliability**: Global servers and failover across regions. + - **Scalability**: Auto-scale serverless functions based on traffic. + - **Cost-Effectiveness**: Pay-per-use model means low cost for small projects. + +## 6. Infrastructure Components + +- **Load Balancer** + - Provided by the hosting platform—distributes API requests across function instances. + +- **CDN (Content Delivery Network)** + - Vercel’s global edge network caches static assets (CSS, JS, images) for faster page loads. + +- **Caching** + - **Redis** (optional) for session storage or caching dashboard queries to reduce database load. + +- **Object Storage** + - For file uploads or backups, integrate with AWS S3 or similar services. + +- **Message Queue** + - In future, use **RabbitMQ** or **Kafka** for background tasks (e.g., email notifications). + +## 7. Security Measures + +- **Authentication & Authorization** + - Passwords hashed with **bcrypt** and salted. + - Session tokens stored in secure, HttpOnly cookies or Authorization headers. + - Protected endpoints verify tokens before proceeding. + +- **Data Encryption** + - **HTTPS/TLS** encrypts data in transit. + - Database connections use SSL to encrypt data between the app and the database. + +- **Input Validation** + - Every incoming request is validated (e.g., valid email format, password length) to prevent SQL injection or other attacks. + +- **Web Security Best Practices** + - Enable **CORS** policies to limit allowed origins. + - Use **CSRF tokens** or same-site cookies to prevent cross-site requests. + - Set secure headers with **Helmet** or a similar middleware. + +## 8. Monitoring and Maintenance + +- **Performance Monitoring** + - Integrate **Sentry** or **LogRocket** for real-time crash reporting and performance tracing. + - Use Vercel’s built-in analytics to track request latencies and error rates. + +- **Logging** + - Structured logs (JSON) for all API requests and errors, shipped to a log management service like **Datadog** or **Logflare**. + +- **Health Checks** + - Define a `/health` endpoint that returns a 200 status if the service is up and the database is reachable. + +- **Maintenance Strategies** + - Automated migrations run on deploy to keep the database schema up to date. + - Scheduled dependency audits and security scans (e.g., `npm audit`). + - Regular backups of the database (daily or weekly depending on usage). + +## 9. Conclusion and Overall Backend Summary + +The backend for **codeguide-starter** is built on Next.js API Routes and Node.js, paired with PostgreSQL for data and optional Redis for caching. It follows a clear layered architecture that keeps code easy to maintain and extend. With RESTful endpoints for authentication and data, secure practices like password hashing and HTTPS, and hosting on Vercel for scalability and global performance, this setup meets the project’s goals for a fast, secure, and developer-friendly foundation. Future enhancements—such as background job queues, advanced monitoring, or richer data models—can be added without disrupting the core structure. \ No newline at end of file diff --git a/documentation/frontend_guidelines_document.md b/documentation/frontend_guidelines_document.md new file mode 100644 index 0000000..ffa3ea5 --- /dev/null +++ b/documentation/frontend_guidelines_document.md @@ -0,0 +1,180 @@ +# Frontend Guideline Document + +This document explains, in simple terms, how the frontend of the `codeguide-starter` project is structured, styled, and built. Anyone—technical or not—can read this and understand which tools are used, how components fit together, and what practices keep the app fast, reliable, and easy to maintain. + +--- + +## 1. Frontend Architecture + +**Core Frameworks and Libraries** +- **Next.js (App Router)**: A React-based framework that provides file-based routing, server-side rendering (SSR), static site generation (SSG), and built-in API endpoints all in one project. +- **React 18**: The library for building user interfaces using components and hooks. +- **TypeScript**: A superset of JavaScript that adds static types, helping catch errors early and making the code easier to understand and refactor. + +**How It’s Organized** +- The `app/` folder holds all pages and layouts. Each URL path corresponds to a folder: + - `/app/sign-in` and `/app/sign-up` for authentication pages. + - `/app/dashboard` for the protected user area. + - API routes live under `/app/api/auth/route.ts`. +- Each route folder contains: + - `page.tsx` (the UI for that page) + - `layout.tsx` (wrapping structure, like headers or sidebars) + - Styles (e.g., `theme.css` in the dashboard). + +**Why This Works** +- **Scalability**: Adding new pages or features means creating new folders with their own layouts and pages. You don’t have to touch a central router file. +- **Maintainability**: Code is separated by feature. Backend logic (API routes) lives alongside the frontend code for that feature, reducing context-switching. +- **Performance**: Next.js pre-renders pages where possible and splits code by route, so users download only what’s needed. + +--- + +## 2. Design Principles + +1. **Usability**: Forms give instant feedback. Buttons and links are clearly labeled. +2. **Accessibility**: Semantic HTML, proper color contrast, and focus outlines ensure people using screen readers or keyboards can navigate easily. +3. **Responsiveness**: Layouts adapt from mobile (320px) up to large desktop screens. CSS media queries ensure content resizes and stacks neatly. +4. **Consistency**: Shared global layout and styling mean pages look and feel like part of the same app. + +**How We Apply Them** +- Form fields use `aria-*` attributes and visible labels. +- Error messages appear inline under inputs. +- Navigation elements (header, sidebar) appear in every layout. +- Breakpoints at 480px, 768px, and 1024px guide responsive adjustments. + +--- + +## 3. Styling and Theming + +**Approach** +- **Global Styles (`globals.css`)**: Resets, base typography, and common utility classes. +- **Section Styles (`theme.css` in dashboard)**: Styles specific to the dashboard area (colors, layouts). +- We follow a **BEM-inspired naming** for classes when writing new CSS to avoid conflicts and keep selectors clear. + +**Visual Style**: Modern flat design with subtle shadows for depth. Clear spacing and large touch targets on mobile. + +**Color Palette** +- **Primary Blue**: #1E90FF (buttons, highlights) +- **Secondary Navy**: #2C3E50 (header, sidebar background) +- **Accent Cyan**: #00CEC9 (links, hover states) +- **Neutral Light**: #F8F9FA (page backgrounds) +- **Neutral Dark**: #2D3436 (text, icons) + +**Font** +- **Inter** (sans-serif): Clean, modern, highly legible on screens. Fallback to system fonts like `-apple-system, BlinkMacSystemFont, sans-serif`. + +**Theming** +- To keep a consistent look, all colors and font sizes are defined in CSS variables in `globals.css`: + ```css + :root { + --color-primary: #1E90FF; + --color-secondary: #2C3E50; + --color-accent: #00CEC9; + --color-bg: #F8F9FA; + --color-text: #2D3436; + --font-family: 'Inter', sans-serif; + } + ``` +- Components consume these variables for backgrounds, borders, and text. + +--- + +## 4. Component Structure + +**File Layout** +- `/app` (top-level folder) + - `layout.tsx`: Global wrapper (nav, footer). + - `page.tsx`: Landing or redirect logic. + - `/sign-in`, `/sign-up`, `/dashboard`, `/api/auth` + - Each has its own `layout.tsx` and `page.tsx`. +- **Common Components**: Put reusable UI pieces (buttons, inputs, cards) into a `/components` folder at the project root. + +**Reusability & Encapsulation** +- Components are self-contained: each has its own styles (class names scoped to BEM) and behavior. +- Shared logic (e.g., API calls) lives in `/lib` or `/hooks` so pages import only what they need. + +**Benefits** +- **Easier Maintenance**: Fix a bug in one button component, and it updates everywhere. +- **Better Team Collaboration**: Developers can own specific components or pages without stepping on each other’s code. + +--- + +## 5. State Management + +**Current Approach** +- **Local State**: React `useState` and `useEffect` for form values, loading flags, and error messages. +- **Server State**: Fetch data (e.g., dashboard JSON) directly in page components or using React Server Components. + +**Sharing State** +- **React Context**: A simple auth context (`AuthContext`) holds the user’s session info, login/logout methods, and makes it available to any component. + - Located in `/context/AuthContext.tsx`. + +**Future Growth** +- If complexity grows (deeply nested data, multiple user roles), consider: + - **Redux Toolkit** or **Zustand** for centralized state. + - Query libraries like **React Query** or **SWR** for caching and re-fetch logic. + +--- + +## 6. Routing and Navigation + +**Routing Library** +- Built into **Next.js App Router**. Each folder under `/app` becomes a route automatically. +- Layouts (`layout.tsx`) and pages (`page.tsx`) are colocated for that route. + +**Protected Pages** +- The dashboard’s `layout.tsx` checks for a valid session (via cookie or context). If missing, it issues a server-side redirect to `/sign-in`. + +**Navigation Structure** +- **Header**: Present in global layout with the app logo and conditional Sign In/Sign Out links. +- **Sidebar**: Included in `dashboard/layout.tsx` with links to dashboard sections (expandable in future). + +--- + +## 7. Performance Optimization + +1. **Code Splitting**: Next.js automatically breaks code by route. Users only load JS needed for the current page. +2. **Lazy Loading**: For large components (charts, maps), wrap with `next/dynamic` to load them only when needed. +3. **Image Optimization**: Use Next.js `` component to serve responsive, compressed images. +4. **Caching**: + - Static assets (CSS, fonts) use long cache headers. + - API responses can be cached or ISR (Incremental Static Regeneration) applied. +5. **Minification & Compression**: Next.js production builds automatically minify JS and CSS, and enable Brotli/Gzip on the CDN. + +These steps ensure fast page loads and smooth interactions. + +--- + +## 8. Testing and Quality Assurance + +**Unit Tests** +- **Jest** + **React Testing Library** for components and utility functions. +- Example: test that the Sign In form shows an error message when fields are empty. + +**Integration Tests** +- Combine multiple components and hooks; test API calls with **msw** (Mock Service Worker). + +**End-to-End (E2E) Tests** +- **Cypress** or **Playwright** to simulate real user flows: signing up, logging in, and viewing the dashboard. + +**Linting & Formatting** +- **ESLint** enforces code style and catches common bugs. +- **Prettier** applies consistent formatting. +- **Git Hooks** (via Husky) run linting/tests before each commit. + +**Continuous Integration (CI)** +- **GitHub Actions** runs tests and lint on each pull request, preventing regressions. + +--- + +## 9. Conclusion and Overall Frontend Summary + +The `codeguide-starter` frontend is built on modern, well-established tools—Next.js, React, and TypeScript—and follows clear principles around usability, accessibility, and maintainability. Its file-based structure, component-driven approach, and CSS-variable theming keep things organized and consistent. + +Key takeaways: +- **Scalable Structure**: Add new features by creating new folders under `app/` without touching a central router. +- **Component Reuse**: Shared UI pieces live in one place, making updates quick and error-free. +- **Simple Styling**: Global and section-specific CSS, underpinned by CSS variables, ensures a unified look. +- **Smooth Performance**: Next.js automatic optimizations plus best practices like lazy loading and caching. +- **Quality Assurance**: A testing plan that covers unit, integration, and E2E scenarios, enforced by CI. + +With these guidelines, any developer coming into the project can understand how the pieces fit together, how to follow existing patterns, and how to keep the app fast, reliable, and easy to grow. \ No newline at end of file diff --git a/documentation/project_requirements_document.md b/documentation/project_requirements_document.md new file mode 100644 index 0000000..526d663 --- /dev/null +++ b/documentation/project_requirements_document.md @@ -0,0 +1,117 @@ +# Project Requirements Document: codeguide-starter + +--- + +## 1. Project Overview + +The **codeguide-starter** project is a boilerplate web application that provides a ready-made foundation for any web project requiring secure user authentication and a post-login dashboard. It sets up the common building blocks—sign-up and sign-in pages, API routes to handle registration and login, and a simple dashboard interface driven by static data. By delivering this skeleton, it accelerates development time and ensures best practices are in place from day one. + +This starter kit is being built to solve the friction developers face when setting up repeated common tasks: credential handling, session management, page routing, and theming. Key objectives include: 1) delivering a fully working authentication flow (registration & login), 2) providing a gated dashboard area upon successful login, 3) establishing a clear, maintainable project structure using Next.js and TypeScript, and 4) demonstrating a clean theming approach with global and section-specific CSS. Success is measured by having an end-to-end login journey in under 200 lines of code and zero runtime type errors. + +--- + +## 2. In-Scope vs. Out-of-Scope + +### In-Scope (Version 1) +- User registration (sign-up) form with validation +- User login (sign-in) form with validation +- Next.js API routes under `/api/auth/route.ts` handling: + - Credential validation + - Password hashing (e.g., bcrypt) + - Session creation or JWT issuance +- Protected dashboard pages under `/dashboard`: + - `layout.tsx` wrapping dashboard content + - `page.tsx` rendering static data from `data.json` +- Global application layout in `/app/layout.tsx` +- Basic styling via `globals.css` and `dashboard/theme.css` +- TypeScript strict mode enabled + +### Out-of-Scope (Later Phases) +- Integration with a real database (PostgreSQL, MongoDB, etc.) +- Advanced authentication flows (password reset, email verification, MFA) +- Role-based access control (RBAC) +- Multi-tenant or white-label theming +- Unit, integration, or end-to-end testing suites +- CI/CD pipeline and production deployment scripts + +--- + +## 3. User Flow + +A new visitor lands on the root URL and sees a welcome page with options to **Sign Up** or **Sign In**. If they choose Sign Up, they fill in their email, password, and hit “Create Account.” The form submits to `/api/auth/route.ts`, which hashes the password, creates a new user session or token, and redirects them to the dashboard. If any input is invalid, an inline error message explains the issue (e.g., “Password too short”). + +Once authenticated, the user is taken to the `/dashboard` route. Here they see a sidebar or header defined by `dashboard/layout.tsx`, and the main panel pulls in static data from `data.json`. They can log out (if that control is present), but otherwise their entire session is managed by server-side cookies or tokens. Returning users go directly to Sign In, submit credentials, and upon success they land back on `/dashboard`. Any unauthorized access to `/dashboard` redirects back to Sign In. + +--- + +## 4. Core Features + +- **Sign-Up Page (`/app/sign-up/page.tsx`)**: Form fields for email & password, client-side validation, POST to `/api/auth`. +- **Sign-In Page (`/app/sign-in/page.tsx`)**: Form fields for email & password, client-side validation, POST to `/api/auth`. +- **Authentication API (`/app/api/auth/route.ts`)**: Handles both registration and login based on HTTP method, integrates password hashing (bcrypt) and session or JWT logic. +- **Global Layout (`/app/layout.tsx` + `globals.css`)**: Shared header, footer, and CSS resets across all pages. +- **Dashboard Layout (`/app/dashboard/layout.tsx` + `dashboard/theme.css`)**: Sidebar or top nav for authenticated flows, section-specific styling. +- **Dashboard Page (`/app/dashboard/page.tsx`)**: Reads `data.json`, renders it as cards or tables. +- **Static Data Source (`/app/dashboard/data.json`)**: Example dataset to demo dynamic rendering. +- **TypeScript Configuration**: `tsconfig.json` with strict mode and path aliases (if any). + +--- + +## 5. Tech Stack & Tools + +- **Framework**: Next.js (App Router) for file-based routing, SSR/SSG, and API routes. +- **Language**: TypeScript for type safety. +- **UI Library**: React 18 for component-based UI. +- **Styling**: Plain CSS via `globals.css` (global reset) and `theme.css` (sectional styling). Can easily migrate to CSS Modules or Tailwind in the future. +- **Backend**: Node.js runtime provided by Next.js API routes. +- **Password Hashing**: bcrypt (npm package). +- **Session/JWT**: NextAuth.js or custom JWT logic (to be decided in implementation). +- **IDE & Dev Tools**: VS Code with ESLint, Prettier extensions. Optionally, Cursor.ai for AI-assisted coding. + +--- + +## 6. Non-Functional Requirements + +- **Performance**: Initial page load under 200 ms on a standard broadband connection. API responses under 300 ms. +- **Security**: + - HTTPS only in production. + - Proper CORS, CSRF protection for API routes. + - Secure password storage (bcrypt with salt). + - No credentials or secrets checked into version control. +- **Scalability**: Structure must support adding database integration, caching layers, and advanced auth flows without rewiring core app. +- **Usability**: Forms should give real-time feedback on invalid input. Layout must be responsive (mobile > 320 px). +- **Maintainability**: Code must adhere to TypeScript strict mode. Linting & formatting enforced by ESLint/Prettier. + +--- + +## 7. Constraints & Assumptions + +- **No Database**: Dashboard uses only `data.json`; real database integration is deferred. +- **Node Version**: Requires Node.js >= 14. +- **Next.js Version**: Built on Next.js 13+ App Router. +- **Authentication**: Assumes availability of bcrypt or NextAuth.js at implementation time. +- **Hosting**: Targets serverless or Node.js-capable hosting (e.g., Vercel, Netlify). +- **Browser Support**: Modern evergreen browsers; no IE11 support required. + +--- + +## 8. Known Issues & Potential Pitfalls + +- **Static Data Limitation**: `data.json` is only for demo. A real API or database will be needed to avoid stale data. + *Mitigation*: Define a clear interface for data fetching so swapping to a live endpoint is trivial. + +- **Global CSS Conflicts**: Using global styles can lead to unintended overrides. + *Mitigation*: Plan to migrate to CSS Modules or utility-first CSS in Phase 2. + +- **API Route Ambiguity**: Single `/api/auth/route.ts` handling both sign-up and sign-in could get complex. + *Mitigation*: Clearly branch on HTTP method (`POST /register` vs. `POST /login`) or split into separate files. + +- **Lack of Testing**: No test suite means regressions can slip in. + *Mitigation*: Build a minimal Jest + React Testing Library setup in an early iteration. + +- **Error Handling Gaps**: Client and server must handle edge cases (network failures, malformed input). + *Mitigation*: Define a standard error response schema and show user-friendly messages. + +--- + +This PRD should serve as the single source of truth for the AI model or any developer generating the next set of technical documents: Tech Stack Doc, Frontend Guidelines, Backend Structure, App Flow, File Structure, and IDE Rules. It contains all functional and non-functional requirements with no ambiguity, enabling seamless downstream development. diff --git a/documentation/security_guideline_document.md b/documentation/security_guideline_document.md new file mode 100644 index 0000000..683c23f --- /dev/null +++ b/documentation/security_guideline_document.md @@ -0,0 +1,116 @@ +# Security Guidelines for codeguide-starter + +This document defines mandatory security principles and implementation best practices tailored to the **codeguide-starter** repository. It aligns with Security-by-Design, Least Privilege, Defense-in-Depth, and other core security tenets. All sections reference specific areas of the codebase (e.g., `/app/api/auth/route.ts`, CSS files, environment configuration) to ensure practical guidance. + +--- + +## 1. Security by Design + +• Embed security from day one: review threat models whenever adding new features (e.g., new API routes, data fetching). +• Apply “secure defaults” in Next.js configuration (`next.config.js`), enabling strict mode and disabling debug flags in production builds. +• Maintain a security checklist in your PR template to confirm that each change has been reviewed against this guideline. + +--- + +## 2. Authentication & Access Control + +### 2.1 Password Storage +- Use **bcrypt** (or Argon2) with a per-user salt to hash passwords in `/app/api/auth/route.ts`. +- Enforce a strong password policy on both client and server: minimum 12 characters, mixed case, numbers, and symbols. + +### 2.2 Session Management +- Issue sessions via Secure, HttpOnly, SameSite=strict cookies. Do **not** expose tokens to JavaScript. +- Implement absolute and idle timeouts. For example, invalidate sessions after 30 minutes of inactivity. +- Protect against session fixation by regenerating session IDs after authentication. + +### 2.3 Brute-Force & Rate Limiting +- Apply rate limiting at the API layer (e.g., using `express-rate-limit` or Next.js middleware) on `/api/auth` to throttle repeated login attempts. +- Introduce exponential backoff or temporary lockout after N failed attempts. + +### 2.4 Role-Based Access Control (Future) +- Define user roles in your database model (e.g., `role = 'user' | 'admin'`). +- Enforce server-side authorization checks in every protected route (e.g., in `dashboard/layout.tsx` loader functions). + +--- + +## 3. Input Handling & Processing + +### 3.1 Validate & Sanitize All Inputs +- On **client** (`sign-up/page.tsx`, `sign-in/page.tsx`): perform basic format checks (email regex, password length). +- On **server** (`/app/api/auth/route.ts`): re-validate inputs with a schema validator (e.g., `zod`, `Joi`). +- Reject or sanitize any unexpected fields to prevent injection attacks. + +### 3.2 Prevent Injection +- If you introduce a database later, always use parameterized queries or an ORM (e.g., Prisma) rather than string concatenation. +- Avoid dynamic `eval()` or template rendering with unsanitized user input. + +### 3.3 Safe Redirects +- When redirecting after login or logout, validate the target against an allow-list to prevent open redirects. + +--- + +## 4. Data Protection & Privacy + +### 4.1 Encryption & Secrets +- Enforce HTTPS/TLS 1.2+ for all front-end ↔ back-end communications. +- Never commit secrets—use environment variables and a secrets manager (e.g., AWS Secrets Manager, Vault). + +### 4.2 Sensitive Data Handling +- Do ​not​ log raw passwords, tokens, or PII in server logs. Mask or redact any user identifiers. +- If storing PII in `data.json` or a future database, classify it and apply data retention policies. + +--- + +## 5. API & Service Security + +### 5.1 HTTPS Enforcement +- In production, redirect all HTTP traffic to HTTPS (e.g., via Vercel’s redirect rules or custom middleware). + +### 5.2 CORS +- Configure `next.config.js` or API middleware to allow **only** your front-end origin (e.g., `https://your-domain.com`). + +### 5.3 API Versioning & Minimal Exposure +- Version your API routes (e.g., `/api/v1/auth`) to handle future changes without breaking clients. +- Return only necessary fields in JSON responses; avoid leaking internal server paths or stack traces. + +--- + +## 6. Web Application Security Hygiene + +### 6.1 CSRF Protection +- Use anti-CSRF tokens for any state-changing API calls. Integrate Next.js CSRF middleware or implement synchronizer tokens stored in cookies. + +### 6.2 Security Headers +- In `next.config.js` (or a custom server), add these headers: + - `Strict-Transport-Security: max-age=63072000; includeSubDomains; preload` + - `X-Content-Type-Options: nosniff` + - `X-Frame-Options: DENY` + - `Referrer-Policy: no-referrer-when-downgrade` + - `Content-Security-Policy`: restrict script/style/src to self and trusted CDNs. + +### 6.3 Secure Cookies +- Set `Secure`, `HttpOnly`, `SameSite=Strict` on all cookies. Avoid storing sensitive data in `localStorage`. + +### 6.4 Prevent XSS +- Escape or encode all user-supplied data in React templates. Avoid `dangerouslySetInnerHTML` unless content is sanitized. + +--- + +## 7. Infrastructure & Configuration Management + +- Harden your hosting environment (e.g., Vercel/Netlify) by disabling unnecessary endpoints (GraphQL/GraphiQL playgrounds in production). +- Rotate secrets and API keys regularly via your secrets manager. +- Maintain minimal privileges: e.g., database accounts should only have read/write on required tables. +- Keep Node.js, Next.js, and all system packages up to date. + +--- + +## 8. Dependency Management + +- Commit and maintain `package-lock.json` to guarantee reproducible builds. +- Integrate a vulnerability scanner (e.g., GitHub Dependabot, Snyk) to monitor and alert on CVEs in dependencies. +- Trim unused packages; each added library increases the attack surface. + +--- + +Adherence to these guidelines will ensure that **codeguide-starter** remains secure, maintainable, and resilient as it evolves. Regularly review and update this document to reflect new threats and best practices. \ No newline at end of file diff --git a/documentation/tech_stack_document.md b/documentation/tech_stack_document.md new file mode 100644 index 0000000..6db3f9b --- /dev/null +++ b/documentation/tech_stack_document.md @@ -0,0 +1,90 @@ +# Tech Stack Document + +This document explains the key technologies chosen for the **codeguide-starter** project. It’s written in everyday language so anyone—technical or not—can understand why each tool was picked and how it supports the application. + +## 1. Frontend Technologies +The frontend is everything the user sees and interacts with. For this project, we’ve used: + +- **Next.js (App Router)** + - A React framework that makes page routing, server-side rendering, and API routes very simple. + - Enhances user experience by pre-rendering pages on the server or at build time, leading to faster initial load. +- **React 18** + - The underlying library for building user interfaces with reusable components. + - Provides a smooth, interactive experience thanks to its virtual DOM and modern hooks. +- **TypeScript** + - A superset of JavaScript that adds types (labels for data). + - Helps catch errors early during development and makes the code easier to maintain. +- **CSS (globals.css & theme.css)** + - **globals.css** applies base styles (fonts, colors, resets) across the entire app. + - **dashboard/theme.css** defines the look and feel specific to the dashboard area. + - This separation keeps styles organized and avoids accidental style conflicts. + +By combining these tools, we have a clear structure (Next.js folders for pages and layouts), safer code (TypeScript), and flexible styling with vanilla CSS. + +## 2. Backend Technologies +The backend handles data, user accounts, and the logic behind the scenes. Our choices here are: + +- **Next.js API Routes** + - Allows us to write server-side code (`route.ts` files) alongside our frontend in the same project. + - Runs on Node.js, so we can handle requests like sign-up, sign-in, and data fetching in one place. +- **Node.js Runtime** + - The JavaScript environment on the server that executes our API routes. +- **bcrypt** (npm package) + - A library for hashing passwords securely before storing them. + - Ensures that even if someone got access to our data, raw passwords aren’t visible. +- **(Optional) NextAuth.js or JWT** + - While this starter kit shows a custom authentication flow, it can easily integrate services like NextAuth.js for email-based login or JWT (JSON Web Tokens) for stateless sessions. + +These components work together to receive user credentials, verify or store them securely, manage sessions or tokens, and deliver protected data back to the frontend. + +## 3. Infrastructure and Deployment +Infrastructure covers where and how we host the app, as well as how changes get delivered: + +- **Git & GitHub** + - Version control system (Git) and remote hosting (GitHub) keep track of all code changes and allow team collaboration. +- **Vercel (or Netlify)** + - A popular hosting service optimized for Next.js, with one-click deployments and global content delivery. + - Automatically rebuilds and deploys the site whenever code is pushed to the main branch. +- **GitHub Actions (CI/CD)** + - Automates tasks like linting (ESLint), formatting (Prettier), and running any tests you add. + - Ensures that only clean, tested code goes live. + +Together, these tools provide a reliable, scalable setup where every code change is tested and deployed quickly, with minimal manual work. + +## 4. Third-Party Integrations +While this starter kit is minimal by design, it already includes or can easily add: + +- **bcrypt** + - For secure password hashing (included as an npm dependency). +- **NextAuth.js** (optional) + - A full-featured authentication library supporting email/password, OAuth, and more. +- **Sentry or LogRocket** (optional) + - For real-time error tracking and performance monitoring in production. + +These integrations help extend the app’s capabilities without building every feature from scratch. + +## 5. Security and Performance Considerations +We’ve baked in several measures to keep users safe and the app running smoothly: + +Security: +- Passwords are never stored in plain text—bcrypt hashes them with a random salt. +- API routes can implement CSRF protection and input validation to block malicious requests. +- Session tokens or cookies are marked secure and HttpOnly to prevent theft via JavaScript. + +Performance: +- Server-side rendering (SSR) and static site generation (SSG) in Next.js deliver pages faster. +- Code splitting and lazy-loaded components ensure users only download what they need. +- Global CSS and theme files are small and cached by the browser for quick repeat visits. + +These strategies work together to give users a fast, secure experience every time. + +## 6. Conclusion and Overall Tech Stack Summary +In building **codeguide-starter**, we chose technologies that: + +- Align with modern web standards (Next.js, React, TypeScript). +- Provide a clear, file-based project structure for rapid onboarding. +- Offer built-in support for server-side rendering, API routes, and static assets. +- Emphasize security through password hashing, session management, and safe defaults. +- Enable easy scaling and future enhancements via modular code and optional integrations. + +This stack strikes a balance between simplicity for newcomers and flexibility for experienced teams. It accelerates development of a secure authentication flow and a polished dashboard, while leaving room to plug in databases, test suites, and advanced features as the project grows. \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 5760b7c..4de9436 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,11 +1,11 @@ { - "name": "codeguide-starter", + "name": "codeguide-starter-fullstack", "version": "0.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "codeguide-starter", + "name": "codeguide-starter-fullstack", "version": "0.1.0", "dependencies": { "@dnd-kit/core": "^6.3.1", diff --git a/package.json b/package.json index 4e1da44..e63ca9b 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "name": "codeguide-starter", + "name": "codeguide-starter-fullstack", "version": "0.1.0", "private": true, "scripts": { @@ -17,7 +17,7 @@ "db:dev": "docker compose --profile dev up postgres-dev -d", "db:dev-down": "docker compose --profile dev down postgres-dev", "db:reset": "drizzle-kit drop && drizzle-kit push", - "docker:build": "docker build -t codeguide-starter .", + "docker:build": "docker build -t codeguide-starter-fullstack .", "docker:up": "docker compose up -d", "docker:down": "docker compose down", "docker:logs": "docker compose logs -f" diff --git a/reference Readme.md b/reference Readme.md index 4ba2b0e..9f4e153 100644 --- a/reference Readme.md +++ b/reference Readme.md @@ -1,6 +1,6 @@ [![CodeGuide](/codeguide-backdrop.svg)](https://codeguide.dev) -# CodeGuide Starter Kit +# Codeguide Starter Fullstack A modern web application starter template built with Next.js 15, featuring authentication, database integration, AI capabilities, and dark mode support. @@ -29,7 +29,7 @@ Before you begin, ensure you have the following: 1. **Clone the repository** ```bash git clone - cd codeguide-starter-kit + cd codeguide-starter-fullstack ``` 2. **Install dependencies** @@ -116,7 +116,7 @@ ANTHROPIC_API_KEY=your_anthropic_api_key ## Project Structure ``` -codeguide-starter-kit/ +codeguide-starter-fullstack/ ├── src/ │ ├── app/ # Next.js app router pages │ │ ├── api/chat/ # AI chat API endpoint