Skip to content

Commit 20189a6

Browse files
committed
Add CSRF, reCAPTCHA, audit logging, GDPR APIs
Implements multiple security, persistence and data-governance improvements: adds custom CSRF utilities and React CsrfProvider (sets CSRF cookie during GitHub auth and validates on forms), integrates reCAPTCHA v3 on the Support form with server-side verification and score checks, and instruments audit logging with a new web/lib/audit.ts and accompanying DB migration. Persists user configuration to Supabase via a new user_configs table and updates /api/config to GET/POST real data with tier checks and audit logging. Adds GDPR endpoints for data export and account deletion (rate-limited), a Supabase data-retention migration and a scheduled cleanup Edge Function. Also updates layout and support UI, and adds reCAPTCHA dependencies to package.json.
1 parent 1ab5a57 commit 20189a6

21 files changed

Lines changed: 1438 additions & 126 deletions

File tree

docs/implementation.md

Lines changed: 95 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ This document outlines the implementation priorities for GitPulse based on curre
3030
**Priority:** High
3131
**Effort:** Low (15 minutes)
3232

33-
### 1.3 Login Page Logo
33+
### 1.3 Login Page Logo (Temporary)
3434
**File:** `web/app/login/page.tsx`
3535
**Asset:** `assets/GitPulseLogo.png` (white background for contrast)
3636

@@ -39,41 +39,27 @@ This document outlines the implementation priorities for GitPulse based on curre
3939
2. Ensure proper sizing and spacing
4040
3. Maintain brand consistency
4141

42+
**Status:** Temporary - may be removed based on feedback
4243
**Priority:** Medium
4344
**Effort:** Low (10 minutes)
4445

4546
---
4647

4748
## Phase 2: Data Architecture (Short-term)
4849

49-
### 2.1 Config Persistence
50+
### 2.1 Config Persistence ✅ COMPLETED
5051
**Files:**
5152
- `web/app/api/config/route.ts`
5253
- `web/lib/telemetry-client.ts`
54+
- `web/supabase/migrations/20240417_create_user_configs.sql`
5355

54-
**Current State:**
55-
- `/api/config` returns mock data
56-
- `updateConfig()` only logs to console
57-
- No actual persistence
58-
59-
**Implementation Options:**
60-
61-
**Option A: Supabase Table (Recommended)**
62-
```sql
63-
CREATE TABLE user_configs (
64-
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
65-
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
66-
config JSONB NOT NULL DEFAULT '{}',
67-
updated_at TIMESTAMP DEFAULT NOW(),
68-
UNIQUE(user_id)
69-
);
70-
```
71-
72-
**Option B: CLI Config File Sync**
73-
- Read/write to `.gitpulse/config.json`
74-
- Sync between CLI and web dashboard
75-
- More complex but keeps config local
56+
**Implementation:**
57+
- Created Supabase table `user_configs` with RLS policies
58+
- Updated `/api/config` GET to fetch from database with fallback to default
59+
- Updated `/api/config` POST to save to database with tier checking
60+
- Updated `telemetry-client.ts` to use real config from API
7661

62+
**Status:** Completed
7763
**Priority:** High (blocking feature)
7864
**Effort:** Medium (2-3 hours)
7965

@@ -90,73 +76,128 @@ CREATE TABLE user_configs (
9076

9177
## Phase 3: Security Improvements (Medium-term)
9278

93-
### 3.1 reCAPTCHA Integration
79+
### 3.1 reCAPTCHA v3 Integration ✅ COMPLETED
9480
**Target Forms:** Support page (`web/app/support/page.tsx`)
9581

9682
**Implementation:**
97-
1. Sign up for Google reCAPTCHA v2
83+
1. Sign up for Google reCAPTCHA v3
9884
2. Add to environment variables:
9985
```env
10086
NEXT_PUBLIC_RECAPTCHA_SITE_KEY=your_site_key
10187
RECAPTCHA_SECRET_KEY=your_secret_key
10288
```
103-
3. Add reCAPTCHA component to form
104-
4. Validate token in `/api/support/route.ts`
89+
3. Install `react-google-recaptcha-v3` package
90+
4. Wrap form with `GoogleReCaptchaProvider`
91+
5. Use `useGoogleReCaptcha` hook to execute invisible verification
92+
6. Validate token with Google API in `/api/support/route.ts`
93+
7. Check score (0.0-1.0, reject if < 0.5)
10594

95+
**Status:** Completed
10696
**Priority:** Medium
10797
**Effort:** Medium (1-2 hours)
10898

109-
### 3.2 CSRF Protection
99+
### 3.2 CSRF Protection ✅ COMPLETED
110100
**Implementation:**
111-
1. Install CSRF library (e.g., `csurf` or custom implementation)
112-
2. Generate CSRF tokens on session creation
113-
3. Validate on POST/PUT/DELETE requests
114-
4. Add tokens to forms
115-
101+
1. Created custom CSRF utilities (`web/lib/csrf.ts`)
102+
2. Generate CSRF tokens on session creation (`/api/auth/github/route.ts`)
103+
3. Created CSRF context/provider (`web/lib/csrf-context.tsx`)
104+
4. Added CSRF validation to support API (`/api/support/route.ts`)
105+
5. Added CSRF token to form headers (support page)
106+
107+
**Files Created:**
108+
- `web/lib/csrf.ts` - CSRF token generation and verification
109+
- `web/lib/csrf-context.tsx` - React context for accessing token
110+
111+
**Files Modified:**
112+
- `web/app/layout.tsx` - Added CsrfProvider wrapper
113+
- `web/app/api/auth/github/route.ts` - Generate and set CSRF cookie on auth
114+
- `web/app/support/page.tsx` - Include CSRF token in form submission
115+
- `web/app/api/support/route.ts` - Validate CSRF token
116+
117+
**Status:** Completed
116118
**Priority:** Medium
117119
**Effort:** Medium (2-3 hours)
118120

119-
### 3.3 Audit Logging
121+
### 3.3 Audit Logging ✅ COMPLETED
120122
**Target Operations:**
121-
- API key creation/revocation
122-
- Config changes
123-
- User settings updates
124-
- Support ticket submissions
123+
- API key creation/revocation
124+
- Config changes
125+
- User settings updates
126+
- Support ticket submissions
125127

126128
**Implementation:**
129+
- Created SQL migration for `audit_logs` table with RLS policies
130+
- Created `web/lib/audit.ts` with logging utilities
131+
- Added logging to:
132+
- `/api/keys/route.ts` - API key create/revoke
133+
- `/api/config/route.ts` - Config updates
134+
- `/api/settings/route.ts` - Settings updates
135+
- `/api/support/route.ts` - Support ticket creation
136+
137+
**Files Created:**
138+
- `web/supabase/migrations/20240417_create_audit_logs.sql`
139+
- `web/lib/audit.ts`
140+
141+
**Audit Log Schema:**
127142
```sql
128143
CREATE TABLE audit_logs (
129-
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
144+
id UUID PRIMARY KEY,
130145
user_id UUID REFERENCES users(id),
131-
action VARCHAR(50) NOT NULL,
132-
resource_type VARCHAR(50),
146+
action VARCHAR(50) NOT NULL, -- e.g., 'api_key.create'
147+
resource_type VARCHAR(50), -- e.g., 'api_key'
133148
resource_id UUID,
134-
details JSONB,
149+
details JSONB, -- Additional context
135150
ip_address INET,
136-
created_at TIMESTAMP DEFAULT NOW()
151+
user_agent TEXT,
152+
timestamp TIMESTAMP,
153+
success BOOLEAN
137154
);
138155
```
139156

157+
**Status:** Completed
140158
**Priority:** Medium
141159
**Effort:** Medium (3-4 hours)
142160

143161
---
144162

145163
## Phase 4: Data Governance (Long-term)
146164

147-
### 4.1 Data Retention Policy
165+
### 4.1 Data Retention Policy ✅ COMPLETED
148166
**Retention Rules:**
149-
- Telemetry runs: 90 days
150-
- Support tickets: 365 days (after resolution)
151-
- API keys: No expiration (add feature)
152-
- Audit logs: 180 days
167+
- Telemetry runs: 90 days ✅
168+
- Support tickets: 365 days (after resolution) ✅
169+
- Audit logs: 180 days ✅
153170

154171
**Implementation:**
155-
1. Add retention columns to tables
156-
2. Create scheduled cleanup job (Supabase Edge Function or cron)
157-
3. Add user-facing data export (GDPR)
158-
4. Add user account deletion with data wipe
159-
172+
1. Created SQL migration (`20240417_data_retention.sql`):
173+
- Added `retention_until` columns to telemetry_runs, support_tickets, audit_logs
174+
- Created cleanup function `cleanup_expired_data()`
175+
- Added trigger for auto-setting retention on ticket resolution
176+
177+
2. Created Supabase Edge Function (`supabase/functions/data-cleanup/`):
178+
- Scheduled cleanup job
179+
- Runs `cleanup_expired_data()` function
180+
- Requires CRON_SECRET for authorization
181+
182+
3. GDPR Data Export (`/api/user/export`):
183+
- Exports all user data as JSON
184+
- Includes profile, API keys, configs, telemetry, tickets, audit logs
185+
- Rate limited: 3 exports/hour
186+
187+
4. Account Deletion (`/api/user/delete`):
188+
- Full data wipe (Right to be Forgotten)
189+
- Requires confirmation flag
190+
- Deletes all tables in correct order
191+
- Clears session cookies
192+
- Rate limited: 1 attempt/hour
193+
194+
**Files Created:**
195+
- `web/supabase/migrations/20240417_data_retention.sql`
196+
- `web/supabase/functions/data-cleanup/index.ts`
197+
- `web/app/api/user/export/route.ts`
198+
- `web/app/api/user/delete/route.ts`
199+
200+
**Status:** Completed
160201
**Priority:** Low
161202
**Effort:** High (1-2 days)
162203

docs/project_dossier.md

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
# GitPulse: Project Dossier - Technical & Strategic Overview
2+
**Document Date:** April 17, 2026
3+
**Lead AI Assistant:** Antigravity
4+
**Status:** Phase 6 - Foundation Reset
5+
6+
---
7+
8+
## 1. Executive Summary
9+
10+
**GitPulse** is the governance layer for the AI-assisted developer era. It provides automated guardrails (Quality Gates) and context-aware intelligence (Convention Learning) to ensure that code generated by tools like Cursor, Windsurf, or Copilot adheres to team standards, security protocols, and architectural patterns.
11+
12+
GitPulse bridges the gap between the velocity of AI and the rigor of production engineering. It operates as a local-first CLI, an MCP server, and a cloud-synced analytics platform.
13+
14+
---
15+
16+
## 2. Technical Deep Dive: The Governance Engine
17+
18+
The core of GitPulse is its **Quality Gates Engine**, which performs incremental, AST-aware (via Babel) and pattern-based scanning of staged changes.
19+
20+
### A. Security Guardrails (`SecurityScanGate`)
21+
The engine uses high-signal regex patterns and AST analysis to block commits containing:
22+
- **Hardcoded Secrets:** Scans for `password`, `api_key`, `secret`, `token`, and `aws_access_key` with proximity-based value detection.
23+
- **SQL Injection:** Detects template literals in raw queries (e.g., `query(\`...\${...}\`)`) and string concatenation with request parameters.
24+
- **XSS Vulnerabilities:** Flags `innerHTML` assignments and React's `dangerouslySetInnerHTML`.
25+
- **Path Traversal:** Identifies `fs` operations using unvalidated `req.*` input.
26+
27+
### B. Structural Integrity (`CodeSmellsGate`)
28+
- **Complexity Thresholds:** Flags functions exceeding **50 lines** and files exceeding **500 lines**.
29+
- **God Class Detection:** Monitors classes with more than **20 methods**.
30+
- **Cruft Removal:** Blocks commits containing `console.log`, `debugger`, or unresolved `TODO`/`FIXME` markers in production-bound code.
31+
32+
### C. Parity & Compliance
33+
- **Test Coverage Gate:** Heuristically checks for corresponding `.test.ts`, `.spec.ts`, or `test_*.py` files for every new or modified logic file.
34+
- **Documentation Gate:** Ensures every **exported** function or class is preceded by a valid JSDoc (`/** ... */`) block.
35+
36+
---
37+
38+
## 3. Technical Deep Dive: Context-Aware Intelligence
39+
40+
### Convention Learning Heuristic
41+
Instead of hardcoded rules, GitPulse analyzes the repository's `.git` history to detect:
42+
- **Naming Conventions:** automatically identifying if the team prefers `camelCase`, `PascalCase`, or `snake_case` for different file types.
43+
- **Commit Patterns:** Learning if the project follows `Conventional Commits` or a custom `Semantic` style.
44+
- **Architectural Boundaries:** Identifying file co-change patterns to suggest architectural violations (e.g., "This UI component shouldn't be importing from the DB layer").
45+
46+
---
47+
48+
## 4. Systems Architecture
49+
50+
### Local-to-Cloud Sync (Claude Code Pattern)
51+
GitPulse implements a hybrid architecture that balances privacy with team visibility:
52+
1. **Local Core:** All git operations and quality scans happen on the developer's machine. Telemetry is stored locally in `.gitpulse/telemetry.jsonl`.
53+
2. **Secure Sync:** If an API key is present, the CLI non-blockingly syncs metadata to **Supabase** via a secure `cloud-sync` module. This ensures zero latency during the commit flow.
54+
3. **Web Dashboard:** A Next.js 16 app provides a team-wide view of these metrics, secured via **JWT-encrypted sessions** and HTTP-only cookies.
55+
56+
### Tech Stack Breakdown
57+
- **Runtime:** Node.js 18+ (TypeScript 5.3)
58+
- **CLI Rendering:** [Ink](https://github.com/vadimdemedes/ink) (React-based terminal DSL)
59+
- **AST Parsing:** Babel Parser & Traverse
60+
- **Database:** Supabase (PostgreSQL + Auth + Realtime)
61+
- **AI Providers:** Multi-provider client supporting Ollama (Local), OpenRouter, OpenAI, Google Lyria/Gemma, and Groq.
62+
63+
---
64+
65+
## 5. Business & Strategic Metrics (Pulse Metrics)
66+
67+
For mentors and investors, GitPulse quantifies the "AI Technical Debt" it prevents:
68+
- **AI Efficiency Ratio:** Measures the percentage of AI-assisted commits vs. manual work.
69+
- **Hours Saved:** A conservative calculation of **2 minutes saved per AI-assisted commit**.
70+
- **Quality Score:** A weighted aggregate metric of repository health (Pass/Fail rate of gates).
71+
- **Issue Prevention:** Real-time counter of total security risks and smells caught before merge.
72+
- **Momentum Heatmap:** GitHub-style visualization of team velocity.
73+
74+
---
75+
76+
## 6. Project Status & Roadmap
77+
78+
### Current Focus: Phase 6 - Foundation Reset
79+
The product is currently being hardened for production-grade team usage.
80+
- **Production Readiness:** JWT encryption, rate limiting, and input validation for the web dashboard are **Complete**.
81+
- **Major Risk:** **0% Test Coverage** on core modules. This is the P0 priority for the next development sprint.
82+
- **CI/CD Integration:** A basic GitHub Action (`action/`) is functional; next step is a marketplace-grade integration.
83+
84+
### Strategic Roadmap
85+
- **Phase 7 (Medium Term):** Expand MCP from 3 tools to 10+ (Semantic history search, risk scoring).
86+
- **Phase 8 (Long Term):** **Convention Marketplace** for sharing/selling rule packs for specific frameworks (Next.js, Django, etc.).
87+
88+
---
89+
90+
## 7. Critical Risks & Technical Debt
91+
92+
| Risk | Severity | Mitigation Plan |
93+
| :--- | :---: | :--- |
94+
| **Test Coverage** | 🔴 Critical | Initialize Vitest suite for `quality-gates.ts` and `convention-learner.ts`. |
95+
| **Type Safety** | 🟠 Medium | Refactor `args: any` in MCP server tool handlers. |
96+
| **Monorepo Split** | 🟡 Low | Separate CLI and Web codebases into a shared monorepo structure for type reuse. |
97+
98+
---
99+
100+
**License:** Proprietary. Copyright (c) 2025 Rishi Praseeth Krishnan. All rights reserved.
101+
**Repository:** [CodedRichy/GitPulse](https://github.com/CodedRichy/GitPulse)

0 commit comments

Comments
 (0)