Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
1e4b1de
feat(gemini): support multiple API keys and improve response formatting
krishnaborude Feb 17, 2026
c48a6e8
feat: update Gemini model to 2.5-flash and modularize prompt builders
krishnaborude Feb 18, 2026
2191458
Merge branch 'main' of https://github.com/krishnaborude/CyberAI into …
krishnaborude Feb 18, 2026
aae70f0
Update README with OffSec-style documentation and diagrams
krishnaborude Feb 19, 2026
d562289
Update README with OffSec-style documentation and diagrams
krishnaborude Feb 19, 2026
37ffca5
feat: add studyplan command for certification-focused learning plans
krishnaborude Feb 20, 2026
1ddb626
Merge branch 'development' of https://github.com/krishnaborude/CyberA…
krishnaborude Feb 20, 2026
802ff0e
refactor: remove duplicate heading instructions from prompt
krishnaborude Feb 20, 2026
4ae8825
feat(studyplan): add experience scaling and intensity guidance to stu…
krishnaborude Feb 20, 2026
799b144
feat(explain): enhance command with structured output and autocomplete
krishnaborude Feb 22, 2026
bc11bac
feat(quiz): enhance quiz generation with question count inference and…
krishnaborude Feb 22, 2026
1495c7e
docs: add architecture and command specification documentation
krishnaborude Feb 22, 2026
3e0b2a1
docs: move architecture and command spec to docs directory
krishnaborude Feb 22, 2026
dcd586b
docs: add badges to README for quick project overview
krishnaborude Feb 22, 2026
65df9ed
chore: update and remove logo assets
krishnaborude Feb 23, 2026
5b40dbe
feat: rename bot from CyberAI to CyberCortex and improve explain command
krishnaborude Feb 23, 2026
f0dc91e
chore: update logo image file
krishnaborude Feb 23, 2026
7fe10f9
feat: add help command to display available commands and usage guidance
krishnaborude Feb 23, 2026
7e527c5
refactor(discord.js): migrate ephemeral flag to MessageFlags enum
krishnaborude Feb 23, 2026
fc3a1a4
feat(command-registration): add configurable command scope
krishnaborude Feb 24, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
287 changes: 140 additions & 147 deletions README.md
Original file line number Diff line number Diff line change
@@ -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.
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.
Binary file added assets/image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
81 changes: 81 additions & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
@@ -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
Loading