diff --git a/.env.example b/.env.example index fc3c8d8..bcbfd93 100644 --- a/.env.example +++ b/.env.example @@ -3,6 +3,8 @@ DISCORD_TOKEN=your_discord_bot_token DISCORD_CLIENT_ID=your_discord_application_client_id # Optional in development; if set, slash commands register instantly for this guild DISCORD_GUILD_ID=your_test_guild_id +# Command registration scope: global (DM + server), guild (server-only), or both +DISCORD_COMMAND_SCOPE=global # Gemini GEMINI_API_KEY=your_gemini_api_key diff --git a/README.md b/README.md index f993bf1..c87d298 100644 --- a/README.md +++ b/README.md @@ -1,160 +1,153 @@ -# CyberAI Bot +![CyberCortex - Ethical Cybersecurity Discord Bot](./assets/logo.png) + +# CyberCortex - Ethical Offensive Security Learning Assistant + +![Node.js](https://img.shields.io/badge/node-20%2B-green) +![License](https://img.shields.io/badge/license-MIT-blue) +![Status](https://img.shields.io/badge/status-active-success) +![Security](https://img.shields.io/badge/design-secure--by--default-red) +![Top Language](https://img.shields.io/github/languages/top/krishnaborude/CyberCortex?color=yellow) +![Repo Views](https://komarev.com/ghpvc/?username=krishnaborude&repo=CyberCortex&label=repo%20views&color=0e75b6&style=flat) + +CyberCortex is a Discord bot that helps cybersecurity learners build structured, certification-aligned practice workflows while enforcing authorized-use boundaries. + +## Abstract +CyberCortex combines practical learning guidance, search-grounded recommendations, and safety-aware AI orchestration for offensive and defensive security education in authorized environments. + +## Why This Matters +Many cybersecurity learners struggle with: +- Structuring their study path for certifications +- Knowing which labs to practice and in what order +- Understanding full attack-chain methodology +- Translating practice into professional reporting habits +- Staying within ethical and authorized boundaries + +CyberCortex addresses these challenges by combining structured learning workflows with AI-driven personalization and safety enforcement. + +## Key Differentiators +- Structured progression workflows (`/studyplan`, `/roadmap`) instead of one-off generic advice +- Scope-aware red-team guidance with explicit authorization context (`/redteam`) +- Certification-aligned weekly plans with exam-readiness and alignment notes +- Search-grounded labs/resources/news with validated links, not hallucinated URLs +- Discord-safe response chunking that preserves formatting and readability +- Defensive awareness integrated into offensive-learning outputs + +## What You Can Do +| Command | Value | +|---|---| +| `/studyplan` | Build certification-focused weekly prep plans | +| `/roadmap` | Generate phased learning roadmaps for a target role/goal | +| `/redteam` | Get authorized-scope red-team methodology guidance | +| `/labs` | Find relevant lab platforms and challenge paths | +| `/resource` | Curate useful articles, blogs, repos, books, and walkthroughs | +| `/news` | Track cybersecurity developments with practical context | +| `/quiz` | Practice with structured MCQ sets | +| `/explain` | Break down security concepts into practical learning chunks | +| `/tools` | Learn safe starter tooling and common setup pitfalls | + +## Documentation +- [Architecture](docs/ARCHITECTURE.md) +- [Command Specification](docs/COMMAND_SPEC.md) + +## Example Output (Study Plan Snippet) +```text +Week 4 - Active Directory Fundamentals +Focus: Enumeration and attack-path mapping +Deliverable: AD topology report with identified escalation paths -CyberAI is a production-focused Discord bot that uses Gemini to provide **ethical cybersecurity learning assistance** through slash commands. +Certification Alignment: +This mirrors enterprise engagement flow expected in practical certifications. +``` -## 1) Architecture +## Responsible AI and Safety +- Input validation and prompt-injection checks before model generation +- Explicit scope gating for sensitive red-team style requests +- Rate limiting to reduce abuse and control cost +- Grounded selection for labs/resources/news (only links from fetched candidates) +- Safety-focused output rules that avoid weaponized instructions + +## Security Testing Performed +The current implementation and validation flow covers: +- Prompt injection simulation attempts +- Malicious scope bypass attempts for offensive commands +- Rate limit behavior and retry-window handling +- Oversized response chunk validation for Discord constraints +- Null-input, malformed-input, and unsafe-pattern handling + +## Known Limitations +- Prompt injection detection is primarily rule-based. +- Rate limiting is in-memory (Redis is better for horizontal scaling). +- No persistent chat memory by design (privacy-first behavior). +- Availability depends on external model and feed providers. + +## Architecture At a Glance +![High-level data flow: User -> Discord -> AI Service -> Safety Filter -> Response](./assets/image.png) -- **Discord Interface Layer**: `src/index.js` + `src/commands/*` handle slash interactions only. -- **AI Service Layer**: `src/services/geminiService.js` contains prompt orchestration and Gemini API calls. -- **Application Utilities**: `src/utils/*` provide input validation, prompt-injection checks, rate limiting, smart message chunking, and Discord reply helpers. -- **Command System**: `src/handlers/commandHandler.js` dynamically loads command modules. -- **Error Middleware**: `src/handlers/errorHandler.js` wraps command execution and sends safe user-facing failures. -- **Config Layer**: `src/config/env.js` validates environment variables at startup. +```text +Discord Slash Command + -> Command Handler + -> Input Guard (sanitize + validate + injection checks) + -> Rate Limiter + -> Gemini Service (prompt orchestration + retries/fallback) + -> Response Formatter + Smart Split + -> Discord Reply/Follow-up +``` -This separation keeps AI logic independent of Discord transport, so it can be reused later in a SaaS API/backend. +For deeper technical details, see `docs/ARCHITECTURE.md`. -## 2) Folder Structure +## Quick Start +### Requirements +- Node.js 20+ +- Discord bot token and application client ID +- Gemini API key -```text -cyberai-bot/ - +-- src/ - +-- commands/ - +-- explain.js - +-- labs.js - +-- news.js - +-- quiz.js - +-- roadmap.js - +-- tools.js - +-- config/ - +-- env.js - +-- handlers/ - +-- commandHandler.js - +-- errorHandler.js - +-- services/ - +-- geminiService.js - +-- utils/ - +-- discordResponse.js - +-- inputGuard.js - +-- logger.js - +-- rateLimiter.js - +-- runAICommand.js - +-- smartSplitMessage.js - +-- index.js - +-- registerCommands.js - +-- .env.example - +-- package.json - +-- README.md +### Setup +1. Install dependencies: +```bash +npm install +``` +2. Configure environment variables in `.env`. +3. Register slash commands: +```bash +npm run register +``` +4. Start the bot: +```bash +npm start ``` -## 3) Slash Commands - -- `/roadmap` -- `/explain` -- `/tools` -- `/labs` -- `/quiz` -- `/news` - -## 4) Security Controls - -- Input sanitization and validation (`src/utils/inputGuard.js`) -- Basic prompt injection pattern blocking -- In-memory per-user rate limiting (`src/utils/rateLimiter.js`) -- Safe API error handling and masked internal failures -- Secrets only via environment variables (`.env`, never commit keys) -- Ethical-only system prompt constraints in AI service - -## 5) Smart Message Splitting - -`src/utils/smartSplitMessage.js` exports: - -- `smartSplitMessage(text)` - -Behavior: -- If output is `> 1900` chars, split by double newline first. -- If still too long, split by sentence. -- Protect fenced code blocks and avoid splitting inside them. -- Multi-part responses add page headers like `?? CyberAI Response (1/3)`. -- Hard cap ensures Discord-compatible chunks (`<= 2000`). - -## 6) Installation - -1. Install Node.js LTS (Node 20+). -2. Clone the project and open folder. -3. Install dependencies: - ```bash - npm install - ``` -4. Create `.env` from `.env.example` and fill values. -5. Register slash commands: - ```bash - npm run register - ``` -6. Start bot: - ```bash - npm start - ``` - -For local development: - +Development mode: ```bash npm run dev ``` -## 7) Environment Variables - -```env -DISCORD_TOKEN= -DISCORD_CLIENT_ID= -DISCORD_GUILD_ID= -GEMINI_API_KEY= -GEMINI_MODEL=gemini-2.5-flash -GEMINI_FALLBACK_MODELS=gemini-flash-latest,gemini-2.0-flash -NODE_ENV=development -RATE_LIMIT_WINDOW_MS=60000 -RATE_LIMIT_MAX_REQUESTS=6 -MAX_PROMPT_CHARS=1200 -``` +## Environment Variables (Core) +| Variable | Required | Description | +|---|---|---| +| `DISCORD_TOKEN` | Yes | Discord bot token | +| `DISCORD_CLIENT_ID` | Yes | Discord application client ID | +| `DISCORD_GUILD_ID` | No | Guild-scoped command registration | +| `DISCORD_COMMAND_SCOPE` | No | `global` (default, DM + server), `guild` (server only), or `both` | +| `GEMINI_API_KEY` | Yes | Primary Gemini API key | +| `SERPER_API_KEY` | No | Search API key for `/labs` and `/resource` | + +Additional tuning vars are available in `src/config/env.js`. + +## Community Impact +CyberCortex is designed to help: +- New learners build structured offensive methodology +- Intermediate students prepare for practical certifications +- Community members run exam-style simulation workflows in labs +- Users learn responsibly within explicit authorized scope + +The goal is not automation, but disciplined security thinking. + +## Intended Use +CyberCortex is for authorized learning environments: +- Personal labs +- CTF platforms +- Internal approved simulation exercises + +It is not intended for unauthorized real-world exploitation guidance. -## 8) Deploy on VPS (24/7) - -### Ubuntu example with PM2 - -1. Install Node.js LTS and Git. -2. Copy project to server. -3. Install dependencies: - ```bash - npm ci --omit=dev - ``` -4. Create production `.env`. -5. Register commands once: - ```bash - npm run register - ``` -6. Install PM2 and run app: - ```bash - npm i -g pm2 - pm2 start src/index.js --name cyberai-bot - pm2 save - pm2 startup - ``` -7. Check logs: - ```bash - pm2 logs cyberai-bot - ``` - -### System hardening recommendations - -- Run bot as non-root user. -- Restrict firewall to SSH only if bot does not expose HTTP ports. -- Store `.env` with strict permissions (`chmod 600 .env`). -- Rotate Discord and Gemini keys periodically. -- Add external uptime monitoring (Uptime Kuma / Better Stack / Pingdom). - -## 9) Scaling Notes (10,000+ users) - -- Move rate limiting from memory to Redis for multi-instance deployments. -- Add queueing/backpressure for AI calls. -- Add command analytics and structured observability (e.g., OpenTelemetry). -- Externalize chat/session context to database if personalized history is added. -- Reuse `GeminiService` in an HTTP API service when migrating to SaaS architecture. \ No newline at end of file +CyberCortex demonstrates that AI can enhance cybersecurity education while maintaining safety, structure, and responsibility. It is built not as an exploit generator, but as a structured learning assistant for ethical practitioners. diff --git a/assets/image.png b/assets/image.png new file mode 100644 index 0000000..0a0272c Binary files /dev/null and b/assets/image.png differ diff --git a/assets/logo.png b/assets/logo.png new file mode 100644 index 0000000..bf98189 Binary files /dev/null and b/assets/logo.png differ diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..8064c63 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,81 @@ +# CyberCortex Architecture + +## Purpose +CyberCortex is built as a Discord-native cybersecurity learning assistant that balances three goals: +- Practical value for learners preparing in authorized environments +- Consistent structure across outputs (roadmaps, study plans, quizzes, red-team guidance) +- Safety controls for dual-use cybersecurity topics + +## System Context +```text +Discord User + -> Slash Command + -> Command Handler + -> Input Guard + Scope Validation + Rate Limiter + -> Gemini Service (prompt orchestration, retries, quality checks) + -> Formatter + Smart Splitter + -> Discord Reply / Follow-up +``` + +## Core Design Principles +- Safety-first request handling before model invocation +- Structured AI outputs instead of free-form responses +- Search-grounded links for labs, resources, and news +- Graceful degradation under provider/API failures +- Discord-friendly formatting and chunk delivery + +## Runtime Request Flow +1. User triggers a slash command. +2. Command module validates required options and normalizes input. +3. `inputGuard` sanitizes text and blocks unsafe prompt patterns. +4. `rateLimiter` enforces per-user request quotas. +5. Command routes to either: + - `runAICommand` + `geminiService` for generated content, or + - Search services (`labsSearchService`, `resourceSearchService`, `newsService`) for grounded content. +6. Output is formatted and split using `smartSplitMessage`. +7. Response is sent through Discord interaction reply/edit/follow-up APIs. + +## Component Map +| Layer | Responsibility | Key Files | +|---|---|---| +| Bot Entry | Startup, Discord client events, service wiring | `src/index.js` | +| Command Surface | Slash command definitions and per-command execution | `src/commands/*` | +| Command Dispatch | Dynamic command loading and routing | `src/handlers/commandHandler.js` | +| Input and Abuse Controls | Sanitization, prompt-injection checks, rate limiting | `src/utils/inputGuard.js`, `src/utils/rateLimiter.js` | +| AI Orchestration | Prompt construction, model fallback, retries, quality validation | `src/services/geminiService.js`, `src/services/prompts/*` | +| Grounded Search | Candidate retrieval for labs/resources/news | `src/services/labsSearchService.js`, `src/services/resourceSearchService.js`, `src/services/newsService.js` | +| Output Delivery | Markdown normalization, chunk-safe Discord delivery | `src/utils/formatResponse.js`, `src/utils/smartSplitMessage.js`, `src/utils/discordResponse.js` | +| Error Handling | User-safe failure responses and logging | `src/handlers/errorHandler.js`, `src/utils/logger.js` | +| Configuration | Environment loading and validation | `src/config/env.js` | + +## Safety and Governance Controls +- Input sanitation and prompt-injection pattern blocking +- Authorized-scope checks for sensitive red-team style requests +- Guardrails in prompt templates to avoid weaponized output +- Grounding constraints so generated links must match fetched candidates +- Defensive framing for dual-use topics + +## Reliability Model +- Multi-key API support and model fallback candidates +- Exponential backoff retries for transient provider errors +- Quality validation + refinement pass for structured commands +- Response length/chunk management for Discord limits + +## Extensibility +CyberCortex is modular by command and service. New features typically require: +1. Add a command file under `src/commands`. +2. Add a prompt builder under `src/services/prompts` (if AI-generated). +3. Extend `geminiService` quality/validation rules (if structured output). +4. Register command and update docs. + +## Current Tradeoffs +- Rate limiting is in-memory (single-process scope) +- Prompt-injection detection is rule-based +- External dependency risk from model/search/feed providers +- No persistent memory by design (privacy-first) + +## Planned Improvements +- Redis-backed distributed rate limiting +- Deeper policy-driven prompt risk scoring +- Optional analytics for command usage and quality outcomes +- Expanded integration tests for command output contracts diff --git a/docs/COMMAND_SPEC.md b/docs/COMMAND_SPEC.md new file mode 100644 index 0000000..12d04f7 --- /dev/null +++ b/docs/COMMAND_SPEC.md @@ -0,0 +1,117 @@ +# Command Input and Output Contracts + +## Roadmap Command +`/roadmap` inputs: +- Required: `goal` +- Optional: `weeks` + +Output format: +1. ` Roadmap` title +2. `Overview` section with duration, pace, prerequisites, lab setup +3. Phase sections (`Phase N: ...`) +4. Week sections (`Week N: ...`) for full duration coverage +5. Weekly bullets: `Learn`, `Do`, `Deliverable` + +## Study Plan Command +`/studyplan` requires all of the following inputs: +- `certification` +- `experience_level` +- `hours_per_week` +- `duration_weeks` +- `focus_area` + +Output format: +1. Overview Summary +2. Weekly Breakdown +3. Skills Progression Milestones +4. Recommended Lab Types +5. Practice Strategy +6. Review & Reinforcement Plan +7. Final Exam Readiness Checklist +8. Certification Alignment Notes + +## Explain Command +`/explain` requires: +- `concept` + +Output format: +1. Chunk 1/5: Concept Summary +2. Chunk 2/5 +3. Chunk 3/5: Discovery Commands +4. Chunk 4/5: Enumeration Commands +5. Chunk 5/5: Validation and Safety Notes + +## Tools Command +`/tools` requires: +- `focus` + +Output format: +1. Tool categories +2. Best starter tools per category +3. Safe basic commands with what each command does +4. Common setup mistakes +5. Lab-only safety reminders +6. Next learning steps + +## Labs Command +`/labs` inputs: +- Required: `query` +- Optional: `platform` + +Output format: +1. User input echo +2. Numbered lab recommendations +3. Per lab: name, platform, difficulty, link, short description + +## Quiz Command +`/quiz` inputs: +- Optional: `topic` (default: general cybersecurity fundamentals) +- Optional: `questions` (default: 5, range: 3-10) + +Output format: +1. Quiz title heading +2. `Questions` section +3. Each question with exactly four options: `A)`, `B)`, `C)`, `D)` +4. `Answer Key` section using `Qn: