# Project export: ShadowGuard-AI

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: UC Berkeley AI Hackathon 2026
- Tagline: ShadowGuard AI: Your 100% local, zero-trust AI security bodyguard that blocks sensitive data leaks before they ever leave your browser.
- Devpost: https://devpost.com/software/shadowguard-ai-26q9y0
- GitHub: https://github.com/s333s/ShadowGuard-AI
- Video: https://www.youtube.com/embed/bPYgBfl567s?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 1 GitHub contributor(s) — s3x0s (1 commits)

## Devpost submission (written by the team)

### Overview

🛡️

### Inspiration

We noticed a massive security blind spot in the AI era: developers and users are constantly copy-pasting code, logs, and environment variables into AI chatbots (ChatGPT, Claude, Gemini) for debugging. One accidental paste of an AWS key, GitHub token, or credit card can lead to a catastrophic breach. Existing Data Loss Prevention (DLP) tools are enterprise-heavy, cloud-based, and ironically, require sending your data to a third-party server to check if it's sensitive. We wanted to build a "security bodyguard" that stops the leak before it leaves the browser. 🚀

### What it does

ShadowGuard AI is a Chrome extension that intercepts paste events and keystrokes, running a 100% local, synchronous regex and heuristic engine to detect PII and secrets. If a leak is detected, it instantly blocks the paste and flashes a red overlay. It also features a real-time WebSocket dashboard that visualizes live threats and scans your other installed Chrome extensions for dangerous permission combinations. 🛠️

### How we built it

Extension (Phase 1): Built with React, TypeScript, and Manifest V3. We used capture-phase event listeners to synchronously block pastes without relying on heavy MutationObservers. Detection Engine: We implemented a comprehensive pattern-matching library. To avoid false positives (e.g., flagging a 16-digit order ID as a credit card), we wrote a synchronous Luhn algorithm check directly in the content script. Backend & Dashboard (Phase 2): Built a FastAPI backend with WebSockets. The React dashboard visualizes live threats and historical charts using Recharts. Zero-Trust Architecture: We designed the system so that no raw data ever leaves the browser. Even when the backend receives telemetry, it only receives heavily masked metadata (e.g., AKIA****MPLE). 🚧 Challenges & Accomplishments Regex vs. False Positives: Implementing the Luhn check in the browser was a massive win for the demo, as it mathematically guarantees we only flag valid credit cards. Manifest V3 Limitations: Adapting to the new service worker lifecycle in MV3 while maintaining real-time WebSocket connections to the dashboard required careful state management. Accomplishments: We are incredibly proud of the synchronous paste-blocking mechanism. It works flawlessly on complex, dynamically injected React inputs (like ChatGPT's textarea) with zero latency. 🧠

### What we learned

We deep-dived into Chrome Extension Manifest V3 architecture, capture-phase event delegation, and designing zero-trust data pipelines where the backend is treated as an untrusted entity that only receives sanitized metadata.

## README (from the GitHub repository)

# 🛡️ ShadowGuard AI
### 🎥 📺 [Watch the Official Demo Video on YouTube!](https://youtu.be/bPYgBfl567s?si=HbUrzP7yXUf36nUz)
**Your AI Security Bodyguard.**

ShadowGuard AI is a Chrome extension that detects sensitive data (passwords, API keys, SSNs, credit cards) the instant you type or paste it into any AI chat tool, and blocks it before it's sent **entirely on-device, zero data ever leaves the browser for detection.**

## 🌟 Features

### Phase 1: 100% Local Detection Engine
- **Zero-Trust Architecture:** All PII/secret detection runs via regex/heuristics directly in the browser content script.
- **Comprehensive Pattern Matching:** Detects AWS keys, GitHub tokens, OpenAI/Anthropic API keys, JWTs, Credit Cards (with Luhn validation), US SSNs, and password contexts.
- **Synchronous Paste Blocking:** Intercepts paste events in the capture phase, preventing the secret from ever reaching the DOM.
- **Visual Feedback:** Instant red overlay warning on the input field.

### Phase 2: Backend & Dashboard
- **FastAPI Backend:** Receives masked detection metadata via WebSocket for a live threat feed.
- **Extension Risk Scanner:** Flags dangerous permission combinations in your installed Chrome extensions.
- **React Dashboard:** Real-time UI showing live threats, extension risks, and historical charts.

## 🚀 Quick Start

### 1. Start Backend & Dashboard
```bash
docker compose up --build -d
```
- Backend: `http://localhost:8000`
- Dashboard: `http://localhost:3000`

### 2. Build & Load the Chrome Extension
```bash
cd extension
npm install
npm run build
```
**Load into Chrome:**
1. Go to `chrome://extensions/`.
2. Enable **Developer mode**.
3. Click **Load unpacked** and select the `extension/dist` folder.

## 🎤 Demo Script
1. Open `http://localhost:3000` (Dashboard).
2. Open the ShadowGuard popup on `claude.ai` (See 🟢 Recognized AI).
3. Paste a fake AWS key (`AKIAIOSFODNN7EXAMPLE`) into the chat.
4. Watch the paste get blocked instantly with a red overlay.
5. Check the Dashboard to see the live WebSocket alert!

## 🛠️ Tech Stack
- **Extension:** React, TypeScript, Vite, Manifest V3
- **Backend:** Python, FastAPI, SQLAlchemy, SQLite
- **Dashboard:** React, Recharts, Nginx
- **DevOps:** Docker, Docker Compose


## Detected evidence (automated analysis)

Indexed codebase: 4 recognized source files, 33 KB.
- Python (language) — detected in the code

## Codebase structure (from repository index)

### Files (7 of 7)

```
.env
.github/ISSUE_TEMPLATE/bug_report.md
.gitignore
docker-compose.yml
LICENSE
README.md
setup.py
```

### Dependencies

No dependency index available.

### Recent commits (newest first)

- Update README with project details and instructions
- Update README.md with demo video link and formatting
- Add MIT License to the project
- Update issue templates
- Add files via upload
- Revise README for ShadowGuard AI project
- Initial commit

## Key source files (fetched from GitHub, selected and truncated for size)

### .github/ISSUE_TEMPLATE/bug_report.md

```markdown
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''

---

**Describe the bug**
A clear and concise description of what the bug is.

**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

**Expected behavior**
A clear and concise description of what you expected to happen.

**Screenshots**
If applicable, add screenshots to help explain your problem.

**Desktop (please complete the following information):**
 - OS: [e.g. iOS]
 - Browser [e.g. chrome, safari]
 - Version [e.g. 22]

**Smartphone (please complete the following information):**
 - Device: [e.g. iPhone6]
 - OS: [e.g. iOS8.1]
 - Browser [e.g. stock browser, safari]
 - Version [e.g. 22]

**Additional context**
Add any other context about the problem here.

```

### docker-compose.yml

```yaml
version: '3.8'
services:
  backend:
    build: {context: ., dockerfile: backend/Dockerfile}
    ports: ["8000:8000"]
    volumes: ["./backend:/app/backend", "backend_data:/app/data"]
  dashboard:
    build: {context: ., dockerfile: dashboard/Dockerfile}
    ports: ["3000:80"]
    depends_on: [backend]
volumes:
  backend_data:

```

### setup.py

```python
# -*- coding: utf-8 -*-
import os
import subprocess
import sys

def write_file(path, content):
    dir_name = os.path.dirname(path)
    if dir_name:
        os.makedirs(dir_name, exist_ok=True)
    # Force UTF-8 to prevent Windows encoding issues
    with open(path, 'w', encoding='utf-8') as f:
        f.write(content)

def main():
    print(r"""
  ____  _                   ____ _                 _ _____  
 / ___| | __ _ _ __   __ _/ ___| | __ _ _ __   __| |___ \ 
 \___ \| |/ _` | '_ \ / _` \___ \ | |/ _` | '_ \ / _` | __) |
  ___) | | (_| | | | | (_| |___) | | (_| | | | | (_| | __/ 
 |____/|_|\__,_|_| |_|\__, |____/|_|\__,_|_| |_|\__,_|_____|
                      |___/                                 
        [ Your Local AI Security Bodyguard ]
                      by: s3x0s
                 First Version (1.0.0)
    """)
    
    print("🚀 Initializing ShadowGuard AI Project (100% Local, No API Required)...")
    print("="*60)

    # 1. Root Files
    write_file('.gitignore', "node_modules/\nextension/dist/\ndashboard/dist/\n__pycache__/\n*.pyc\nbackend/data/*.db\n.env\n.DS_Store\n")

    write_file('README.md', """# 🛡️ ShadowGuard AI\n\n**Your AI Security Bodyguard.**\n\nShadowGuard AI is a Chrome extension that detects sensitive data (passwords, API keys, SSNs, credit cards) the instant you type or paste it into any AI chat tool, and blocks it before it's sent — **entirely on-device, zero data ever leaves the browser for detection.**\n\n## 🌟 Features\n\n### Phase 1: 100% Local Detection Engine\n- **Zero-Trust Architecture:** All PII/secret detection runs via regex/heuristics directly in the browser content script.\n- **Comprehensive Pattern Matching:** Detects AWS keys, GitHub tokens, OpenAI/Anthropic API keys, JWTs, Credit Cards (with Luhn validation), US SSNs, and password contexts.\n- **Synchronous Paste Blocking:** Intercepts paste events in the capture phase, preventing the secret from ever reaching the DOM.\n- **Visual Feedback:** Instant red overlay warning on the input field.\n\n### Phase 2: Backend & Dashboard\n- **FastAPI Backend:** Receives masked detection metadata via WebSocket for a live threat feed.\n- **Extension Risk Scanner:** Flags dangerous permission combinations in your installed Chrome extensions.\n- **React Dashboard:** Real-time UI showing live threats, extension risks, and historical charts.\n\n## 🚀 Quick Start\n\n### 1. Start Backend & Dashboard\n```bash\ndocker compose up --build -d\n```\n- Backend: `http://localhost:8000`\n- Dashboard: `http://localhost:3000`\n\n### 2. Build & Load the Chrome Extension\n```bash\ncd extension\nnpm install\nnpm run build\n```\n**Load into Chrome:**\n1. Go to `chrome://extensions/`.\n2. Enable **Developer mode**.\n3. Click **Load unpacked** and select the `extension/dist` folder.\n\n## 🎤 Demo Script\n1. Open `http://localhost:3000` (Dashboard).\n2. Open the ShadowGuard popup on `claude.ai` (See 🟢 Recognized AI).\n3. Paste a fake AWS key (`AKIAIOSFODNN7EXAMPLE`) into the chat.\n4. Watch the paste get blocked instantly with a red overlay.\n5. Check the Dashboard to see the live WebSocket alert!\n\n## 🛠️ Tech Stack\n- **Extension:** React, TypeScript, Vite, Manifest V3\n- **Backend:** Python, FastAPI, SQLAlchemy, SQLite\n- **Dashboard:** React, Recharts, Nginx\n- **DevOps:** Docker, Docker Compose\n""")

    write_file('docker-compose.yml', """version: '3.8'\nservices:\n  backend:\n    build: {context: ., dockerfile: backend/Dockerfile}\n    ports: ["8000:8000"]\n    volumes: ["./backend:/app/backend", "backend_data:/app/data"]\n  dashboard:\n    build: {context: ., dockerfile: dashboard/Dockerfile}\n    ports: ["3000:80"]\n    depends_on: [backend]\nvolumes:\n  backend_data:\n""")

    # 2. Backend Files
    write_file('backend/Dockerfile', """FROM python:3.11-slim\nWORKDIR /app\nCOPY backend/requirements.txt .\nRUN pip install --no-cache-dir -r requirements.txt\nCOPY backend/ /app/backend/\nRUN touch /app/backend/__init__.py /app/backend/routers/__init__.py\nRUN mkdir -p /app/data\nCMD ["uvicorn", "backend.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]\n""")
    write_file('backend/requirements.txt', "fastapi==0.111.0\nuvicorn==0.30.1\nsqlalchemy==2.0.30\npydantic==2.7.1\n")
    write_file('backend/main.py', """from fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom contextlib import asynccontextmanager\nfrom .database import engine, Base\nfrom .routers import alerts, extensions\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    Base.metadata.create_all(bind=engine)\n    yield\n\napp = FastAPI(lifespan=lifespan)\napp.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])\napp.include_router(alerts.router, prefix="/api")\napp.include_router(extensions.router, prefix="/api")\n\n@app.get("/")\ndef read_root():\n    return {"status": "ShadowGuard Backend Running"}\n""")
    write_file('backend/database.py', """from sqlalchemy import create_engine\nfrom sqlalchemy.orm import declarative_base, sessionmaker\nSQLALCHEMY_DATABASE_URL = "sqlite:////app/data/shadowguard.db"\nengine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})\nSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)\nBase = declarative_base()\n""")
    write_file('backend/models.py', """from sqlalchemy import Column, Integer, String, Float, DateTime\nfrom sqlalchemy.sql import func\nfrom .database import Base\n\nclass Detection(Base):\n    __tablename__ = "detections"\n    id = Column(Integer, primary_key=True, index=True)\n    type = Column(String, index=True)\n    masked_value = Column(String)\n    risk_score = Column(Float)\n    source_url = Column(String)\n    timestamp = Column(DateTime(timezone=True), server_default=func.now())\n\nclass ExtensionRisk(Base):\n    __tablename__ = "extension_risks"\n    id = Column(Integer, primary_key=True, index=True)\n    extension_id = Column(St
[truncated — 24011 more characters]
```