first commit

This commit is contained in:
khuongnguyen committed 2026-11-28 20:37:00 +07:00
commit 41d9e9e8eb
21 files changed
+3538

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
# Discord Bot Token (from Discord Developer Portal > Bot > Reset Token)
DISCORD_TOKEN=your_bot_token_here
# Discord Client / Application ID (from General Information)
DISCORD_CLIENT_ID=your_client_id_here
# Target Discord Server (Guild) ID for fast slash command deployment & testing
DISCORD_GUILD_ID=your_guild_id_here
# Discord Role ID permitted to execute sensitive commands like `/vps connect`
DEVOPS_ROLE_ID=your_devops_role_id_here
+12
View File
@@ -0,0 +1,12 @@
node_modules/
dist/
.env
.env.local
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
.DS_Store
coverage/
.vitest/
+395
View File
@@ -0,0 +1,395 @@
# 🖥️ Discord Bot – VPS Inventory Assistant
Discord Bot quản lý và tra cứu thông tin hạ tầng VPS tập trung dành cho các đội ngũ kỹ thuật, DevOps và quản trị hệ thống. Ứng dụng được xây dựng theo kiến trúc phân lớp sạch (Clean Layered Architecture), bảo mật cao, và tuân thủ các tiêu chuẩn tương tác native của Discord (Slash Commands, Embeds, RBAC).
---
## 📌 Mục Lục
1. [Tổng Quan Dự Án (Project Overview)](#1-tổng-quan-dự-án)
2. [Ngăn Xếp Công Nghệ (Technology Stack)](#2-ngăn-xếp-công-nghệ)
3. [Kiến Trúc Ứng Dụng (Architecture)](#3-kiến-trúc-ứng-dụng)
4. [Dữ Liệu Khởi Tạo (Seed Data)](#4-dữ-liệu-khởi-tạo)
5. [Cấu Hình Discord Application & Bot (Step-by-Step)](#5-cấu-hình-discord-application--bot)
6. [Cài Đặt Và Khởi Chạy Local (Local Setup)](#6-cài-đặt-và-khởi-chạy-local)
7. [Tài Liệu Chi Tiết 6 Lệnh Slash Commands](#7-tài-liệu-chi-tiết-6-lệnh-slash-commands)
8. [Kiến Trúc Bảo Mật & RBAC (Security Design)](#8-kiến-trúc-bảo-mật--rbac)
9. [Kịch Bản Trình Diễn Workshop (Demo Scenarios)](#9-kịch-bản-trình-diễn-workshop)
10. [Nợ Kỹ Thuật & Hướng Phát Triển (Technical Debt & Roadmap)](#10-nợ-kỹ-thuật--hướng-phát-triển)
---
## 1. Tổng Quan Dự Án
Trong các nhóm phát triển và vận hành hệ thống, thông tin về máy chủ VPS (cấu hình CPU, RAM, Disk, Nhà cung cấp, Môi trường triển khai, lệnh kết nối) thường bị phân tán trong các tài liệu nội bộ hoặc bảng tính rời rạc.
**Discord Bot – VPS Inventory Assistant** ra đời nhằm:
- Cho phép thành viên trong team tra cứu tức thì thông tin máy chủ trực tiếp ngay trong kênh Discord mà không cần đăng nhập vào dashboard của từng Cloud Provider.
- Cung cấp số liệu thống kê tổng hợp tài nguyên phần cứng (Tổng số vCPU, Tổng dung lượng RAM, Tổng dung lượng ổ cứng).
- Bảo mật thông tin nhạy cảm: Chỉ các thành viên có vai trò **DevOps** hoặc quyền **Administrator** mới có thể tạo lệnh kết nối SSH; các thông tin nhạy cảm được gửi dưới dạng tin nhắn riêng tư (**Ephemeral Message**).
---
## 2. Ngăn Xếp Công Nghệ
| Công nghệ | Vai trò & Lý do lựa chọn |
|---|---|
| **Node.js LTS (v22+)** | Môi trường runtime tiêu chuẩn, ổn định, hiệu năng I/O bất đồng bộ cao phù hợp cho WebSocket Gateway của Discord. |
| **TypeScript (Strict Mode)** | Đảm bảo tính an toàn kiểu dữ liệu (Type Safety), tự động bắt lỗi từ thời điểm biên dịch, tự sinh tài liệu qua interfaces và types. |
| **discord.js v14** | Thư viện chính thức, tương thích toàn diện với Discord API v10, hỗ trợ SlashCommandBuilder, EmbedBuilder và REST API mới nhất. |
| **JSON Storage** | Nguồn dữ liệu duy nhất (Single Source of Truth) cho MVP: gọn nhẹ, không cần dựng cơ sở dữ liệu cồng kềnh, dễ dàng audit qua git. |
| **Zod** | Xác thực Schema dữ liệu runtime cho file `vps.json` và các biến môi trường, bảo vệ hệ thống trước dữ liệu bị hỏng hoặc cấu hình thiếu. |
| **dotenv** | Tải và quản lý biến môi trường an toàn từ file `.env`. |
| **pnpm** | Trình quản lý gói nhanh, tiết kiệm dung lượng đĩa nhờ content-addressable storage. |
| **tsx** | Trình thực thi TypeScript tức thì (Zero-config TS execution) cho môi trường dev và chạy script độc lập. |
| **Vitest** | Khung kiểm thử tự động thế hệ mới, tốc độ thực thi cực nhanh, native ESM/TypeScript, không phụ thuộc kết nối Discord live khi chạy unit tests. |
*Lưu ý:* Dự án là một native Discord Bot, không sử dụng các framework web/frontend (React, Next.js, Express, Tailwind CSS, Prisma,...) theo đúng yêu cầu đề bài.
---
## 3. Kiến Trúc Ứng Dụng
Dự án áp dụng mô hình phân lớp rõ ràng (Layered Architecture):
```text
Discord User (Discord Client)
│
▼ (Slash Command Interaction)
Command Handler (src/commands/vps.command.ts)
- Phân tích tương tác Discord Slash Command
- Kiểm tra quyền hạn RBAC (Viewer vs DevOps/Admin)
- Xác thực tham số đầu vào (Input Validation)
│
▼
VPS Service (src/services/vps.service.ts)
- Nghiệp vụ tìm kiếm, lọc (Filter), tính toán thống kê (Stats)
- Không phụ thuộc vào Discord API
│
▼
VPS Repository (src/repositories/vps.repository.ts)
- Đọc file JSON từ đĩa, xác thực runtime schema với Zod
- Cung cấp các phương thức truy vấn dữ liệu gốc
│
▼
JSON Data Storage (data/vps.json)
```
### Cấu trúc thư mục mã nguồn:
```text
prj-discordcheckvps/
├── src/
│ ├── index.ts # Điểm khởi chạy Bot, kết nối Gateway, xử lý sự kiện & graceful shutdown
│ ├── deploy-commands.ts # Script đăng ký Slash Commands với Discord REST API
│ │
│ ├── commands/
│ │ └── vps.command.ts # Định nghĩa SlashCommandBuilder & bộ điều phối 6 subcommands
│ │
│ ├── services/
│ │ └── vps.service.ts # Logic nghiệp vụ xử lý danh sách, tìm kiếm, lọc, thống kê
│ │
│ ├── repositories/
│ │ └── vps.repository.ts # Tầng truy xuất file JSON, nạp dữ liệu và kiểm tra runtime schema
│ │
│ ├── types/
│ │ └── vps.ts # Định nghĩa interface, enum và Zod schema cho VPS
│ │
│ ├── utils/
│ │ ├── embeds.ts # Định dạng và chuẩn hóa Discord Embeds (màu sắc, layout, icons)
│ │ ├── permissions.ts # Logic kiểm tra quyền RBAC (DevOps role, Discord Administrator)
│ │ └── ssh.ts # Xây dựng câu lệnh SSH an toàn, ngăn chặn Command Injection
│ │
│ └── config/
│ └── env.ts # Nạp và xác thực biến môi trường với Zod
│
├── data/
│ └── vps.json # Nguồn dữ liệu mẫu chuẩn của workshop
│
├── tests/
│ ├── vps.service.test.ts # Unit tests cho Repository và Service (tìm kiếm, lọc, thống kê)
│ ├── permissions.test.ts # Unit tests cho hệ thống kiểm tra phân quyền RBAC
│ └── ssh.test.ts # Unit tests cho kiểm tra tính hợp lệ và an toàn của lệnh SSH
│
├── .env.example # Mẫu cấu hình biến môi trường an toàn
├── .gitignore # Loại trừ các file nhạy cảm và thư mục build
├── package.json # Định nghĩa scripts và dependencies
├── pnpm-lock.yaml # Khóa phiên bản dependencies
├── tsconfig.json # Cấu hình TypeScript Strict Mode
└── README.md # Tài liệu hướng dẫn sử dụng và triển khai
```
---
## 4. Dữ Liệu Khởi Tạo (Seed Data)
Dữ liệu được lưu trữ tại file [data/vps.json](file:///home/imkhuong/workspace/prj-discordcheckvps/data/vps.json) chứa chính xác 3 bản ghi máy chủ mẫu của workshop:
| ID | Name | Provider | Region | CPU | RAM | Disk | Environment |
|---|---|---|---|---|---|---|---|
| `vps-001` | **shop-prod-01** | Vultr | Singapore | 4 vCPU | 8 GB | 160 GB | Production |
| `vps-002` | **staging-01** | DigitalOcean | Singapore | 2 vCPU | 4 GB | 80 GB | Staging |
| `vps-003` | **db-prod-01** | Vultr | Singapore | 4 vCPU | 16 GB | 320 GB | Production |
> [!NOTE]
> Để đảm bảo an toàn tuyệt đối, hệ thống **không tự ý bịa đặt địa chỉ IP thực tế hay thông tin đăng nhập SSH** trong dữ liệu ban đầu. Các thuộc tính `ip`, `sshUser`, `sshPort` là tùy chọn (`optional`) và được cấu hình khi có nhu cầu kết nối.
---
## 5. Cấu Hình Discord Application & Bot
Để triển khai và chạy bot trên máy chủ Discord của bạn, hãy thực hiện theo 9 bước chi tiết dưới đây:
### Bước 1: Tạo Discord Application
1. Truy cập vào **[Discord Developer Portal](https://discord.com/developers/applications)**.
2. Đăng nhập bằng tài khoản Discord của bạn.
3. Nhấp vào nút **New Application** ở góc trên bên phải.
4. Đặt tên ứng dụng (ví dụ: `VPS-Inventory-Bot`) và đồng ý với Điều khoản dịch vụ, sau đó nhấn **Create**.
### Bước 2: Tạo và cấu hình Bot User
1. Tại menu bên trái, chọn mục **Bot**.
2. Nhấn **Add Bot** (nếu chưa được tạo tự động).
3. Đặt Username cho bot (ví dụ: `VPS Assistant`).
4. Tắt tùy chọn **Public Bot** nếu bạn chỉ muốn sử dụng nội bộ trong team của mình.
### Bước 3: Lấy Bot Token
1. Vẫn trong trang **Bot**, nhấp vào nút **Reset Token**.
2. Xác nhận bảo mật (nếu Discord yêu cầu nhập mã 2FA).
3. Sao chép chuỗi mã Token vừa hiển thị và lưu cẩn thận (đây chính là giá trị cho biến `DISCORD_TOKEN`).
> [!CAUTION]
> Tuyệt đối không chia sẻ Token này hoặc commit lên GitHub.
### Bước 4: Lấy Client ID (Application ID)
1. Tại menu bên trái, chọn mục **General Information**.
2. Tìm trường **Application ID**, nhấp nút **Copy** để lấy ID (đây chính là giá trị cho biến `DISCORD_CLIENT_ID`).
### Bước 5: Lấy Server (Guild) ID
1. Mở ứng dụng Discord trên máy tính.
2. Vào **User Settings (Cài đặt người dùng)** -> **Advanced (Nâng cao)** -> Bật **Developer Mode (Chế độ nhà phát triển)**.
3. Nhấp chuột phải vào biểu tượng máy chủ (Server) Discord thử nghiệm của bạn -> Chọn **Copy Server ID** (đây là giá trị cho biến `DISCORD_GUILD_ID`).
### Bước 6: Mời Bot vào Server với đúng quyền hạn (OAuth2 URL)
1. Trong Developer Portal, vào mục **OAuth2** -> **URL Generator**.
2. Trong phần **Scopes**, tích chọn:
- `bot`
- `applications.commands` (bắt buộc để bot đăng ký Slash Commands).
3. Trong phần **Bot Permissions**, tích chọn các quyền tối thiểu:
- `Send Messages`
- `Embed Links`
- `Use Slash Commands`
4. Cuộn xuống dưới cùng, sao chép liên kết được tạo ra tại ô **Generated URL**.
5. Dán liên kết đó vào trình duyệt, chọn máy chủ thử nghiệm của bạn và nhấn **Authorize**.
### Bước 7: Tạo DevOps Role trên Server
1. Trong server Discord của bạn, vào **Server Settings** -> **Roles**.
2. Nhấp **Create Role**, đặt tên vai trò là `DevOps` (chọn màu sắc tùy ý).
3. Lưu thay đổi.
### Bước 8: Lấy Role ID của DevOps
1. Vẫn tại trang quản lý Roles, nhấp chuột phải vào role `DevOps` vừa tạo (hoặc nhấp vào dấu 3 chấm bên cạnh role).
2. Chọn **Copy Role ID** (đây là giá trị cho biến `DEVOPS_ROLE_ID`).
3. Gán role `DevOps` này cho tài khoản của bạn hoặc người cần thử nghiệm lệnh kết nối SSH.
---
## 6. Cài Đặt Và Khởi Chạy Local
### Yêu cầu tiên quyết:
- Đã cài đặt **Node.js** phiên bản v18+ hoặc v20+ / v22+ LTS.
- Đã cài đặt **pnpm**: `npm install -g pnpm`.
### Hướng dẫn từng bước:
```bash
# 1. Cài đặt các gói phụ thuộc
pnpm install
# 2. Tạo file cấu hình môi trường .env từ mẫu
cp .env.example .env
# Đối với Windows PowerShell:
# Copy-Item .env.example .env
# Đối với Windows CMD:
# copy .env.example .env
# 3. Mở file .env và điền đầy đủ các thông tin đã thu thập ở Bước 5:
# DISCORD_TOKEN=...
# DISCORD_CLIENT_ID=...
# DISCORD_GUILD_ID=...
# DEVOPS_ROLE_ID=...
# 4. Đăng ký Slash Commands với Discord Guild
pnpm deploy:commands
# 5. Khởi chạy Bot ở chế độ phát triển (auto-reload khi code thay đổi)
pnpm dev
```
### Các scripts hỗ trợ khác:
- `pnpm start`: Chạy Bot ở chế độ Production.
- `pnpm typecheck`: Kiểm tra tính toàn vẹn kiểu dữ liệu TypeScript (`tsc --noEmit`).
- `pnpm test`: Chạy toàn bộ 37 automated unit tests với Vitest.
---
## 7. Tài Liệu Chi Tiết 6 Lệnh Slash Commands
Bot sử dụng một lệnh cấp cao nhất duy nhất là `/vps` với 6 subcommands độc lập:
### 7.1 `/vps list`
- **Mục đích:** Hiển thị toàn bộ danh sách máy chủ trong kho dữ liệu.
- **Quyền hạn:** Mọi thành viên (Viewer).
- **Phản hồi:** Discord Embed màu Primary Blue liệt kê tên từng server, môi trường (Production/Staging/Dev), nhà cung cấp, vị trí và thông số tài nguyên (CPU/RAM/Disk).
### 7.2 `/vps info`
- **Cú pháp:** `/vps info name:<tên-vps>` (ví dụ: `/vps info name:shop-prod-01`)
- **Mục đích:** Hiển thị chi tiết cấu hình chuyên sâu của một máy chủ.
- **Đặc điểm:** Tìm kiếm không phân biệt chữ hoa chữ thường.
- **Chính sách hiển thị mạng:** Nếu server đã cấu hình IP:
- Thành viên có quyền DevOps/Admin: Nhìn thấy IP đầy đủ.
- Thành viên thường: IP được ẩn dưới nhãn bảo vệ `🔒 Protected (DevOps role required)`.
- Nếu chưa cấu hình IP: Hiển thị `Not configured`.
### 7.3 `/vps search`
- **Cú pháp:** `/vps search query:<từ-khóa>` (ví dụ: `/vps search query:prod`)
- **Mục đích:** Tìm kiếm máy chủ theo tên hoặc địa chỉ IP.
- **Đặc điểm:** Hỗ trợ tìm kiếm một phần (partial matching), tự động loại bỏ khoảng trắng thừa, không phân biệt hoa thường.
### 7.4 `/vps filter`
- **Cú pháp:**
- `/vps filter provider:Vultr`
- `/vps filter environment:Production`
- `/vps filter provider:Vultr environment:Production`
- **Mục đích:** Lọc máy chủ theo Nhà cung cấp và/hoặc Môi trường.
- **Đặc điểm:** Bắt buộc nhập ít nhất 1 tiêu chí; nếu nhập cả 2 tiêu chí, áp dụng logic **AND** đồng thời. Hỗ trợ dropdown chọn nhanh môi trường (`Production`, `Staging`, `Development`).
### 7.5 `/vps stats`
- **Mục đích:** Tổng hợp và tính toán động số liệu tài nguyên toàn bộ hạ tầng.
- **Kết quả tính toán với dữ liệu seed ban đầu:**
- Tổng số máy chủ: **3**
- Tổng vCPU: **10**
- Tổng RAM: **28 GB**
- Tổng ổ cứng: **560 GB**
- Phân bố theo Môi trường: Production (2), Staging (1)
- Phân bố theo Nhà cung cấp: Vultr (2), DigitalOcean (1)
### 7.6 `/vps connect`
- **Cú pháp:** `/vps connect name:<tên-vps>` (ví dụ: `/vps connect name:shop-prod-01`)
- **Mục đích:** Sinh câu lệnh kết nối SSH terminal cho kỹ sư DevOps.
- **Quy tắc an toàn tuyệt đối:**
- **Chỉ người dùng có role DevOps hoặc quyền Server Administrator mới được phép thực thi.**
- **Phản hồi luôn ở chế độ Ephemeral:** Chỉ người gọi lệnh mới nhìn thấy kết quả trong Discord; không bao giờ để lộ thông tin kết nối lên kênh chat công cộng.
- Bot **không bao giờ thực thi kết nối SSH** hay gửi lệnh ra ngoài môi trường server.
- Không chứa mật khẩu hay private key.
- Nếu VPS chưa cấu hình IP hoặc SSH User: Phản hồi thông báo cấu hình chưa hoàn tất.
---
## 8. Kiến Trúc Bảo Mật & RBAC
1. **Phân quyền Role-Based Access Control (RBAC):**
- Tầng command handler kiểm tra trực tiếp quyền hạn trên `interaction.member`.
- Chấp thuận nếu thành viên sở hữu quyền `Administrator` của server hoặc có Role ID trùng khớp với biến môi trường `DEVOPS_ROLE_ID`.
- Cơ chế từ chối an toàn (**Fail-secure**): Nếu thiếu cấu hình role trong `.env` và người dùng không phải là Admin, lệnh sẽ bị từ chối lập tức.
2. **Bảo vệ thông tin kết nối nhạy cảm:**
- Lệnh `/vps connect` luôn gửi phản hồi **Ephemeral**.
- Thông tin IP trong `/vps info` được che dấu đối với người dùng không có thẩm quyền.
3. **Phòng chống Command Injection khi tạo lệnh SSH:**
- Hàm `generateSSHCommand` kiểm tra chặt chẽ:
- `ip`: Phải là địa chỉ IPv4/IPv6 hợp lệ hoặc Hostname tuân thủ RFC 1123; nghiêm cấm các ký tự đặc biệt của shell (`;`, `&`, `|`, `` ` ``, `$`, khoảng trắng).
- `sshUser`: Chỉ cho phép ký tự chữ số, gạch dưới, gạch ngang (tối đa 32 ký tự).
- `sshPort`: Phải là số nguyên từ 1 đến 65535 (mặc định là 22).
4. **Bảo vệ biến môi trường & Token:**
- `.gitignore` ngăn ngừa triệt để việc commit file `.env`.
- File log của bot không bao giờ in giá trị `DISCORD_TOKEN` hay các thông số nhạy cảm.
---
## 9. Kịch Bản Trình Diễn Workshop (Demo Scenarios)
### Kịch bản 1: Kiểm tra danh sách tổng quan
- **Người thực hiện:** Thành viên bất kỳ.
- **Lệnh gõ:** `/vps list`
- **Kết quả hiển thị:** Embed hiển thị đầy đủ 3 máy chủ (`shop-prod-01`, `staging-01`, `db-prod-01`).
### Kịch bản 2: Tra cứu chi tiết một máy chủ
- **Người thực hiện:** Thành viên bất kỳ.
- **Lệnh gõ:** `/vps info name:shop-prod-01`
- **Kết quả hiển thị:** Embed hiển thị thông số: Vultr, Singapore, 4 vCPU, 8 GB RAM, 160 GB Disk, Production.
### Kịch bản 3: Tìm kiếm theo từ khóa
- **Người thực hiện:** Thành viên bất kỳ.
- **Lệnh gõ:** `/vps search query:prod`
- **Kết quả hiển thị:** Trả về 2 máy chủ: `shop-prod-01` và `db-prod-01`.
### Kịch bản 4: Lọc theo nhà cung cấp
- **Người thực hiện:** Thành viên bất kỳ.
- **Lệnh gõ:** `/vps filter provider:Vultr`
- **Kết quả hiển thị:** Trả về 2 máy chủ của nhà cung cấp Vultr.
- **Thử nghiệm mở rộng:** `/vps filter provider:Vultr environment:Production` -> Trả về 2 máy chủ.
### Kịch bản 5: Xem thống kê toàn bộ tài nguyên
- **Người thực hiện:** Thành viên bất kỳ.
- **Lệnh gõ:** `/vps stats`
- **Kết quả hiển thị:** Tổng 3 VPS, 10 vCPU, 28 GB RAM, 560 GB Disk; phân nhóm Vultr: 2, DigitalOcean: 1; Production: 2, Staging: 1.
### Kịch bản 6: Kiểm tra bảo mật SSH Connect & Phân quyền
- **Trường hợp 6A (Người dùng thường - không có quyền):**
- Gõ: `/vps connect name:shop-prod-01`
- Kết quả: Nhận thông báo lỗi Ephemeral từ chối quyền truy cập: *"Permission Denied: You must have the DevOps role or Server Administrator permissions to access SSH connection details."*
- **Trường hợp 6B (DevOps / Admin - Chưa cấu hình SSH):**
- Gõ: `/vps connect name:shop-prod-01`
- Kết quả: Nhận thông báo Ephemeral: *"SSH connection information has not been configured for this VPS."*
- **Trường hợp 6C (Trình diễn cấu hình mẫu an toàn - Demo Record):**
- Thêm một bản ghi demo vào `data/vps.json` sử dụng dải IP tài liệu tiêu chuẩn RFC 5737 (`203.0.113.10`):
```json
{
"id": "vps-demo",
"name": "demo-jump-01",
"provider": "Vultr",
"region": "Singapore",
"environment": "Development",
"cpu": 2,
"ramGB": 4,
"diskGB": 40,
"ip": "203.0.113.10",
"sshUser": "deploy",
"sshPort": 22
}
```
- Khi người dùng DevOps gõ `/vps connect name:demo-jump-01`:
- Bot trả về tin nhắn Ephemeral chứa đoạn lệnh terminal:
```bash
ssh -p 22 deploy@203.0.113.10
```
---
## 10. Nợ Kỹ Thuật & Hướng Phát Triển
Trong phạm vi MVP của workshop, một số tính năng đã được tinh gọn để tập trung vào kiến trúc sạch và độ tin cậy. Dưới đây là các điểm nợ kỹ thuật và lộ trình nâng cấp trong môi trường sản xuất:
1. **Lưu trữ dữ liệu (JSON → Database):**
- *Hiện tại:* Dùng file `vps.json` phù hợp cho quy mô nhỏ.
- *Tương lai:* Chuyển sang SQLite (đơn giản, nhúng) hoặc PostgreSQL kết hợp ORM (Drizzle/Prisma) để hỗ trợ đồng thời nhiều lượt ghi và khóa giao dịch.
2. **Đồng bộ tự động (Manual Inventory → Provider API Sync):**
- *Hiện tại:* Dữ liệu cấu hình thủ công.
- *Tương lai:* Tích hợp Webhook hoặc cron job gọi API trực tiếp của Vultr, DigitalOcean, AWS để tự động cập nhật trạng thái khi VPS được tạo mới hoặc hủy.
3. **Phân quyền nâng cao (Advanced RBAC):**
- *Hiện tại:* Một role DevOps duy nhất kết hợp Administrator.
- *Tương lai:* Hỗ trợ phân quyền theo môi trường (ví dụ: Developer được xem SSH server Staging/Dev, chỉ Lead DevOps mới xem được Production).
4. **Lệnh quản trị động (Dynamic Inventory Management):**
- *Hiện tại:* Sửa file JSON thủ công.
- *Tương lai:* Bổ sung các lệnh quản trị dành cho Admin: `/vps add`, `/vps edit`, `/vps delete`.
5. **Giám sát sức khỏe máy chủ (Health Monitoring & Heartbeat):**
- *Hiện tại:* Thông tin cấu hình tĩnh.
- *Tương lai:* Tích hợp kiểm tra Ping, Port check, hoặc truy vấn Prometheus/Uptime Kuma để hiển thị trạng thái máy chủ Online/Offline theo thời gian thực.
6. **Ghi nhật ký có cấu trúc (Structured Logging & Telemetry):**
- *Hiện tại:* Dùng `console.log` và `console.error`.
- *Tương lai:* Triển khai thư viện Pino/Winston, tích hợp đẩy log về Grafana Loki hoặc Datadog để giám sát audit log các lần gọi lệnh `/vps connect`.
7. **Đóng gói và triển khai tự động (Docker & CI/CD):**
- *Hiện tại:* Khởi chạy node thủ công qua terminal.
- *Tương lai:* Đóng gói `Dockerfile` nhiều giai đoạn (multi-stage build), triển khai với docker-compose hoặc Kubernetes kèm quy trình GitHub Actions tự động kiểm thử.
8. **Hỗ trợ đa máy chủ (Multi-guild Support):**
- *Hiện tại:* Triển khai guild-specific commands để đăng ký lệnh tức thì.
- *Tương lai:* Đăng ký Global Commands để bot hoạt động trên nhiều máy chủ Discord khác nhau của doanh nghiệp.
+39
View File
@@ -0,0 +1,39 @@
[
{
"id": "vps-001",
"name": "shop-prod-01",
"provider": "Vultr",
"region": "Singapore",
"environment": "Production",
"cpu": 4,
"ramGB": 8,
"diskGB": 160,
"ip": "203.0.113.10",
"sshUser": "deploy",
"sshPort": 22
},
{
"id": "vps-002",
"name": "staging-01",
"provider": "DigitalOcean",
"region": "Singapore",
"environment": "Staging",
"cpu": 2,
"ramGB": 4,
"diskGB": 80,
"ip": "198.51.100.20",
"sshUser": "ubuntu",
"sshPort": 2222
},
{
"id": "vps-003",
"name": "db-prod-01",
"provider": "Vultr",
"region": "Singapore",
"environment": "Production",
"cpu": 4,
"ramGB": 16,
"diskGB": 320,
"ip": "192.0.2.30"
}
]
+32
View File
@@ -0,0 +1,32 @@
{
"name": "prj-discordcheckvps",
"version": "1.0.0",
"description": "Discord Bot - VPS Inventory Assistant",
"type": "module",
"scripts": {
"dev": "tsx watch src/index.ts",
"start": "tsx src/index.ts",
"deploy:commands": "tsx src/deploy-commands.ts",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"keywords": [
"discord-bot",
"vps-inventory",
"discordjs",
"typescript"
],
"author": "",
"license": "ISC",
"dependencies": {
"discord.js": "^14.28.1",
"dotenv": "^18.0.10",
"zod": "^4.6.7"
},
"devDependencies": {
"@types/node": "^26.6.6",
"tsx": "^4.23.15",
"typescript": "^7.0.2",
"vitest": "^5.1.0"
}
}
+1571
View File
File diff suppressed because it is too large. Load diff
+2
View File
@@ -0,0 +1,2 @@
allowBuilds:
esbuild: true
+236
View File
@@ -0,0 +1,236 @@
import {
ChatInputCommandInteraction,
SlashCommandBuilder,
} from "discord.js";
import { VPSService } from "../services/vps.service.js";
import { VPSEnvironment } from "../types/vps.js";
import {
createErrorEmbed,
createSSHConnectEmbed,
createVPSFilterEmbed,
createVPSInfoEmbed,
createVPSListEmbed,
createVPSSearchEmbed,
createVPSStatsEmbed,
createWarningEmbed,
} from "../utils/embeds.js";
import { checkDevOpsAuthorization, isDevOpsOrAdmin } from "../utils/permissions.js";
import { generateSSHCommand } from "../utils/ssh.js";
export const vpsCommandData = new SlashCommandBuilder()
.setName("vps")
.setDescription("VPS Inventory Assistant management commands")
.addSubcommand((sub) =>
sub.setName("list").setDescription("Display all available VPS in the inventory")
)
.addSubcommand((sub) =>
sub
.setName("info")
.setDescription("Display configuration details for a specific VPS")
.addStringOption((opt) =>
opt
.setName("name")
.setDescription("The name of the VPS (case-insensitive)")
.setRequired(true)
)
)
.addSubcommand((sub) =>
sub
.setName("search")
.setDescription("Search VPS instances by name or IP address")
.addStringOption((opt) =>
opt
.setName("query")
.setDescription("Search keyword or IP address")
.setRequired(true)
)
)
.addSubcommand((sub) =>
sub
.setName("filter")
.setDescription("Filter VPS instances by Provider or Environment")
.addStringOption((opt) =>
opt
.setName("provider")
.setDescription("Provider name (e.g. Vultr, DigitalOcean)")
.setRequired(false)
)
.addStringOption((opt) =>
opt
.setName("environment")
.setDescription("Target environment")
.setRequired(false)
.addChoices(
{ name: "Production", value: "Production" },
{ name: "Staging", value: "Staging" },
{ name: "Development", value: "Development" }
)
)
)
.addSubcommand((sub) =>
sub.setName("stats").setDescription("Show aggregate VPS inventory statistics")
)
.addSubcommand((sub) =>
sub
.setName("connect")
.setDescription("Generate SSH connection command (DevOps / Admin only)")
.addStringOption((opt) =>
opt
.setName("name")
.setDescription("The name of the VPS")
.setRequired(true)
)
);
export class VPSCommandHandler {
private vpsService: VPSService;
constructor(vpsService?: VPSService) {
this.vpsService = vpsService || new VPSService();
}
/**
* Main router for `/vps` subcommands.
*/
public async handle(interaction: ChatInputCommandInteraction): Promise<void> {
const subcommand = interaction.options.getSubcommand();
try {
switch (subcommand) {
case "list":
await this.handleList(interaction);
break;
case "info":
await this.handleInfo(interaction);
break;
case "search":
await this.handleSearch(interaction);
break;
case "filter":
await this.handleFilter(interaction);
break;
case "stats":
await this.handleStats(interaction);
break;
case "connect":
await this.handleConnect(interaction);
break;
default:
await interaction.reply({
embeds: [createErrorEmbed("Unknown Subcommand", "The requested subcommand is not recognized.")],
ephemeral: true,
});
}
} catch (error) {
console.error(`[Error in /vps ${subcommand}]:`, (error as Error).message);
const errorEmbed = createErrorEmbed(
"Internal Processing Error",
"An unexpected error occurred while executing the command. Please try again or contact an administrator."
);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({ embeds: [errorEmbed], ephemeral: true });
} else {
await interaction.reply({ embeds: [errorEmbed], ephemeral: true });
}
}
}
private async handleList(interaction: ChatInputCommandInteraction): Promise<void> {
const servers = this.vpsService.listAll();
const embed = createVPSListEmbed(servers);
await interaction.reply({ embeds: [embed] });
}
private async handleInfo(interaction: ChatInputCommandInteraction): Promise<void> {
const name = interaction.options.getString("name", true);
const vps = this.vpsService.getByName(name);
if (!vps) {
const errorEmbed = createErrorEmbed(
"VPS Not Found",
`Could not find any VPS with the name **"${name}"** in the inventory.`
);
await interaction.reply({ embeds: [errorEmbed], ephemeral: true });
return;
}
const isAuthorized = isDevOpsOrAdmin(interaction.member, process.env.DEVOPS_ROLE_ID);
const embed = createVPSInfoEmbed(vps, isAuthorized);
await interaction.reply({ embeds: [embed] });
}
private async handleSearch(interaction: ChatInputCommandInteraction): Promise<void> {
const query = interaction.options.getString("query", true);
const isAuthorized = isDevOpsOrAdmin(interaction.member, process.env.DEVOPS_ROLE_ID);
const results = this.vpsService.search(query, isAuthorized);
const embed = createVPSSearchEmbed(query, results);
await interaction.reply({ embeds: [embed] });
}
private async handleFilter(interaction: ChatInputCommandInteraction): Promise<void> {
const provider = interaction.options.getString("provider") || undefined;
const environment = (interaction.options.getString("environment") as VPSEnvironment) || undefined;
if (!provider && !environment) {
const warningEmbed = createWarningEmbed(
"Missing Filter Criteria",
"Please provide at least one filter criterion: `provider` or `environment`."
);
await interaction.reply({ embeds: [warningEmbed], ephemeral: true });
return;
}
const results = this.vpsService.filter({ provider, environment });
const embed = createVPSFilterEmbed({ provider, environment }, results);
await interaction.reply({ embeds: [embed] });
}
private async handleStats(interaction: ChatInputCommandInteraction): Promise<void> {
const stats = this.vpsService.getStats();
const embed = createVPSStatsEmbed(stats);
await interaction.reply({ embeds: [embed] });
}
private async handleConnect(interaction: ChatInputCommandInteraction): Promise<void> {
// 1. Enforce Role-Based Authorization
const authResult = checkDevOpsAuthorization(interaction, process.env.DEVOPS_ROLE_ID);
if (!authResult.authorized) {
const errorEmbed = createErrorEmbed(
"Unauthorized",
authResult.reason || "You do not have permission to execute this command."
);
await interaction.reply({ embeds: [errorEmbed], ephemeral: true });
return;
}
// 2. Fetch VPS Record
const name = interaction.options.getString("name", true);
const vps = this.vpsService.getByName(name);
if (!vps) {
const errorEmbed = createErrorEmbed(
"VPS Not Found",
`Could not find any VPS with the name **"${name}"**.`
);
await interaction.reply({ embeds: [errorEmbed], ephemeral: true });
return;
}
// 3. Generate SSH Command securely
const sshResult = generateSSHCommand(vps);
if (!sshResult.success || !sshResult.command) {
const warningEmbed = createWarningEmbed(
"SSH Configuration Incomplete",
sshResult.error || "SSH connection information has not been configured for this VPS."
);
await interaction.reply({ embeds: [warningEmbed], ephemeral: true });
return;
}
// 4. Return Ephemeral Response with SSH details
const connectEmbed = createSSHConnectEmbed(vps, sshResult.command);
await interaction.reply({ embeds: [connectEmbed], ephemeral: true });
}
}
+31
View File
@@ -0,0 +1,31 @@
import dotenv from "dotenv";
import { z } from "zod";
dotenv.config();
export const envSchema = z.object({
DISCORD_TOKEN: z.string().min(1, "DISCORD_TOKEN is required"),
DISCORD_CLIENT_ID: z.string().min(1, "DISCORD_CLIENT_ID is required"),
DISCORD_GUILD_ID: z.string().min(1, "DISCORD_GUILD_ID is required"),
DEVOPS_ROLE_ID: z.string().optional(),
VPS_DATA_PATH: z.string().default("data/vps.json"),
});
export type EnvConfig = z.infer<typeof envSchema>;
let cachedEnv: EnvConfig | null = null;
export function getEnv(): EnvConfig {
if (cachedEnv) {
return cachedEnv;
}
const result = envSchema.safeParse(process.env);
if (!result.success) {
const errorMessages = result.error.issues
.map((issue) => `${issue.path.join(".")}: ${issue.message}`)
.join("; ");
throw new Error(`[Config Error] Invalid environment variables: ${errorMessages}`);
}
cachedEnv = result.data;
return cachedEnv;
}
+27
View File
@@ -0,0 +1,27 @@
import { REST, Routes } from "discord.js";
import { vpsCommandData } from "./commands/vps.command.js";
import { getEnv } from "./config/env.js";
async function deployCommands() {
try {
const env = getEnv();
console.log("🚀 Starting deployment of Discord Slash Commands...");
const commands = [vpsCommandData.toJSON()];
const rest = new REST({ version: "10" }).setToken(env.DISCORD_TOKEN);
console.log(`📦 Registering ${commands.length} application command(s) to Guild ID: ${env.DISCORD_GUILD_ID}`);
const data = (await rest.put(
Routes.applicationGuildCommands(env.DISCORD_CLIENT_ID, env.DISCORD_GUILD_ID),
{ body: commands }
)) as unknown[];
console.log(`✅ Successfully deployed ${data.length} slash command(s) to guild ${env.DISCORD_GUILD_ID}.`);
} catch (error) {
console.error("❌ Failed to deploy slash commands:", (error as Error).message);
process.exit(1);
}
}
deployCommands();
+62
View File
@@ -0,0 +1,62 @@
import { Client, Events, GatewayIntentBits } from "discord.js";
import { VPSCommandHandler } from "./commands/vps.command.js";
import { getEnv } from "./config/env.js";
async function bootstrap() {
console.log("⚡ Starting VPS Inventory Assistant Discord Bot...");
// Validate environment configuration
let env;
try {
env = getEnv();
} catch (err) {
console.error((err as Error).message);
process.exit(1);
}
// Initialize Discord Client with minimal required intents for slash commands
const client = new Client({
intents: [GatewayIntentBits.Guilds],
});
const commandHandler = new VPSCommandHandler();
// Ready event
client.once(Events.ClientReady, (readyClient) => {
console.log(`🤖 Logged in as ${readyClient.user.tag}`);
console.log(`🌐 Active in ${readyClient.guilds.cache.size} guild(s)`);
console.log("✨ Bot is ready to receive /vps commands!");
});
// Interaction Create event
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand()) {
return;
}
if (interaction.commandName === "vps") {
await commandHandler.handle(interaction);
}
});
// Graceful shutdown handling
const handleShutdown = (signal: string) => {
console.log(`\n🛑 Received ${signal}. Shutting down gracefully...`);
client.destroy();
console.log("👋 Discord client disconnected. Goodbye!");
process.exit(0);
};
process.on("SIGINT", () => handleShutdown("SIGINT"));
process.on("SIGTERM", () => handleShutdown("SIGTERM"));
// Login to Discord Gateway
try {
await client.login(env.DISCORD_TOKEN);
} catch (err) {
console.error("❌ Failed to log in to Discord:", (err as Error).message);
process.exit(1);
}
}
bootstrap();
+81
View File
@@ -0,0 +1,81 @@
import fs from "node:fs";
import path from "node:path";
import { VPS, vpsListSchema } from "../types/vps.js";
export class VPSRepository {
private filePath: string;
private cache: VPS[] | null = null;
constructor(filePath?: string) {
this.filePath = filePath || process.env.VPS_DATA_PATH || path.resolve(process.cwd(), "data/vps.json");
}
/**
* Loads and validates VPS records from the JSON data file.
*/
public load(): VPS[] {
const resolvedPath = path.resolve(this.filePath);
if (!fs.existsSync(resolvedPath)) {
throw new Error(`Inventory data file not found at path: ${resolvedPath}`);
}
let rawData: string;
try {
rawData = fs.readFileSync(resolvedPath, "utf-8");
} catch (err) {
throw new Error(`Failed to read inventory data file: ${(err as Error).message}`);
}
let parsed: unknown;
try {
parsed = JSON.parse(rawData);
} catch (err) {
throw new Error(`Corrupted JSON inventory data file: ${(err as Error).message}`);
}
const validation = vpsListSchema.safeParse(parsed);
if (!validation.success) {
const issueDetails = validation.error.issues
.map((issue) => `[${issue.path.join(".")}]: ${issue.message}`)
.join("; ");
throw new Error(`Invalid VPS inventory data structure: ${issueDetails}`);
}
this.cache = validation.data;
return this.cache;
}
/**
* Returns all VPS records.
*/
public getAll(): VPS[] {
if (!this.cache) {
return this.load();
}
return this.cache;
}
/**
* Finds a VPS by exact ID.
*/
public getById(id: string): VPS | undefined {
return this.getAll().find((vps) => vps.id === id);
}
/**
* Finds a VPS by name (case-insensitive).
*/
public getByName(name: string): VPS | undefined {
const trimmed = name.trim().toLowerCase();
return this.getAll().find((vps) => vps.name.toLowerCase() === trimmed);
}
/**
* Force reloads the data from disk.
*/
public reload(): VPS[] {
this.cache = null;
return this.load();
}
}
+106
View File
@@ -0,0 +1,106 @@
import { VPSRepository } from "../repositories/vps.repository.js";
import { VPS, VPSFilterOptions, VPSStats } from "../types/vps.js";
export class VPSService {
private repository: VPSRepository;
constructor(repository?: VPSRepository) {
this.repository = repository || new VPSRepository();
}
/**
* Retrieves all VPS records from inventory.
*/
public listAll(): VPS[] {
return this.repository.getAll();
}
/**
* Looks up a VPS by name (case-insensitive, trimmed).
*/
public getByName(name: string): VPS | undefined {
if (!name || name.trim() === "") {
return undefined;
}
return this.repository.getByName(name);
}
/**
* Searches VPS records by name or IP.
* Case-insensitive, supports partial matching.
*/
public search(query: string, allowIPSearch = true): VPS[] {
const trimmed = query.trim().toLowerCase();
if (!trimmed) {
return [];
}
const all = this.repository.getAll();
return all.filter((vps) => {
// Match by name
const nameMatch = vps.name.toLowerCase().includes(trimmed);
// Match by IP if allowed and IP is configured
const ipMatch = allowIPSearch && vps.ip ? vps.ip.toLowerCase().includes(trimmed) : false;
return nameMatch || ipMatch;
});
}
/**
* Filters VPS records by provider and/or environment using AND logic.
*/
public filter(options: VPSFilterOptions): VPS[] {
const all = this.repository.getAll();
const providerFilter = options.provider?.trim().toLowerCase();
const envFilter = options.environment?.trim().toLowerCase();
return all.filter((vps) => {
let matchesProvider = true;
let matchesEnv = true;
if (providerFilter) {
matchesProvider = vps.provider.toLowerCase() === providerFilter;
}
if (envFilter) {
matchesEnv = vps.environment.toLowerCase() === envFilter;
}
return matchesProvider && matchesEnv;
});
}
/**
* Dynamically calculates aggregate inventory statistics.
*/
public getStats(): VPSStats {
const all = this.repository.getAll();
const stats: VPSStats = {
totalVPS: all.length,
totalVCPU: 0,
totalRamGB: 0,
totalDiskGB: 0,
byEnvironment: {},
byProvider: {},
};
for (const vps of all) {
stats.totalVCPU += vps.cpu;
stats.totalRamGB += vps.ramGB;
stats.totalDiskGB += vps.diskGB;
// Group by Environment
const env = vps.environment;
stats.byEnvironment[env] = (stats.byEnvironment[env] || 0) + 1;
// Group by Provider
const provider = vps.provider;
stats.byProvider[provider] = (stats.byProvider[provider] || 0) + 1;
}
return stats;
}
}
+36
View File
@@ -0,0 +1,36 @@
import { z } from "zod";
export const VPSEnvironmentEnum = z.enum(["Production", "Staging", "Development"]);
export type VPSEnvironment = z.infer<typeof VPSEnvironmentEnum>;
export const vpsSchema = z.object({
id: z.string().min(1, "VPS ID cannot be empty"),
name: z.string().min(1, "VPS name cannot be empty"),
provider: z.string().min(1, "VPS provider cannot be empty"),
region: z.string().min(1, "VPS region cannot be empty"),
environment: VPSEnvironmentEnum,
cpu: z.number().int().positive("CPU count must be a positive integer"),
ramGB: z.number().positive("RAM must be a positive number"),
diskGB: z.number().positive("Disk must be a positive number"),
ip: z.string().optional(),
sshUser: z.string().optional(),
sshPort: z.number().int().min(1).max(65535).optional(),
});
export const vpsListSchema = z.array(vpsSchema);
export type VPS = z.infer<typeof vpsSchema>;
export interface VPSFilterOptions {
provider?: string;
environment?: VPSEnvironment;
}
export interface VPSStats {
totalVPS: number;
totalVCPU: number;
totalRamGB: number;
totalDiskGB: number;
byEnvironment: Record<string, number>;
byProvider: Record<string, number>;
}
+276
View File
@@ -0,0 +1,276 @@
import { EmbedBuilder } from "discord.js";
import { VPS, VPSFilterOptions, VPSStats } from "../types/vps.js";
export const EMBED_COLORS = {
PRIMARY: 0x5865f2, // Discord Blurple
SUCCESS: 0x2ecc71, // Green
WARNING: 0xf1c40f, // Yellow
ERROR: 0xe74c3c, // Red
} as const;
/**
* Creates an embed for the inventory list command.
*/
export function createVPSListEmbed(servers: VPS[]): EmbedBuilder {
const embed = new EmbedBuilder()
.setTitle("🖥️ VPS Inventory Overview")
.setColor(EMBED_COLORS.PRIMARY)
.setTimestamp()
.setFooter({ text: `Total Servers: ${servers.length}` });
if (servers.length === 0) {
embed.setDescription("ℹ️ No VPS records found in the inventory.");
return embed;
}
embed.setDescription(
`Displaying **${servers.length}** VPS server(s) currently managed in the inventory:\n`
);
for (const vps of servers) {
const envBadge =
vps.environment === "Production"
? "🔴 Production"
: vps.environment === "Staging"
? "🟡 Staging"
: "🟢 Development";
const value = [
`• **Provider:** ${vps.provider} (${vps.region})`,
`• **Environment:** ${envBadge}`,
`• **Hardware:** ${vps.cpu} vCPU | ${vps.ramGB} GB RAM | ${vps.diskGB} GB Disk`,
].join("\n");
embed.addFields({
name: `📌 ${vps.name}`,
value,
inline: false,
});
}
return embed;
}
/**
* Creates a detailed embed for a specific VPS.
*/
export function createVPSInfoEmbed(vps: VPS, isAuthorized = false): EmbedBuilder {
const envBadge =
vps.environment === "Production"
? "🔴 Production"
: vps.environment === "Staging"
? "🟡 Staging"
: "🟢 Development";
let ipDisplay = "Not configured";
if (vps.ip) {
ipDisplay = isAuthorized ? `\`${vps.ip}\`` : "🔒 Protected (DevOps role required)";
}
return new EmbedBuilder()
.setTitle(`🖥️ VPS DETAILS — ${vps.name}`)
.setColor(EMBED_COLORS.PRIMARY)
.setDescription(`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n**Server Identification:** \`${vps.id}\``)
.addFields(
{
name: "📌 General Information",
value: [
`• **Provider:** ${vps.provider}`,
`• **Region:** ${vps.region}`,
`• **Environment:** ${envBadge}`,
].join("\n"),
inline: false,
},
{
name: "⚙️ Hardware Specifications",
value: [
`• **CPU:** ${vps.cpu} vCPU`,
`• **RAM:** ${vps.ramGB} GB`,
`• **Disk:** ${vps.diskGB} GB SSD`,
].join("\n"),
inline: false,
},
{
name: "🌐 Network & Access",
value: [
`• **IP Address:** ${ipDisplay}`,
`• **SSH User:** ${vps.sshUser && isAuthorized ? `\`${vps.sshUser}\`` : vps.sshUser ? "🔒 Protected" : "Not configured"}`,
`• **SSH Port:** ${vps.sshPort ?? 22}`,
].join("\n"),
inline: false,
}
)
.setFooter({ text: "VPS Inventory Assistant • Confidential" })
.setTimestamp();
}
/**
* Creates an embed for VPS search results.
*/
export function createVPSSearchEmbed(query: string, results: VPS[]): EmbedBuilder {
const embed = new EmbedBuilder()
.setTitle("🔍 VPS Search Results")
.setTimestamp()
.setFooter({ text: `Matched: ${results.length} server(s)` });
if (results.length === 0) {
return embed
.setColor(EMBED_COLORS.WARNING)
.setDescription(`No VPS found matching query: **"${query}"**.\nTry another keyword or IP.`);
}
embed
.setColor(EMBED_COLORS.PRIMARY)
.setDescription(`Found **${results.length}** server(s) matching search keyword: **"${query}"**\n`);
for (const vps of results) {
embed.addFields({
name: `📌 ${vps.name} (${vps.environment})`,
value: `• **Provider:** ${vps.provider} (${vps.region})\n• **Specs:** ${vps.cpu} vCPU | ${vps.ramGB} GB RAM | ${vps.diskGB} GB Disk`,
inline: false,
});
}
return embed;
}
/**
* Creates an embed for filtered VPS results.
*/
export function createVPSFilterEmbed(filters: VPSFilterOptions, results: VPS[]): EmbedBuilder {
const activeFilters: string[] = [];
if (filters.provider) activeFilters.push(`Provider = **${filters.provider}**`);
if (filters.environment) activeFilters.push(`Environment = **${filters.environment}**`);
const filterSummary = activeFilters.join(" AND ");
const embed = new EmbedBuilder()
.setTitle("🎯 VPS Filter Results")
.setTimestamp()
.setFooter({ text: `Matched: ${results.length} server(s)` });
if (results.length === 0) {
return embed
.setColor(EMBED_COLORS.WARNING)
.setDescription(
`Active Filter: ${filterSummary}\n\n❌ No VPS found matching the selected filter criteria.`
);
}
embed
.setColor(EMBED_COLORS.PRIMARY)
.setDescription(
`Active Filter: ${filterSummary}\nFound **${results.length}** matching server(s):\n`
);
for (const vps of results) {
embed.addFields({
name: `📌 ${vps.name}`,
value: `• **Provider:** ${vps.provider} (${vps.region})\n• **Environment:** ${vps.environment}\n• **Specs:** ${vps.cpu} vCPU | ${vps.ramGB} GB | ${vps.diskGB} GB`,
inline: false,
});
}
return embed;
}
/**
* Creates an embed displaying dynamic inventory statistics.
*/
export function createVPSStatsEmbed(stats: VPSStats): EmbedBuilder {
const providerBreakdown = Object.entries(stats.byProvider)
.map(([provider, count]) => `• **${provider}:** ${count} server(s)`)
.join("\n") || "None";
const envBreakdown = Object.entries(stats.byEnvironment)
.map(([env, count]) => `• **${env}:** ${count} server(s)`)
.join("\n") || "None";
return new EmbedBuilder()
.setTitle("📊 VPS Inventory Statistics")
.setColor(EMBED_COLORS.SUCCESS)
.setDescription("Aggregated statistics across all registered VPS instances in the inventory.")
.addFields(
{
name: "🖥️ Inventory Summary",
value: `• **Total VPS:** ${stats.totalVPS}`,
inline: true,
},
{
name: "⚙️ Aggregate Resources",
value: [
`• **Total vCPU:** ${stats.totalVCPU} vCPU`,
`• **Total RAM:** ${stats.totalRamGB} GB`,
`• **Total Disk:** ${stats.totalDiskGB} GB SSD`,
].join("\n"),
inline: true,
},
{
name: "\u200B", // Spacer line for visual separation
value: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
inline: false,
},
{
name: "🏢 Servers by Provider",
value: providerBreakdown,
inline: true,
},
{
name: "🏷️ Servers by Environment",
value: envBreakdown,
inline: true,
}
)
.setFooter({ text: "VPS Inventory Assistant" })
.setTimestamp();
}
/**
* Creates an ephemeral embed containing the generated SSH connection command.
*/
export function createSSHConnectEmbed(vps: VPS, sshCommand: string): EmbedBuilder {
return new EmbedBuilder()
.setTitle(`🔑 SSH Access: ${vps.name}`)
.setColor(EMBED_COLORS.SUCCESS)
.setDescription(
[
`Connection parameters verified for **${vps.name}** (${vps.provider} - ${vps.region}).`,
"",
"Copy and run the command below in your authorized terminal:",
"```bash",
sshCommand,
"```",
].join("\n")
)
.addFields(
{ name: "SSH Target Host", value: `\`${vps.ip}\``, inline: true },
{ name: "SSH User", value: `\`${vps.sshUser}\``, inline: true },
{ name: "SSH Port", value: `\`${vps.sshPort ?? 22}\``, inline: true }
)
.setFooter({
text: "🔒 Confidential • Authorized DevOps Access Only • Command not executed by bot",
})
.setTimestamp();
}
/**
* Creates a standardized error embed.
*/
export function createErrorEmbed(title: string, description: string): EmbedBuilder {
return new EmbedBuilder()
.setTitle(`❌ ${title}`)
.setColor(EMBED_COLORS.ERROR)
.setDescription(description)
.setTimestamp();
}
/**
* Creates a standardized warning embed.
*/
export function createWarningEmbed(title: string, description: string): EmbedBuilder {
return new EmbedBuilder()
.setTitle(`⚠️ ${title}`)
.setColor(EMBED_COLORS.WARNING)
.setDescription(description)
.setTimestamp();
}
+87
View File
@@ -0,0 +1,87 @@
import {
ChatInputCommandInteraction,
GuildMember,
PermissionsBitField,
PermissionFlagsBits,
} from "discord.js";
/**
* Checks whether a guild member has Administrator permissions or the designated DevOps role.
* Fails securely if permissions or role configurations are missing.
*/
export function isDevOpsOrAdmin(
member: GuildMember | ChatInputCommandInteraction["member"],
devopsRoleId?: string
): boolean {
if (!member) {
return false;
}
// Check Discord Administrator permission
if ("permissions" in member && member.permissions) {
try {
if (typeof member.permissions === "string") {
const bitfield = new PermissionsBitField(BigInt(member.permissions));
if (bitfield.has(PermissionFlagsBits.Administrator)) {
return true;
}
} else if (member.permissions instanceof PermissionsBitField) {
if (member.permissions.has(PermissionFlagsBits.Administrator)) {
return true;
}
}
} catch {
// Securely fallback to role check if permissions cannot be evaluated
}
}
// Check DevOps Role ID
if (!devopsRoleId || devopsRoleId.trim() === "") {
return false;
}
const trimmedRole = devopsRoleId.trim();
if ("roles" in member && member.roles) {
// If member is a GuildMember, roles is a GuildMemberRoleManager
if ("cache" in member.roles && member.roles.cache) {
return member.roles.cache.has(trimmedRole);
}
// If member is raw APIInteractionGuildMember, roles is string[]
if (Array.isArray(member.roles)) {
return member.roles.includes(trimmedRole);
}
}
return false;
}
export interface AuthorizationResult {
authorized: boolean;
reason?: string;
}
/**
* Validates interaction context and checks DevOps/Admin authorization.
*/
export function checkDevOpsAuthorization(
interaction: ChatInputCommandInteraction,
devopsRoleId?: string
): AuthorizationResult {
if (!interaction.guildId || !interaction.member) {
return {
authorized: false,
reason: "This command can only be executed within an authorized Discord Server (Guild).",
};
}
const authorized = isDevOpsOrAdmin(interaction.member, devopsRoleId);
if (!authorized) {
return {
authorized: false,
reason: "Permission Denied: You must have the DevOps role or Server Administrator permissions to access SSH connection details.",
};
}
return { authorized: true };
}
+94
View File
@@ -0,0 +1,94 @@
import net from "node:net";
import { VPS } from "../types/vps.js";
export interface SSHCommandResult {
success: boolean;
command?: string;
error?: string;
}
// RFC 1123 compliant hostname regex: letters, numbers, hyphens, dots. Max 253 chars.
const HOSTNAME_REGEX = /^(?=.{1,253}$)(?!-)[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
// Standard POSIX username: alphanumeric, underscore, hyphen; 1-32 chars
const USERNAME_REGEX = /^[a-zA-Z0-9_-]{1,32}$/;
/**
* Validates the SSH target (IP or hostname).
*/
export function isValidHost(host: string): boolean {
const trimmed = host.trim();
// 1. Check if valid IPv4 or IPv6 via Node standard library
if (net.isIP(trimmed) !== 0) {
return true;
}
// 2. If it contains only digits and dots, it is an invalid IP address
if (/^[\d.]+$/.test(trimmed)) {
return false;
}
// 3. Otherwise, validate as a standard hostname / FQDN
return HOSTNAME_REGEX.test(trimmed);
}
/**
* Validates the SSH username to prevent argument or command injection.
*/
export function isValidUsername(user: string): boolean {
return USERNAME_REGEX.test(user.trim());
}
/**
* Validates the SSH port number.
*/
export function isValidPort(port: number): boolean {
return Number.isInteger(port) && port >= 1 && port <= 65535;
}
/**
* Safely constructs an SSH connection string for an authorized user.
* Never executes the command or performs network requests.
*/
export function generateSSHCommand(vps: VPS): SSHCommandResult {
if (!vps.ip || !vps.sshUser) {
return {
success: false,
error: "SSH connection information has not been configured for this VPS.",
};
}
const host = vps.ip.trim();
const user = vps.sshUser.trim();
const port = vps.sshPort ?? 22;
if (!isValidHost(host)) {
return {
success: false,
error: "Configured IP or hostname format is invalid or unsafe.",
};
}
if (!isValidUsername(user)) {
return {
success: false,
error: "Configured SSH username format is invalid or unsafe.",
};
}
if (!isValidPort(port)) {
return {
success: false,
error: "Configured SSH port must be an integer between 1 and 65535.",
};
}
// Safe construction: ssh -p <port> <user>@<host>
const command = `ssh -p ${port} ${user}@${host}`;
return {
success: true,
command,
};
}
+113
View File
@@ -0,0 +1,113 @@
import { describe, it, expect } from "vitest";
import { PermissionFlagsBits, PermissionsBitField } from "discord.js";
import { isDevOpsOrAdmin, checkDevOpsAuthorization } from "../src/utils/permissions.js";
describe("Permissions Utilities", () => {
const DEVOPS_ROLE_ID = "role-devops-123";
describe("isDevOpsOrAdmin", () => {
it("should return false if member is null or undefined", () => {
expect(isDevOpsOrAdmin(null as any, DEVOPS_ROLE_ID)).toBe(false);
expect(isDevOpsOrAdmin(undefined as any, DEVOPS_ROLE_ID)).toBe(false);
});
it("should return true if member has Administrator permission via PermissionsBitField", () => {
const member = {
permissions: new PermissionsBitField(PermissionFlagsBits.Administrator),
roles: { cache: new Map() },
};
expect(isDevOpsOrAdmin(member as any, DEVOPS_ROLE_ID)).toBe(true);
});
it("should return true if member has Administrator permission via string bitfield", () => {
const bitfield = new PermissionsBitField(PermissionFlagsBits.Administrator).bitfield.toString();
const member = {
permissions: bitfield,
roles: [],
};
expect(isDevOpsOrAdmin(member as any, DEVOPS_ROLE_ID)).toBe(true);
});
it("should return true if member has the DevOps role via cache.has", () => {
const roleMap = new Map();
roleMap.set(DEVOPS_ROLE_ID, { id: DEVOPS_ROLE_ID, name: "DevOps" });
const member = {
permissions: new PermissionsBitField(),
roles: {
cache: {
has: (id: string) => roleMap.has(id),
},
},
};
expect(isDevOpsOrAdmin(member as any, DEVOPS_ROLE_ID)).toBe(true);
});
it("should return true if member has the DevOps role via string array (APIInteractionGuildMember)", () => {
const member = {
permissions: "0",
roles: ["other-role", DEVOPS_ROLE_ID],
};
expect(isDevOpsOrAdmin(member as any, DEVOPS_ROLE_ID)).toBe(true);
});
it("should return false if member does not have DevOps role or Admin", () => {
const member = {
permissions: new PermissionsBitField(),
roles: {
cache: {
has: (_id: string) => false,
},
},
};
expect(isDevOpsOrAdmin(member as any, DEVOPS_ROLE_ID)).toBe(false);
});
it("should fail securely (return false) if devopsRoleId is empty or not provided and member is not admin", () => {
const member = {
permissions: new PermissionsBitField(),
roles: ["some-role"],
};
expect(isDevOpsOrAdmin(member as any, undefined)).toBe(false);
expect(isDevOpsOrAdmin(member as any, "")).toBe(false);
});
});
describe("checkDevOpsAuthorization", () => {
it("should deny access when command is executed outside a guild (e.g. DM)", () => {
const mockInteraction = {
guildId: null,
member: null,
};
const result = checkDevOpsAuthorization(mockInteraction as any, DEVOPS_ROLE_ID);
expect(result.authorized).toBe(false);
expect(result.reason).toContain("only be executed within an authorized Discord Server");
});
it("should deny access when member does not hold DevOps or Admin permissions", () => {
const mockInteraction = {
guildId: "guild-123",
member: {
permissions: new PermissionsBitField(),
roles: { cache: { has: () => false } },
},
};
const result = checkDevOpsAuthorization(mockInteraction as any, DEVOPS_ROLE_ID);
expect(result.authorized).toBe(false);
expect(result.reason).toContain("Permission Denied");
});
it("should grant access when member has DevOps role in a guild", () => {
const mockInteraction = {
guildId: "guild-123",
member: {
permissions: new PermissionsBitField(),
roles: { cache: { has: (id: string) => id === DEVOPS_ROLE_ID } },
},
};
const result = checkDevOpsAuthorization(mockInteraction as any, DEVOPS_ROLE_ID);
expect(result.authorized).toBe(true);
expect(result.reason).toBeUndefined();
});
});
});
+115
View File
@@ -0,0 +1,115 @@
import { describe, it, expect } from "vitest";
import { generateSSHCommand, isValidHost, isValidUsername, isValidPort } from "../src/utils/ssh.js";
import { VPS } from "../src/types/vps.js";
describe("SSH Utility", () => {
const baseVPS: VPS = {
id: "vps-test",
name: "test-node",
provider: "Vultr",
region: "Singapore",
environment: "Production",
cpu: 4,
ramGB: 8,
diskGB: 160,
};
describe("Validation functions", () => {
it("should correctly validate IPv4 and hostnames", () => {
expect(isValidHost("203.0.113.10")).toBe(true);
expect(isValidHost("192.168.1.1")).toBe(true);
expect(isValidHost("vps.example.com")).toBe(true);
// Malicious or invalid hosts
expect(isValidHost("203.0.113.10; rm -rf /")).toBe(false);
expect(isValidHost("`whoami`.example.com")).toBe(false);
expect(isValidHost("-oProxyCommand=calc.exe")).toBe(false);
expect(isValidHost("256.300.1.1")).toBe(false);
});
it("should correctly validate SSH usernames", () => {
expect(isValidUsername("root")).toBe(true);
expect(isValidUsername("deploy")).toBe(true);
expect(isValidUsername("admin_user-01")).toBe(true);
// Malicious usernames
expect(isValidUsername("deploy; ls")).toBe(false);
expect(isValidUsername("user$(whoami)")).toBe(false);
expect(isValidUsername("user`id`")).toBe(false);
expect(isValidUsername("user with spaces")).toBe(false);
});
it("should correctly validate ports", () => {
expect(isValidPort(22)).toBe(true);
expect(isValidPort(2222)).toBe(true);
expect(isValidPort(65535)).toBe(true);
expect(isValidPort(0)).toBe(false);
expect(isValidPort(-1)).toBe(false);
expect(isValidPort(70000)).toBe(false);
expect(isValidPort(22.5)).toBe(false);
});
});
describe("generateSSHCommand", () => {
it("should fail gracefully if IP is missing", () => {
const vpsWithoutIP: VPS = { ...baseVPS, sshUser: "deploy" };
const result = generateSSHCommand(vpsWithoutIP);
expect(result.success).toBe(false);
expect(result.error).toBe("SSH connection information has not been configured for this VPS.");
expect(result.command).toBeUndefined();
});
it("should fail gracefully if sshUser is missing", () => {
const vpsWithoutUser: VPS = { ...baseVPS, ip: "203.0.113.10" };
const result = generateSSHCommand(vpsWithoutUser);
expect(result.success).toBe(false);
expect(result.error).toBe("SSH connection information has not been configured for this VPS.");
});
it("should default to port 22 when sshPort is not specified", () => {
const vps: VPS = {
...baseVPS,
ip: "203.0.113.10",
sshUser: "deploy",
};
const result = generateSSHCommand(vps);
expect(result.success).toBe(true);
expect(result.command).toBe("ssh -p 22 deploy@203.0.113.10");
});
it("should use custom port when sshPort is specified", () => {
const vps: VPS = {
...baseVPS,
ip: "198.51.100.25",
sshUser: "ubuntu",
sshPort: 22022,
};
const result = generateSSHCommand(vps);
expect(result.success).toBe(true);
expect(result.command).toBe("ssh -p 22022 ubuntu@198.51.100.25");
});
it("should reject malicious IP input", () => {
const vps: VPS = {
...baseVPS,
ip: "203.0.113.10; id",
sshUser: "deploy",
};
const result = generateSSHCommand(vps);
expect(result.success).toBe(false);
expect(result.error).toContain("invalid or unsafe");
});
it("should reject malicious username input", () => {
const vps: VPS = {
...baseVPS,
ip: "203.0.113.10",
sshUser: "deploy&&reboot",
};
const result = generateSSHCommand(vps);
expect(result.success).toBe(false);
expect(result.error).toContain("invalid or unsafe");
});
});
});
+197
View File
@@ -0,0 +1,197 @@
import { describe, it, expect, beforeEach } from "vitest";
import path from "node:path";
import { VPSRepository } from "../src/repositories/vps.repository.js";
import { VPSService } from "../src/services/vps.service.js";
import { VPS } from "../src/types/vps.js";
describe("VPS Repository and Service", () => {
let repository: VPSRepository;
let service: VPSService;
beforeEach(() => {
// Point to data/vps.json
const seedPath = path.resolve(process.cwd(), "data/vps.json");
repository = new VPSRepository(seedPath);
service = new VPSService(repository);
});
describe("Repository loading and validation", () => {
it("should load exactly the 3 seed VPS records", () => {
const all = repository.getAll();
expect(all).toHaveLength(3);
});
it("should throw a descriptive error when file is missing", () => {
const invalidRepo = new VPSRepository("non-existent-path.json");
expect(() => invalidRepo.getAll()).toThrow("Inventory data file not found");
});
});
describe("listAll", () => {
it("should return all three VPS with correct properties", () => {
const list = service.listAll();
expect(list).toHaveLength(3);
const names = list.map((v) => v.name);
expect(names).toEqual(["shop-prod-01", "staging-01", "db-prod-01"]);
});
});
describe("getByName", () => {
it("should return the exact VPS when name matches", () => {
const vps = service.getByName("shop-prod-01");
expect(vps).toBeDefined();
expect(vps?.name).toBe("shop-prod-01");
expect(vps?.provider).toBe("Vultr");
expect(vps?.region).toBe("Singapore");
expect(vps?.environment).toBe("Production");
expect(vps?.cpu).toBe(4);
expect(vps?.ramGB).toBe(8);
expect(vps?.diskGB).toBe(160);
});
it("should support case-insensitive name lookup", () => {
const vps1 = service.getByName("SHOP-PROD-01");
const vps2 = service.getByName("sHoP-pRoD-01");
expect(vps1).toBeDefined();
expect(vps1?.id).toBe("vps-001");
expect(vps2?.id).toBe("vps-001");
});
it("should trim surrounding whitespace in name lookup", () => {
const vps = service.getByName(" staging-01 ");
expect(vps).toBeDefined();
expect(vps?.name).toBe("staging-01");
});
it("should return undefined for non-existent VPS", () => {
const vps = service.getByName("non-existent-vps");
expect(vps).toBeUndefined();
});
it("should return undefined for empty string or whitespace-only name", () => {
expect(service.getByName("")).toBeUndefined();
expect(service.getByName(" ")).toBeUndefined();
});
});
describe("search", () => {
it("should search by partial name case-insensitively", () => {
const results = service.search("prod");
expect(results).toHaveLength(2);
expect(results.map((v) => v.name)).toEqual(["shop-prod-01", "db-prod-01"]);
});
it("should return staging-01 when searching 'stag'", () => {
const results = service.search("STAG");
expect(results).toHaveLength(1);
expect(results[0].name).toBe("staging-01");
});
it("should search by IP address when IP is configured", () => {
// Mock repository with an IP configured
const mockRepo = new VPSRepository();
const mockVPSList: VPS[] = [
{
id: "vps-test",
name: "test-vps",
provider: "AWS",
region: "Tokyo",
environment: "Development",
cpu: 2,
ramGB: 4,
diskGB: 40,
ip: "192.0.2.15",
},
];
mockRepo.getAll = () => mockVPSList;
const testService = new VPSService(mockRepo);
const byIp = testService.search("192.0.2", true);
expect(byIp).toHaveLength(1);
expect(byIp[0].name).toBe("test-vps");
// When IP search is not permitted (e.g. unauthenticated)
const noIp = testService.search("192.0.2", false);
expect(noIp).toHaveLength(0);
});
it("should return empty array for empty search query", () => {
const results = service.search(" ");
expect(results).toEqual([]);
});
it("should return empty array when no VPS matches", () => {
const results = service.search("unknown-query-xyz");
expect(results).toEqual([]);
});
});
describe("filter", () => {
it("should filter by Provider case-insensitively", () => {
const vultr = service.filter({ provider: "vultr" });
expect(vultr).toHaveLength(2);
expect(vultr.map((v) => v.name)).toEqual(["shop-prod-01", "db-prod-01"]);
const doServers = service.filter({ provider: "DigitalOcean" });
expect(doServers).toHaveLength(1);
expect(doServers[0].name).toBe("staging-01");
});
it("should filter by Environment", () => {
const prod = service.filter({ environment: "Production" });
expect(prod).toHaveLength(2);
const staging = service.filter({ environment: "Staging" });
expect(staging).toHaveLength(1);
expect(staging[0].name).toBe("staging-01");
const dev = service.filter({ environment: "Development" });
expect(dev).toHaveLength(0);
});
it("should support combining both filters using AND logic", () => {
const result1 = service.filter({ provider: "Vultr", environment: "Production" });
expect(result1).toHaveLength(2);
const result2 = service.filter({ provider: "DigitalOcean", environment: "Production" });
expect(result2).toHaveLength(0);
const result3 = service.filter({ provider: "DigitalOcean", environment: "Staging" });
expect(result3).toHaveLength(1);
expect(result3[0].name).toBe("staging-01");
});
it("should return empty array when no records match filter criteria", () => {
const none = service.filter({ provider: "NonExistentProvider" });
expect(none).toEqual([]);
});
});
describe("getStats", () => {
it("should accurately compute all aggregate statistics for seed data", () => {
const stats = service.getStats();
// Verified exact calculations:
// shop-prod-01: 4 CPU, 8 RAM, 160 Disk
// staging-01: 2 CPU, 4 RAM, 80 Disk
// db-prod-01: 4 CPU, 16 RAM, 320 Disk
expect(stats.totalVPS).toBe(3);
expect(stats.totalVCPU).toBe(10);
expect(stats.totalRamGB).toBe(28);
expect(stats.totalDiskGB).toBe(560);
// Environment breakdown
expect(stats.byEnvironment).toEqual({
Production: 2,
Staging: 1,
});
// Provider breakdown
expect(stats.byProvider).toEqual({
Vultr: 2,
DigitalOcean: 1,
});
});
});
});
+15
View File
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"outDir": "./dist"
},
"include": ["src/**/*", "tests/**/*"]
}