From 4ccb35a44c27d5f390351f9afd32a01f2fb44217 Mon Sep 17 00:00:00 2001 From: Khuong Nguyen Date: Wed, 2 Dec 2026 10:26:56 +0700 Subject: [PATCH] feat: SQLite RBAC, granular permissions, 100-VPS seeder, DM pagination --- .env.example | 3 + .gitignore | 3 + data/vps.json | 39 -- package.json | 1 + src/commands/vps.command.ts | 417 ++++++++++++++++++++-- src/config/env.ts | 26 +- src/index.ts | 57 ++- src/repositories/permission.repository.ts | 353 ++++++++++++++++++ src/repositories/vps.repository.ts | 297 ++++++++++++--- src/seed.ts | 36 ++ src/services/vps.service.ts | 6 +- src/utils/embeds.ts | 166 ++++++--- src/utils/permissions.ts | 206 ++++++++--- tests/embeds.test.ts | 46 +++ tests/permissions.test.ts | 237 +++++++++--- tests/vps.service.test.ts | 124 ++++--- 16 files changed, 1690 insertions(+), 327 deletions(-) delete mode 100644 data/vps.json create mode 100644 src/repositories/permission.repository.ts create mode 100644 src/seed.ts create mode 100644 tests/embeds.test.ts diff --git a/.env.example b/.env.example index 81904a5..68dcfaf 100644 --- a/.env.example +++ b/.env.example @@ -9,3 +9,6 @@ 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 + +# Path to SQLite database file (optional, defaults to data/vps.db) +VPS_DB_PATH=data/vps.db diff --git a/.gitignore b/.gitignore index 7436a3b..07f1a0c 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,9 @@ node_modules/ dist/ .env .env.local +data/*.db +data/*.db-wal +data/*.db-shm *.log npm-debug.log* yarn-debug.log* diff --git a/data/vps.json b/data/vps.json deleted file mode 100644 index 09efb45..0000000 --- a/data/vps.json +++ /dev/null @@ -1,39 +0,0 @@ -[ - { - "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" - } -] diff --git a/package.json b/package.json index d269dcd..dcaea8a 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,7 @@ "dev": "tsx watch src/index.ts", "start": "tsx src/index.ts", "deploy:commands": "tsx src/deploy-commands.ts", + "db:seed": "tsx src/seed.ts", "typecheck": "tsc --noEmit", "test": "vitest run" }, diff --git a/src/commands/vps.command.ts b/src/commands/vps.command.ts index cf5a2f2..4fb399b 100644 --- a/src/commands/vps.command.ts +++ b/src/commands/vps.command.ts @@ -1,7 +1,14 @@ import { + ActionRowBuilder, + ButtonBuilder, + ButtonInteraction, + ButtonStyle, ChatInputCommandInteraction, + EmbedBuilder, SlashCommandBuilder, } from "discord.js"; +import { getDataConfig } from "../config/env.js"; +import { PermissionRepository } from "../repositories/permission.repository.js"; import { VPSService } from "../services/vps.service.js"; import { VPSEnvironment } from "../types/vps.js"; import { @@ -9,14 +16,49 @@ import { createSSHConnectEmbed, createVPSFilterEmbed, createVPSInfoEmbed, - createVPSListEmbed, + createVPSListPages, createVPSSearchEmbed, createVPSStatsEmbed, createWarningEmbed, + EMBED_COLORS, } from "../utils/embeds.js"; -import { checkDevOpsAuthorization, isDevOpsOrAdmin } from "../utils/permissions.js"; +import { + ALL_VPS_PERMISSIONS, + authorizeAction, + createDefaultPermissionConfig, + hasAdministratorPermission, + hasPermission, + PermissionSource, + VPSPermission, +} from "../utils/permissions.js"; import { generateSSHCommand } from "../utils/ssh.js"; +/** + * Action-based permission requirement per subcommand. + */ +export const SUBCOMMAND_PERMISSIONS: Record = { + list: "vps:list", + info: "vps:info", + search: "vps:search", + filter: "vps:filter", + stats: "vps:stats", + connect: "vps:connect", +}; + +const PERMISSION_CHOICES = [ + { name: "all (Full VPS access)", value: "all" }, + { name: "vps:list (/vps list)", value: "vps:list" }, + { name: "vps:info (/vps info)", value: "vps:info" }, + { name: "vps:search (/vps search)", value: "vps:search" }, + { name: "vps:filter (/vps filter)", value: "vps:filter" }, + { name: "vps:stats (/vps stats)", value: "vps:stats" }, + { name: "vps:read_sensitive (View IP/SSH & search by IP)", value: "vps:read_sensitive" }, + { name: "vps:connect (/vps connect)", value: "vps:connect" }, + { name: "vps:add (/vps add - future)", value: "vps:add" }, + { name: "vps:update (/vps update - future)", value: "vps:update" }, + { name: "vps:delete (/vps delete - future)", value: "vps:delete" }, +] as const; + export const vpsCommandData = new SlashCommandBuilder() .setName("vps") .setDescription("VPS Inventory Assistant management commands") @@ -73,29 +115,103 @@ export const vpsCommandData = new SlashCommandBuilder() .addSubcommand((sub) => sub .setName("connect") - .setDescription("Generate SSH connection command (DevOps / Admin only)") + .setDescription("Generate SSH connection command (requires vps:connect permission)") .addStringOption((opt) => opt .setName("name") .setDescription("The name of the VPS") .setRequired(true) ) + ) + .addSubcommandGroup((group) => + group + .setName("perm") + .setDescription("Manage Role -> Permission rules in SQLite (Server Admin only)") + .addSubcommand((sub) => + sub + .setName("grant") + .setDescription("Grant a VPS permission to a Discord Role") + .addRoleOption((opt) => + opt.setName("role").setDescription("Target Discord Role").setRequired(true) + ) + .addStringOption((opt) => + opt + .setName("permission") + .setDescription("Permission action to grant") + .setRequired(true) + .addChoices(...PERMISSION_CHOICES) + ) + ) + .addSubcommand((sub) => + sub + .setName("revoke") + .setDescription("Revoke a VPS permission from a Discord Role") + .addRoleOption((opt) => + opt.setName("role").setDescription("Target Discord Role").setRequired(true) + ) + .addStringOption((opt) => + opt + .setName("permission") + .setDescription("Permission action to revoke") + .setRequired(true) + .addChoices(...PERMISSION_CHOICES) + ) + ) + .addSubcommand((sub) => + sub.setName("list").setDescription("List all Role -> Permission rules stored in SQLite") + ) ); export class VPSCommandHandler { private vpsService: VPSService; + private permissionSource: PermissionSource; - constructor(vpsService?: VPSService) { + constructor(vpsService?: VPSService, permissionSource?: PermissionSource) { + if (!vpsService) { + getDataConfig(); + } this.vpsService = vpsService || new VPSService(); + this.permissionSource = + permissionSource || createDefaultPermissionConfig(process.env.DEVOPS_ROLE_ID); } /** - * Main router for `/vps` subcommands. + * Main router for `/vps` subcommands with centralized action-based authorization. */ public async handle(interaction: ChatInputCommandInteraction): Promise { + const subcommandGroup = interaction.options.getSubcommandGroup(false); const subcommand = interaction.options.getSubcommand(); try { + if (subcommandGroup === "perm") { + await this.handlePermGroup(interaction, subcommand); + return; + } + + const requiredPermission = SUBCOMMAND_PERMISSIONS[subcommand]; + if (!requiredPermission) { + await interaction.reply({ + embeds: [createErrorEmbed("Unknown Subcommand", "The requested subcommand is not recognized.")], + ephemeral: true, + }); + return; + } + + const authResult = authorizeAction(interaction, requiredPermission, this.permissionSource); + if (!authResult.authorized) { + this.recordAudit(interaction, requiredPermission, subcommand, "DENIED", authResult.reason); + await interaction.reply({ + embeds: [ + createErrorEmbed( + "Unauthorized", + authResult.reason || "You do not have permission to execute this action." + ), + ], + ephemeral: true, + }); + return; + } + switch (subcommand) { case "list": await this.handleList(interaction); @@ -115,14 +231,12 @@ export class VPSCommandHandler { 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); + console.error( + `[Error in /vps ${subcommandGroup ? `${subcommandGroup} ` : ""}${subcommand}]:`, + (error as Error).message + ); const errorEmbed = createErrorEmbed( "Internal Processing Error", @@ -137,10 +251,239 @@ export class VPSCommandHandler { } } + private recordAudit( + interaction: ChatInputCommandInteraction, + action: string, + target: string | undefined, + status: "ALLOWED" | "DENIED" | "ERROR", + details?: string + ): void { + if (!(this.permissionSource instanceof PermissionRepository)) { + return; + } + try { + this.permissionSource.logAudit({ + actorId: interaction.user.id, + actorTag: interaction.user.tag, + action, + target, + status, + details, + }); + } catch { + // Never fail user interaction due to audit log write error + } + } + + private async handlePermGroup( + interaction: ChatInputCommandInteraction, + subcommand: string + ): Promise { + if (!interaction.guildId || !interaction.member) { + await interaction.reply({ + embeds: [ + createErrorEmbed( + "Unauthorized", + "This command can only be executed within a Discord Server (Guild)." + ), + ], + ephemeral: true, + }); + return; + } + + if (!hasAdministratorPermission(interaction.member)) { + this.recordAudit( + interaction, + `vps:perm:${subcommand}`, + undefined, + "DENIED", + "Non-administrator attempted to manage permissions" + ); + await interaction.reply({ + embeds: [ + createErrorEmbed( + "Admin Only", + "Only Discord Server Administrators can manage role permissions." + ), + ], + ephemeral: true, + }); + return; + } + + if (!(this.permissionSource instanceof PermissionRepository)) { + await interaction.reply({ + embeds: [ + createWarningEmbed( + "Unavailable", + "Permission management requires a SQLite-backed PermissionRepository." + ), + ], + ephemeral: true, + }); + return; + } + + const permRepo = this.permissionSource; + + if (subcommand === "list") { + const entries = permRepo.listRolePermissions(); + const embed = new EmbedBuilder() + .setTitle("🔐 Role Permissions (SQLite)") + .setColor(EMBED_COLORS.PRIMARY) + .setTimestamp(); + + if (entries.length === 0) { + embed.setDescription( + "ℹ️ No role permissions configured yet. New members currently have **0 permissions**.\nUse `/vps perm grant` to assign permissions to a Discord Role." + ); + } else { + const grouped = new Map(); + for (const entry of entries) { + const item = grouped.get(entry.roleId) || { roleName: entry.roleName, perms: [] }; + item.perms.push(`\`${entry.permissionName}\``); + grouped.set(entry.roleId, item); + } + + embed.setDescription(`Active role-permission rules in SQLite (${entries.length} rule(s)):`); + for (const [roleId, info] of grouped.entries()) { + const label = + roleId === "@everyone" + ? `@everyone (${info.roleName})` + : `${info.roleName} (<@&${roleId}> • \`${roleId}\`)`; + embed.addFields({ name: label, value: info.perms.join(", "), inline: false }); + } + } + + await interaction.reply({ embeds: [embed], ephemeral: true }); + return; + } + + const role = interaction.options.getRole("role", true); + const permissionChoice = interaction.options.getString("permission", true); + + if (subcommand === "grant") { + if (permissionChoice === "all") { + for (const perm of ALL_VPS_PERMISSIONS) { + permRepo.grantRolePermission(role.id, perm, { + roleName: role.name, + grantedBy: interaction.user.id, + }); + } + } else { + permRepo.grantRolePermission(role.id, permissionChoice as VPSPermission, { + roleName: role.name, + grantedBy: interaction.user.id, + }); + } + + this.recordAudit( + interaction, + "vps:perm:grant", + `${role.name} (${role.id})`, + "ALLOWED", + `Granted ${permissionChoice}` + ); + + const embed = new EmbedBuilder() + .setTitle("✅ Permission Granted") + .setColor(EMBED_COLORS.SUCCESS) + .setDescription( + `Granted **\`${permissionChoice}\`** to role **${role.name}** (\`${role.id}\`).` + ) + .setTimestamp(); + + await interaction.reply({ embeds: [embed], ephemeral: true }); + return; + } + + if (subcommand === "revoke") { + if (permissionChoice === "all") { + permRepo.revokeAllRolePermissions(role.id); + } else { + permRepo.revokeRolePermission(role.id, permissionChoice as VPSPermission); + } + + this.recordAudit( + interaction, + "vps:perm:revoke", + `${role.name} (${role.id})`, + "ALLOWED", + `Revoked ${permissionChoice}` + ); + + const embed = new EmbedBuilder() + .setTitle("🗑️ Permission Revoked") + .setColor(EMBED_COLORS.WARNING) + .setDescription( + `Revoked **\`${permissionChoice}\`** from role **${role.name}** (\`${role.id}\`).` + ) + .setTimestamp(); + + await interaction.reply({ embeds: [embed], ephemeral: true }); + } + } + + private buildPaginationRow(currentPage: number, totalPages: number, disabled = false) { + return new ActionRowBuilder().addComponents( + new ButtonBuilder() + .setCustomId(`vps_list_prev:${Math.max(0, currentPage - 1)}`) + .setLabel("◀️ Previous") + .setStyle(ButtonStyle.Secondary) + .setDisabled(disabled || currentPage === 0), + new ButtonBuilder() + .setCustomId(`vps_list_next:${Math.min(totalPages - 1, currentPage + 1)}`) + .setLabel("Next ▶️") + .setStyle(ButtonStyle.Secondary) + .setDisabled(disabled || currentPage >= totalPages - 1) + ); + } + + /** + * Handles stateless Previous/Next pagination button clicks in both DMs and Guild channels. + */ + public async handleListPaginationButton(interaction: ButtonInteraction): Promise { + const [, pageStr] = interaction.customId.split(":"); + const requestedPage = Number.parseInt(pageStr ?? "0", 10); + + const servers = this.vpsService.listAll(); + const pages = createVPSListPages(servers); + const targetPage = Number.isNaN(requestedPage) + ? 0 + : Math.min(Math.max(0, requestedPage), pages.length - 1); + + await interaction.update({ + embeds: [pages[targetPage]], + components: + pages.length > 1 ? [this.buildPaginationRow(targetPage, pages.length)] : [], + }); + } + private async handleList(interaction: ChatInputCommandInteraction): Promise { const servers = this.vpsService.listAll(); - const embed = createVPSListEmbed(servers); - await interaction.reply({ embeds: [embed] }); + const pages = createVPSListPages(servers); + + const payload = { + embeds: [pages[0]], + components: pages.length > 1 ? [this.buildPaginationRow(0, pages.length)] : [], + }; + + try { + await interaction.user.send(payload); + await interaction.reply({ + content: "📩 Đã gửi danh sách VPS vào tin nhắn riêng (DM) của bạn!", + ephemeral: true, + }); + } catch { + // Fallback to ephemeral reply in channel if user has DMs disabled + await interaction.reply({ + content: + "⚠️ Không thể gửi DM (có thể bạn đang tắt nhận tin nhắn riêng từ server). Danh sách chỉ hiển thị riêng cho bạn tại đây:", + ...payload, + ephemeral: true, + }); + } } private async handleInfo(interaction: ChatInputCommandInteraction): Promise { @@ -156,17 +499,40 @@ export class VPSCommandHandler { return; } - const isAuthorized = isDevOpsOrAdmin(interaction.member, process.env.DEVOPS_ROLE_ID); - const embed = createVPSInfoEmbed(vps, isAuthorized); + const canViewSensitive = hasPermission( + interaction.member, + "vps:read_sensitive", + this.permissionSource + ); + const embed = createVPSInfoEmbed(vps, canViewSensitive); await interaction.reply({ embeds: [embed] }); } private async handleSearch(interaction: ChatInputCommandInteraction): Promise { 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 canSearchIP = hasPermission( + interaction.member, + "vps:read_sensitive", + this.permissionSource + ); + const results = this.vpsService.search(query, canSearchIP); const embed = createVPSSearchEmbed(query, results); - await interaction.reply({ embeds: [embed] }); + + try { + await interaction.user.send({ embeds: [embed] }); + await interaction.reply({ + content: "📩 Đã gửi kết quả tìm kiếm vào tin nhắn riêng (DM) của bạn!", + ephemeral: true, + }); + } catch { + // Fallback to ephemeral reply if the user has DMs disabled from server members + await interaction.reply({ + content: + "⚠️ Không thể gửi DM (có thể bạn đang tắt nhận tin nhắn riêng từ server). Kết quả chỉ hiển thị riêng cho bạn tại đây:", + embeds: [embed], + ephemeral: true, + }); + } } private async handleFilter(interaction: ChatInputCommandInteraction): Promise { @@ -194,18 +560,6 @@ export class VPSCommandHandler { } private async handleConnect(interaction: ChatInputCommandInteraction): Promise { - // 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); @@ -218,7 +572,6 @@ export class VPSCommandHandler { return; } - // 3. Generate SSH Command securely const sshResult = generateSSHCommand(vps); if (!sshResult.success || !sshResult.command) { const warningEmbed = createWarningEmbed( @@ -229,7 +582,7 @@ export class VPSCommandHandler { return; } - // 4. Return Ephemeral Response with SSH details + this.recordAudit(interaction, "vps:connect", vps.name, "ALLOWED"); const connectEmbed = createSSHConnectEmbed(vps, sshResult.command); await interaction.reply({ embeds: [connectEmbed], ephemeral: true }); } diff --git a/src/config/env.ts b/src/config/env.ts index 0df7895..b7ae724 100644 --- a/src/config/env.ts +++ b/src/config/env.ts @@ -3,18 +3,40 @@ import { z } from "zod"; dotenv.config(); -export const envSchema = z.object({ +export const dataConfigSchema = z.object({ + VPS_DB_PATH: z.string().trim().min(1).default("data/vps.db"), +}); + +export const envSchema = dataConfigSchema.extend({ 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 DataConfig = z.infer; export type EnvConfig = z.infer; let cachedEnv: EnvConfig | null = null; +/** + * Validates and returns only database-related environment variables. + * Safe to call in unit tests without Discord bot credentials. + */ +export function getDataConfig(): DataConfig { + const result = dataConfigSchema.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 data configuration: ${errorMessages}`); + } + return result.data; +} + +/** + * Validates and caches full application environment configuration. + */ export function getEnv(): EnvConfig { if (cachedEnv) { return cachedEnv; diff --git a/src/index.ts b/src/index.ts index b5f3296..74ba997 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,11 +1,14 @@ -import { Client, Events, GatewayIntentBits } from "discord.js"; +import { Client, Events, GatewayIntentBits, Partials } from "discord.js"; import { VPSCommandHandler } from "./commands/vps.command.js"; import { getEnv } from "./config/env.js"; +import { PermissionRepository } from "./repositories/permission.repository.js"; +import { VPSRepository } from "./repositories/vps.repository.js"; +import { VPSService } from "./services/vps.service.js"; async function bootstrap() { console.log("⚡ Starting VPS Inventory Assistant Discord Bot..."); - // Validate environment configuration + // 1. Validate environment configuration up front let env; try { env = getEnv(); @@ -14,12 +17,39 @@ async function bootstrap() { process.exit(1); } - // Initialize Discord Client with minimal required intents for slash commands - const client = new Client({ - intents: [GatewayIntentBits.Guilds], - }); + // 2. Initialize SQLite data sources up front (VPS inventory & Permission tables) + let vpsRepository: VPSRepository; + let permissionRepository: PermissionRepository; + try { + vpsRepository = new VPSRepository(env.VPS_DB_PATH); + vpsRepository.init(); + const seededVps = vpsRepository.seedIfEmpty(); + const vpsRecords = vpsRepository.getAll(); - const commandHandler = new VPSCommandHandler(); + permissionRepository = new PermissionRepository(env.VPS_DB_PATH); + permissionRepository.init(); + const seededPerms = permissionRepository.seedIfEmpty(env.DEVOPS_ROLE_ID); + const rolePerms = permissionRepository.listRolePermissions(); + + if (seededVps > 0 || seededPerms > 0) { + console.log(`🌱 Initialized SQLite seed data (${seededVps} VPS, ${seededPerms} permission rules).`); + } + console.log( + `🗄️ Connected to SQLite (${env.VPS_DB_PATH}) — ${vpsRecords.length} VPS, ${rolePerms.length} role-permission rule(s).` + ); + } catch (err) { + console.error("❌ Failed to initialize SQLite database:", (err as Error).message); + process.exit(1); + } + + const vpsService = new VPSService(vpsRepository); + const commandHandler = new VPSCommandHandler(vpsService, permissionRepository); + + // 3. Initialize Discord Client with minimal required intents for slash commands & DM buttons + const client = new Client({ + intents: [GatewayIntentBits.Guilds, GatewayIntentBits.DirectMessages], + partials: [Partials.Channel], + }); // Ready event client.once(Events.ClientReady, (readyClient) => { @@ -30,12 +60,13 @@ async function bootstrap() { // Interaction Create event client.on(Events.InteractionCreate, async (interaction) => { - if (!interaction.isChatInputCommand()) { + if (interaction.isChatInputCommand() && interaction.commandName === "vps") { + await commandHandler.handle(interaction); return; } - if (interaction.commandName === "vps") { - await commandHandler.handle(interaction); + if (interaction.isButton() && interaction.customId.startsWith("vps_list_")) { + await commandHandler.handleListPaginationButton(interaction); } }); @@ -43,7 +74,9 @@ async function bootstrap() { const handleShutdown = (signal: string) => { console.log(`\n🛑 Received ${signal}. Shutting down gracefully...`); client.destroy(); - console.log("👋 Discord client disconnected. Goodbye!"); + vpsRepository.close(); + permissionRepository.close(); + console.log("👋 Discord client & SQLite closed. Goodbye!"); process.exit(0); }; @@ -55,6 +88,8 @@ async function bootstrap() { await client.login(env.DISCORD_TOKEN); } catch (err) { console.error("❌ Failed to log in to Discord:", (err as Error).message); + vpsRepository.close(); + permissionRepository.close(); process.exit(1); } } diff --git a/src/repositories/permission.repository.ts b/src/repositories/permission.repository.ts new file mode 100644 index 0000000..9a5ce6f --- /dev/null +++ b/src/repositories/permission.repository.ts @@ -0,0 +1,353 @@ +import fs from "node:fs"; +import path from "node:path"; +import { DatabaseSync } from "node:sqlite"; +import { getDataConfig } from "../config/env.js"; +import { ALL_VPS_PERMISSIONS, VPSPermission } from "../utils/permissions.js"; + +export interface RolePermissionEntry { + roleId: string; + roleName: string; + permissionName: VPSPermission; + grantedBy: string | null; + grantedAt: string; +} + +export type AuditStatus = "ALLOWED" | "DENIED" | "ERROR"; + +export interface AuditLogInput { + actorId: string; + actorTag: string; + action: string; + target?: string; + status: AuditStatus; + details?: string; +} + +export interface AuditLogEntry extends AuditLogInput { + id: number; + createdAt: string; +} + +const PERMISSION_CATALOG: ReadonlyArray<{ name: VPSPermission; description: string }> = [ + { name: "vps:list", description: "List all VPS servers (/vps list)" }, + { name: "vps:info", description: "View detailed VPS specs (/vps info)" }, + { name: "vps:search", description: "Search VPS by name (/vps search)" }, + { name: "vps:filter", description: "Filter VPS by provider or environment (/vps filter)" }, + { name: "vps:stats", description: "View aggregate VPS inventory statistics (/vps stats)" }, + { name: "vps:read_sensitive", description: "View IP/SSH user in info and search by IP" }, + { name: "vps:connect", description: "Generate SSH connection commands (/vps connect)" }, + { name: "vps:add", description: "Add new VPS records (/vps add)" }, + { name: "vps:update", description: "Update existing VPS records (/vps update)" }, + { name: "vps:delete", description: "Delete VPS records (/vps delete)" }, +]; + +export const DEFAULT_GUILD_ROLE_SCOPE = "@everyone"; + +export class PermissionRepository { + private dbPath: string; + private db: DatabaseSync | null = null; + + constructor(dbPath?: string) { + const configuredPath = dbPath || getDataConfig().VPS_DB_PATH; + this.dbPath = + configuredPath === ":memory:" + ? ":memory:" + : path.resolve(process.cwd(), configuredPath); + } + + /** + * Opens SQLite connection with strict Foreign Keys & WAL mode and creates RBAC + Audit tables. + */ + public init(): void { + if (this.db) { + return; + } + + try { + if (this.dbPath !== ":memory:") { + fs.mkdirSync(path.dirname(this.dbPath), { recursive: true }); + } + + this.db = new DatabaseSync(this.dbPath); + this.db.exec(` + PRAGMA foreign_keys = ON; + ${this.dbPath !== ":memory:" ? "PRAGMA journal_mode = WAL;" : ""} + + CREATE TABLE IF NOT EXISTS roles ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + description TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')) + ); + + CREATE TABLE IF NOT EXISTS permissions ( + name TEXT PRIMARY KEY, + description TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS role_permissions ( + role_id TEXT NOT NULL, + permission_name TEXT NOT NULL, + granted_by TEXT, + granted_at TEXT NOT NULL DEFAULT (datetime('now')), + PRIMARY KEY (role_id, permission_name), + FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE, + FOREIGN KEY (permission_name) REFERENCES permissions(name) ON DELETE CASCADE + ); + + CREATE INDEX IF NOT EXISTS idx_role_permissions_perm + ON role_permissions(permission_name); + + CREATE TABLE IF NOT EXISTS audit_logs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + actor_id TEXT NOT NULL, + actor_tag TEXT NOT NULL, + action TEXT NOT NULL, + target TEXT, + status TEXT NOT NULL CHECK (status IN ('ALLOWED', 'DENIED', 'ERROR')), + details TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')) + ); + + CREATE INDEX IF NOT EXISTS idx_audit_logs_created_at + ON audit_logs(created_at DESC); + `); + } catch (err) { + throw new Error(`Failed to initialize SQLite permission tables: ${(err as Error).message}`); + } + } + + public getDb(): DatabaseSync { + if (!this.db) { + this.init(); + } + return this.db!; + } + + /** + * Inserts or updates a Discord role record in the `roles` table. + */ + public upsertRole(roleId: string, name: string, description?: string): void { + const db = this.getDb(); + db.prepare( + `INSERT INTO roles (id, name, description) + VALUES (?, ?, ?) + ON CONFLICT(id) DO UPDATE SET + name = excluded.name, + description = COALESCE(excluded.description, roles.description)` + ).run(roleId.trim(), name.trim(), description ?? null); + } + + /** + * Seeds the permission catalog, base roles, and default DevOps Role -> Permission mappings if empty. + */ + public seedIfEmpty(devopsRoleId?: string): number { + const db = this.getDb(); + + const insertPerm = db.prepare(` + INSERT OR IGNORE INTO permissions (name, description) + VALUES (?, ?) + `); + for (const perm of PERMISSION_CATALOG) { + insertPerm.run(perm.name, perm.description); + } + + // Ensure @everyone exists in roles catalog (with 0 default permissions for zero-trust) + this.upsertRole(DEFAULT_GUILD_ROLE_SCOPE, "Everyone", "Default Discord server scope (zero-trust: no permissions by default)"); + + const countRow = db + .prepare("SELECT COUNT(*) AS count FROM role_permissions") + .get() as { count: number }; + + if (countRow.count > 0) { + return 0; + } + + let inserted = 0; + + const insertRolePerm = db.prepare(` + INSERT OR IGNORE INTO role_permissions (role_id, permission_name, granted_by) + VALUES (?, ?, ?) + `); + + const seedRoleWithPermissions = ( + roleId: string, + roleName: string, + description: string, + perms: readonly VPSPermission[] + ) => { + this.upsertRole(roleId, roleName, description); + for (const perm of perms) { + insertRolePerm.run(roleId, perm, "system-seed"); + inserted += 1; + } + }; + + // Sample roles for workshop demo (alongside @everyone zero-trust) + seedRoleWithPermissions( + "role-viewer-demo", + "Viewer", + "Basic read-only role: list, info, and stats (IP hidden)", + ["vps:list", "vps:info", "vps:stats"] + ); + + seedRoleWithPermissions( + "role-operator-demo", + "Operator", + "Operations role: full lookup + sensitive IP visibility (no SSH connect)", + ["vps:list", "vps:info", "vps:search", "vps:filter", "vps:stats", "vps:read_sensitive"] + ); + + seedRoleWithPermissions( + "role-auditor-demo", + "Auditor", + "Security audit role: list, info, stats, and sensitive IP review", + ["vps:list", "vps:info", "vps:stats", "vps:read_sensitive"] + ); + + if (devopsRoleId && devopsRoleId.trim() !== "") { + seedRoleWithPermissions( + devopsRoleId.trim(), + "DevOps", + "Full DevOps & infrastructure role configured via DEVOPS_ROLE_ID", + ALL_VPS_PERMISSIONS + ); + } + + return inserted; + } + + /** + * Resolves all granted permissions for the given Discord role IDs (including `@everyone`). + */ + public getPermissionsForRoles(roleIds: string[]): Set { + const db = this.getDb(); + const scopes = Array.from(new Set([DEFAULT_GUILD_ROLE_SCOPE, ...roleIds])); + const placeholders = scopes.map(() => "?").join(", "); + + const rows = db + .prepare( + `SELECT DISTINCT permission_name AS permissionName + FROM role_permissions + WHERE role_id IN (${placeholders})` + ) + .all(...scopes) as Array<{ permissionName: VPSPermission }>; + + return new Set(rows.map((row) => row.permissionName)); + } + + /** + * Grants a specific action permission to a Discord role ID (atomically ensuring role exists). + */ + public grantRolePermission( + roleId: string, + permission: VPSPermission, + options?: { roleName?: string; grantedBy?: string } + ): void { + const db = this.getDb(); + const trimmedId = roleId.trim(); + const roleName = options?.roleName?.trim() || trimmedId; + + db.exec("BEGIN"); + try { + this.upsertRole(trimmedId, roleName); + db.prepare( + `INSERT OR IGNORE INTO role_permissions (role_id, permission_name, granted_by) + VALUES (?, ?, ?)` + ).run(trimmedId, permission, options?.grantedBy ?? null); + db.exec("COMMIT"); + } catch (err) { + db.exec("ROLLBACK"); + throw err; + } + } + + /** + * Revokes a specific action permission from a Discord role ID. + */ + public revokeRolePermission(roleId: string, permission: VPSPermission): void { + const db = this.getDb(); + db.prepare( + `DELETE FROM role_permissions WHERE role_id = ? AND permission_name = ?` + ).run(roleId.trim(), permission); + } + + /** + * Revokes all action permissions from a Discord role ID. + */ + public revokeAllRolePermissions(roleId: string): void { + const db = this.getDb(); + db.prepare(`DELETE FROM role_permissions WHERE role_id = ?`).run(roleId.trim()); + } + + /** + * Lists all configured role-to-permission mappings joined with role names. + */ + public listRolePermissions(): RolePermissionEntry[] { + const db = this.getDb(); + return db + .prepare( + `SELECT + rp.role_id AS roleId, + r.name AS roleName, + rp.permission_name AS permissionName, + rp.granted_by AS grantedBy, + rp.granted_at AS grantedAt + FROM role_permissions rp + INNER JOIN roles r ON rp.role_id = r.id + ORDER BY r.name ASC, rp.permission_name ASC` + ) + .all() as unknown as RolePermissionEntry[]; + } + + /** + * Records a security/authorization audit log entry. + */ + public logAudit(entry: AuditLogInput): void { + const db = this.getDb(); + db.prepare( + `INSERT INTO audit_logs (actor_id, actor_tag, action, target, status, details) + VALUES (?, ?, ?, ?, ?, ?)` + ).run( + entry.actorId, + entry.actorTag, + entry.action, + entry.target ?? null, + entry.status, + entry.details ?? null + ); + } + + /** + * Retrieves the most recent audit log entries. + */ + public getRecentAuditLogs(limit = 20): AuditLogEntry[] { + const db = this.getDb(); + return db + .prepare( + `SELECT + id, + actor_id AS actorId, + actor_tag AS actorTag, + action, + target, + status, + details, + created_at AS createdAt + FROM audit_logs + ORDER BY id DESC + LIMIT ?` + ) + .all(limit) as unknown as AuditLogEntry[]; + } + + /** + * Closes the SQLite database connection. + */ + public close(): void { + if (this.db) { + this.db.close(); + this.db = null; + } + } +} diff --git a/src/repositories/vps.repository.ts b/src/repositories/vps.repository.ts index 51cea04..1818e9b 100644 --- a/src/repositories/vps.repository.ts +++ b/src/repositories/vps.repository.ts @@ -1,81 +1,294 @@ import fs from "node:fs"; import path from "node:path"; -import { VPS, vpsListSchema } from "../types/vps.js"; +import { DatabaseSync } from "node:sqlite"; +import { getDataConfig } from "../config/env.js"; +import { VPS, vpsListSchema, vpsSchema } from "../types/vps.js"; -export class VPSRepository { - private filePath: string; - private cache: VPS[] | null = null; +/** + * Storage-agnostic repository contract. + */ +export interface IVPSRepository { + getAll(): VPS[]; + getById(id: string): VPS | undefined; + getByName(name: string): VPS | undefined; + close?(): void; +} - constructor(filePath?: string) { - this.filePath = filePath || process.env.VPS_DATA_PATH || path.resolve(process.cwd(), "data/vps.json"); +interface VPSRow { + id: string; + name: string; + provider: string; + region: string; + environment: string; + cpu: number; + ramGB: number; + diskGB: number; + ip: string | null; + sshUser: string | null; + sshPort: number | null; +} + +const CORE_SEED_RECORDS: readonly VPS[] = [ + { + 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", + }, +]; + +const PROVIDERS = ["Vultr", "DigitalOcean", "AWS", "Linode", "Hetzner"] as const; +const REGIONS = ["Singapore", "Tokyo", "Frankfurt", "US-East"] as const; +const ENVIRONMENTS = ["Production", "Staging", "Development"] as const; +const DOC_PREFIXES = ["203.0.113", "198.51.100", "192.0.2"] as const; +const CPU_TIERS = [2, 4, 8] as const; + +function buildGeneratedSeedRecords(totalTarget = 100): VPS[] { + const records: VPS[] = [...CORE_SEED_RECORDS]; + + for (let i = records.length + 1; i <= totalTarget; i++) { + const num = String(i).padStart(3, "0"); + const env = ENVIRONMENTS[(i - 1) % ENVIRONMENTS.length]; + const envShort = env === "Production" ? "prod" : env === "Staging" ? "stg" : "dev"; + const provider = PROVIDERS[(i - 1) % PROVIDERS.length]; + const region = REGIONS[(i - 1) % REGIONS.length]; + const cpu = CPU_TIERS[(i - 1) % CPU_TIERS.length]; + const ramGB = cpu * 2; + const diskGB = cpu * 40; + const ipPrefix = DOC_PREFIXES[(i - 1) % DOC_PREFIXES.length]; + const lastOctet = ((i * 7) % 240) + 10; + + records.push({ + id: `vps-${num}`, + name: `app-${envShort}-${num}`, + provider, + region, + environment: env, + cpu, + ramGB, + diskGB, + ip: `${ipPrefix}.${lastOctet}`, + sshUser: env === "Production" ? "deploy" : "ubuntu", + sshPort: env === "Staging" ? 2222 : 22, + }); + } + + return records; +} + +export const SEED_VPS_RECORDS: readonly VPS[] = buildGeneratedSeedRecords(100); + +const SELECT_COLUMNS = ` + id, + name, + provider, + region, + environment, + cpu, + ram_gb AS ramGB, + disk_gb AS diskGB, + ip, + ssh_user AS sshUser, + ssh_port AS sshPort +`; + +function mapRowToVPS(row: VPSRow): VPS { + const candidate = { + id: row.id, + name: row.name, + provider: row.provider, + region: row.region, + environment: row.environment, + cpu: row.cpu, + ramGB: row.ramGB, + diskGB: row.diskGB, + ip: row.ip ?? undefined, + sshUser: row.sshUser ?? undefined, + sshPort: row.sshPort ?? undefined, + }; + return vpsSchema.parse(candidate); +} + +export class VPSRepository implements IVPSRepository { + private dbPath: string; + private db: DatabaseSync | null = null; + + constructor(dbPath?: string) { + const configuredPath = dbPath || getDataConfig().VPS_DB_PATH; + this.dbPath = + configuredPath === ":memory:" + ? ":memory:" + : path.resolve(process.cwd(), configuredPath); } /** - * Loads and validates VPS records from the JSON data file. + * Opens the SQLite database connection and ensures the `vps` table exists. */ - public load(): VPS[] { - const resolvedPath = path.resolve(this.filePath); - - if (!fs.existsSync(resolvedPath)) { - throw new Error(`Inventory data file not found at path: ${resolvedPath}`); + public init(): void { + if (this.db) { + return; } - let rawData: string; try { - rawData = fs.readFileSync(resolvedPath, "utf-8"); + if (this.dbPath !== ":memory:") { + fs.mkdirSync(path.dirname(this.dbPath), { recursive: true }); + } + + this.db = new DatabaseSync(this.dbPath); + this.db.exec(` + PRAGMA foreign_keys = ON; + ${this.dbPath !== ":memory:" ? "PRAGMA journal_mode = WAL;" : ""} + CREATE TABLE IF NOT EXISTS vps ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL UNIQUE COLLATE NOCASE, + provider TEXT NOT NULL, + region TEXT NOT NULL, + environment TEXT NOT NULL CHECK (environment IN ('Production', 'Staging', 'Development')), + cpu INTEGER NOT NULL CHECK (cpu > 0), + ram_gb REAL NOT NULL CHECK (ram_gb > 0), + disk_gb REAL NOT NULL CHECK (disk_gb > 0), + ip TEXT, + ssh_user TEXT, + ssh_port INTEGER CHECK (ssh_port IS NULL OR (ssh_port >= 1 AND ssh_port <= 65535)) + ); + `); } catch (err) { - throw new Error(`Failed to read inventory data file: ${(err as Error).message}`); + throw new Error(`Failed to initialize SQLite database: ${(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}`); + private getDb(): DatabaseSync { + if (!this.db) { + this.init(); } - - 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; + return this.db!; } /** - * Returns all VPS records. + * Inserts default workshop seed records if the `vps` table is currently empty. + * Returns the number of inserted records. + */ + public seedIfEmpty(records: readonly VPS[] = SEED_VPS_RECORDS): number { + const db = this.getDb(); + const countRow = db.prepare("SELECT COUNT(*) AS count FROM vps").get() as { count: number }; + + if (countRow.count > 0) { + return 0; + } + + const insert = db.prepare(` + INSERT INTO vps (id, name, provider, region, environment, cpu, ram_gb, disk_gb, ip, ssh_user, ssh_port) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `); + + for (const vps of records) { + insert.run( + vps.id, + vps.name, + vps.provider, + vps.region, + vps.environment, + vps.cpu, + vps.ramGB, + vps.diskGB, + vps.ip ?? null, + vps.sshUser ?? null, + vps.sshPort ?? null + ); + } + + return records.length; + } + + /** + * Returns all VPS records from SQLite. */ public getAll(): VPS[] { - if (!this.cache) { - return this.load(); + try { + const db = this.getDb(); + const rows = db.prepare(`SELECT ${SELECT_COLUMNS} FROM vps ORDER BY rowid ASC`).all() as unknown as VPSRow[]; + const mapped = rows.map(mapRowToVPS); + return vpsListSchema.parse(mapped); + } catch (err) { + throw new Error(`Failed to query VPS records: ${(err as Error).message}`); } - return this.cache; } /** * Finds a VPS by exact ID. */ public getById(id: string): VPS | undefined { - return this.getAll().find((vps) => vps.id === id); + try { + const db = this.getDb(); + const row = db + .prepare(`SELECT ${SELECT_COLUMNS} FROM vps WHERE id = ? LIMIT 1`) + .get(id) as unknown as VPSRow | undefined; + + return row ? mapRowToVPS(row) : undefined; + } catch (err) { + throw new Error(`Failed to query VPS by ID: ${(err as Error).message}`); + } } /** * 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); + const trimmed = name.trim(); + if (!trimmed) { + return undefined; + } + + try { + const db = this.getDb(); + const row = db + .prepare(`SELECT ${SELECT_COLUMNS} FROM vps WHERE LOWER(name) = LOWER(?) LIMIT 1`) + .get(trimmed) as unknown as VPSRow | undefined; + + return row ? mapRowToVPS(row) : undefined; + } catch (err) { + throw new Error(`Failed to query VPS by name: ${(err as Error).message}`); + } } /** - * Force reloads the data from disk. + * Closes the SQLite database connection. */ - public reload(): VPS[] { - this.cache = null; - return this.load(); + public close(): void { + if (this.db) { + this.db.close(); + this.db = null; + } } } diff --git a/src/seed.ts b/src/seed.ts new file mode 100644 index 0000000..0c227a2 --- /dev/null +++ b/src/seed.ts @@ -0,0 +1,36 @@ +import { getDataConfig } from "./config/env.js"; +import { PermissionRepository } from "./repositories/permission.repository.js"; +import { VPSRepository } from "./repositories/vps.repository.js"; + +function seedDatabase() { + const { VPS_DB_PATH } = getDataConfig(); + const vpsRepo = new VPSRepository(VPS_DB_PATH); + const permRepo = new PermissionRepository(VPS_DB_PATH); + + try { + vpsRepo.init(); + const seededVps = vpsRepo.seedIfEmpty(); + const totalVps = vpsRepo.getAll().length; + + permRepo.init(); + const seededPerms = permRepo.seedIfEmpty(process.env.DEVOPS_ROLE_ID); + const totalRolePerms = permRepo.listRolePermissions().length; + + if (seededVps > 0) { + console.log(`✅ Seeded ${seededVps} VPS record(s) into SQLite (${VPS_DB_PATH}).`); + } else { + console.log(`ℹ️ Table 'vps' already contains ${totalVps} record(s).`); + } + + if (seededPerms > 0) { + console.log(`✅ Seeded ${seededPerms} role-permission mapping(s) into SQLite (${VPS_DB_PATH}).`); + } else { + console.log(`ℹ️ Table 'role_permissions' already contains ${totalRolePerms} mapping(s).`); + } + } finally { + vpsRepo.close(); + permRepo.close(); + } +} + +seedDatabase(); diff --git a/src/services/vps.service.ts b/src/services/vps.service.ts index 52f9ee7..a3af962 100644 --- a/src/services/vps.service.ts +++ b/src/services/vps.service.ts @@ -1,10 +1,10 @@ -import { VPSRepository } from "../repositories/vps.repository.js"; +import { IVPSRepository, VPSRepository } from "../repositories/vps.repository.js"; import { VPS, VPSFilterOptions, VPSStats } from "../types/vps.js"; export class VPSService { - private repository: VPSRepository; + private repository: IVPSRepository; - constructor(repository?: VPSRepository) { + constructor(repository?: IVPSRepository) { this.repository = repository || new VPSRepository(); } diff --git a/src/utils/embeds.ts b/src/utils/embeds.ts index 1e9caec..ec11551 100644 --- a/src/utils/embeds.ts +++ b/src/utils/embeds.ts @@ -8,59 +8,111 @@ export const EMBED_COLORS = { 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}` }); +export const DISCORD_EMBED_LIMITS = { + MAX_FIELDS: 25, + MAX_TOTAL_CHARS: 6000, + SAFE_PAGE_CHARS: 5400, // Leave headroom for title, description, and footer + DEFAULT_PAGE_SIZE: 10, +} as const; +function formatEnvironmentBadge(env: VPS["environment"]): string { + if (env === "Production") return "🔴 Production"; + if (env === "Staging") return "🟡 Staging"; + return "🟢 Development"; +} + +function formatVPSListField(vps: VPS): { name: string; value: string; inline: boolean } { + const envBadge = formatEnvironmentBadge(vps.environment); + const value = [ + `• **Provider:** ${vps.provider} (${vps.region})`, + `• **Environment:** ${envBadge}`, + `• **Hardware:** ${vps.cpu} vCPU | ${vps.ramGB} GB RAM | ${vps.diskGB} GB Disk`, + ].join("\n"); + + return { + name: `📌 ${vps.name}`, + value, + inline: false, + }; +} + +/** + * Splits a list of VPS records into Discord-safe Embed pages. + * Respects Discord limits (max 25 fields and max 6,000 total characters per embed). + */ +export function createVPSListPages( + servers: VPS[], + pageSize: number = DISCORD_EMBED_LIMITS.DEFAULT_PAGE_SIZE +): EmbedBuilder[] { if (servers.length === 0) { - embed.setDescription("ℹ️ No VPS records found in the inventory."); - return embed; + const emptyEmbed = new EmbedBuilder() + .setTitle("🖥️ VPS Inventory Overview") + .setColor(EMBED_COLORS.PRIMARY) + .setDescription("ℹ️ No VPS records found in the inventory.") + .setTimestamp() + .setFooter({ text: "Total Servers: 0" }); + return [emptyEmbed]; } - embed.setDescription( - `Displaying **${servers.length}** VPS server(s) currently managed in the inventory:\n` - ); + const effectivePageSize = Math.min(Math.max(1, pageSize), DISCORD_EMBED_LIMITS.MAX_FIELDS); + const chunks: Array> = []; + let currentChunk: Array<{ name: string; value: string; inline: boolean }> = []; + let currentChars = 0; for (const vps of servers) { - const envBadge = - vps.environment === "Production" - ? "🔴 Production" - : vps.environment === "Staging" - ? "🟡 Staging" - : "🟢 Development"; + const field = formatVPSListField(vps); + const fieldChars = field.name.length + field.value.length; - const value = [ - `• **Provider:** ${vps.provider} (${vps.region})`, - `• **Environment:** ${envBadge}`, - `• **Hardware:** ${vps.cpu} vCPU | ${vps.ramGB} GB RAM | ${vps.diskGB} GB Disk`, - ].join("\n"); + const wouldExceedCount = currentChunk.length >= effectivePageSize; + const wouldExceedChars = currentChars + fieldChars > DISCORD_EMBED_LIMITS.SAFE_PAGE_CHARS; - embed.addFields({ - name: `📌 ${vps.name}`, - value, - inline: false, - }); + if (currentChunk.length > 0 && (wouldExceedCount || wouldExceedChars)) { + chunks.push(currentChunk); + currentChunk = []; + currentChars = 0; + } + + currentChunk.push(field); + currentChars += fieldChars; } - return embed; + if (currentChunk.length > 0) { + chunks.push(currentChunk); + } + + const totalPages = chunks.length; + + return chunks.map((fields, index) => { + const pageNum = index + 1; + const footerText = + totalPages > 1 + ? `Page ${pageNum}/${totalPages} • Total Servers: ${servers.length}` + : `Total Servers: ${servers.length}`; + + return new EmbedBuilder() + .setTitle("🖥️ VPS Inventory Overview") + .setColor(EMBED_COLORS.PRIMARY) + .setDescription( + `Displaying **${servers.length}** VPS server(s) currently managed in the inventory:\n` + ) + .addFields(fields) + .setTimestamp() + .setFooter({ text: footerText }); + }); +} + +/** + * Creates a single embed for the inventory list command (first page). + */ +export function createVPSListEmbed(servers: VPS[]): EmbedBuilder { + return createVPSListPages(servers)[0]; } /** * 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"; + const envBadge = formatEnvironmentBadge(vps.environment); let ipDisplay = "Not configured"; if (vps.ip) { @@ -105,7 +157,7 @@ export function createVPSInfoEmbed(vps: VPS, isAuthorized = false): EmbedBuilder } /** - * Creates an embed for VPS search results. + * Creates an embed for VPS search results (capped safely within Discord's 25-field limit). */ export function createVPSSearchEmbed(query: string, results: VPS[]): EmbedBuilder { const embed = new EmbedBuilder() @@ -119,11 +171,19 @@ export function createVPSSearchEmbed(query: string, results: VPS[]): EmbedBuilde .setDescription(`No VPS found matching query: **"${query}"**.\nTry another keyword or IP.`); } + const displayed = results.slice(0, DISCORD_EMBED_LIMITS.MAX_FIELDS); + const extraNote = + results.length > DISCORD_EMBED_LIMITS.MAX_FIELDS + ? `\n_Showing first ${DISCORD_EMBED_LIMITS.MAX_FIELDS} of ${results.length} matches. Refine your query to narrow results._` + : ""; + embed .setColor(EMBED_COLORS.PRIMARY) - .setDescription(`Found **${results.length}** server(s) matching search keyword: **"${query}"**\n`); + .setDescription( + `Found **${results.length}** server(s) matching search keyword: **"${query}"**${extraNote}\n` + ); - for (const vps of results) { + for (const vps of displayed) { 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`, @@ -135,7 +195,7 @@ export function createVPSSearchEmbed(query: string, results: VPS[]): EmbedBuilde } /** - * Creates an embed for filtered VPS results. + * Creates an embed for filtered VPS results (capped safely within Discord's 25-field limit). */ export function createVPSFilterEmbed(filters: VPSFilterOptions, results: VPS[]): EmbedBuilder { const activeFilters: string[] = []; @@ -157,13 +217,19 @@ export function createVPSFilterEmbed(filters: VPSFilterOptions, results: VPS[]): ); } + const displayed = results.slice(0, DISCORD_EMBED_LIMITS.MAX_FIELDS); + const extraNote = + results.length > DISCORD_EMBED_LIMITS.MAX_FIELDS + ? `\n_Showing first ${DISCORD_EMBED_LIMITS.MAX_FIELDS} of ${results.length} matches._` + : ""; + embed .setColor(EMBED_COLORS.PRIMARY) .setDescription( - `Active Filter: ${filterSummary}\nFound **${results.length}** matching server(s):\n` + `Active Filter: ${filterSummary}\nFound **${results.length}** matching server(s):${extraNote}\n` ); - for (const vps of results) { + for (const vps of displayed) { 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`, @@ -178,13 +244,15 @@ export function createVPSFilterEmbed(filters: VPSFilterOptions, results: VPS[]): * 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 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"; + const envBreakdown = + Object.entries(stats.byEnvironment) + .map(([env, count]) => `• **${env}:** ${count} server(s)`) + .join("\n") || "None"; return new EmbedBuilder() .setTitle("📊 VPS Inventory Statistics") diff --git a/src/utils/permissions.ts b/src/utils/permissions.ts index c579cdf..2983c66 100644 --- a/src/utils/permissions.ts +++ b/src/utils/permissions.ts @@ -6,67 +6,172 @@ import { } 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. + * Granular action-based permissions for VPS Inventory operations (one permission per feature). */ -export function isDevOpsOrAdmin( - member: GuildMember | ChatInputCommandInteraction["member"], - devopsRoleId?: string -): boolean { - if (!member) { - return false; - } +export type VPSPermission = + | "vps:list" + | "vps:info" + | "vps:search" + | "vps:filter" + | "vps:stats" + | "vps:read_sensitive" + | "vps:connect" + | "vps:add" + | "vps:update" + | "vps:delete"; - // 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 - } - } +export const ALL_VPS_PERMISSIONS: readonly VPSPermission[] = [ + "vps:list", + "vps:info", + "vps:search", + "vps:filter", + "vps:stats", + "vps:read_sensitive", + "vps:connect", + "vps:add", + "vps:update", + "vps:delete", +] as const; - // 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 RolePermissionConfig { + /** Base permissions granted to any verified member inside the guild */ + defaultGuildPermissions: readonly VPSPermission[]; + /** Mapping from Discord Role ID to granted action permissions */ + rolePermissions: Record; + /** Whether Discord Server Administrators automatically receive all permissions */ + adminBypass?: boolean; } +/** + * Storage-backed permission provider contract (implemented by SQLite PermissionRepository). + */ +export interface IPermissionStore { + getPermissionsForRoles(roleIds: string[]): Set; + adminBypass?: boolean; +} + +export type PermissionSource = RolePermissionConfig | IPermissionStore; + export interface AuthorizationResult { authorized: boolean; reason?: string; } /** - * Validates interaction context and checks DevOps/Admin authorization. + * Builds the default Role -> Permission mapping from environment configuration. + * Zero-trust default: unassigned members get 0 permissions. */ -export function checkDevOpsAuthorization( +export function createDefaultPermissionConfig(devopsRoleId?: string): RolePermissionConfig { + const rolePermissions: Record = {}; + + if (devopsRoleId && devopsRoleId.trim() !== "") { + rolePermissions[devopsRoleId.trim()] = [...ALL_VPS_PERMISSIONS]; + } + + return { + defaultGuildPermissions: [], + rolePermissions, + adminBypass: true, + }; +} + +function isPermissionStore(source: PermissionSource): source is IPermissionStore { + return "getPermissionsForRoles" in source && typeof source.getPermissionsForRoles === "function"; +} + +export function hasAdministratorPermission( + member: GuildMember | ChatInputCommandInteraction["member"] +): boolean { + if (!member || !("permissions" in member) || !member.permissions) { + return false; + } + + try { + if (typeof member.permissions === "string") { + const bitfield = new PermissionsBitField(BigInt(member.permissions)); + return bitfield.has(PermissionFlagsBits.Administrator); + } + if (member.permissions instanceof PermissionsBitField) { + return member.permissions.has(PermissionFlagsBits.Administrator); + } + } catch { + return false; + } + + return false; +} + +function getMemberRoleIds( + member: GuildMember | ChatInputCommandInteraction["member"] +): string[] { + if (!member || !("roles" in member) || !member.roles) { + return []; + } + + if ("cache" in member.roles && member.roles.cache) { + return Array.from(member.roles.cache.keys()); + } + + if (Array.isArray(member.roles)) { + return member.roles; + } + + return []; +} + +/** + * Resolves the full set of action permissions granted to a guild member. + */ +export function getMemberPermissions( + member: GuildMember | ChatInputCommandInteraction["member"], + source: PermissionSource +): Set { + if (!member) { + return new Set(); + } + + if (source.adminBypass !== false && hasAdministratorPermission(member)) { + return new Set(ALL_VPS_PERMISSIONS); + } + + const roleIds = getMemberRoleIds(member); + + if (isPermissionStore(source)) { + return source.getPermissionsForRoles(roleIds); + } + + const resolved = new Set(source.defaultGuildPermissions); + + for (const roleId of roleIds) { + const granted = source.rolePermissions[roleId]; + if (granted) { + for (const perm of granted) { + resolved.add(perm); + } + } + } + + return resolved; +} + +/** + * Checks whether a guild member holds a specific action permission. + */ +export function hasPermission( + member: GuildMember | ChatInputCommandInteraction["member"], + permission: VPSPermission, + source: PermissionSource +): boolean { + return getMemberPermissions(member, source).has(permission); +} + +/** + * Validates guild context and checks whether the caller has the required action permission. + */ +export function authorizeAction( interaction: ChatInputCommandInteraction, - devopsRoleId?: string + permission: VPSPermission, + source: PermissionSource ): AuthorizationResult { if (!interaction.guildId || !interaction.member) { return { @@ -75,11 +180,10 @@ export function checkDevOpsAuthorization( }; } - const authorized = isDevOpsOrAdmin(interaction.member, devopsRoleId); - if (!authorized) { + if (!hasPermission(interaction.member, permission, source)) { return { authorized: false, - reason: "Permission Denied: You must have the DevOps role or Server Administrator permissions to access SSH connection details.", + reason: `Permission Denied: You lack the required \`${permission}\` permission to perform this action.`, }; } diff --git a/tests/embeds.test.ts b/tests/embeds.test.ts new file mode 100644 index 0000000..d313da9 --- /dev/null +++ b/tests/embeds.test.ts @@ -0,0 +1,46 @@ +import { describe, it, expect } from "vitest"; +import { createVPSListPages, DISCORD_EMBED_LIMITS } from "../src/utils/embeds.js"; +import { VPS } from "../src/types/vps.js"; + +function generateMockVPSList(count: number): VPS[] { + return Array.from({ length: count }, (_, i) => ({ + id: `vps-${String(i + 1).padStart(3, "0")}`, + name: `node-prod-${String(i + 1).padStart(3, "0")}`, + provider: i % 2 === 0 ? "Vultr" : "DigitalOcean", + region: "Singapore", + environment: i % 3 === 0 ? "Production" : i % 3 === 1 ? "Staging" : "Development", + cpu: 4, + ramGB: 8, + diskGB: 160, + })); +} + +describe("Embed Pagination for Large VPS Lists", () => { + it("should return a single empty-state embed when inventory is empty", () => { + const pages = createVPSListPages([]); + expect(pages).toHaveLength(1); + expect(pages[0].data.description).toContain("No VPS records found"); + }); + + it("should split 100 VPS records into multiple pages respecting Discord Embed limits", () => { + const servers = generateMockVPSList(100); + const pages = createVPSListPages(servers); + + expect(pages.length).toBeGreaterThan(1); + expect(pages).toHaveLength(10); // 100 items / 10 per page = 10 pages + + let totalFieldsAcrossPages = 0; + for (const page of pages) { + const json = page.toJSON(); + const fieldCount = json.fields?.length ?? 0; + totalFieldsAcrossPages += fieldCount; + + expect(fieldCount).toBeLessThanOrEqual(DISCORD_EMBED_LIMITS.MAX_FIELDS); + expect(page.length).toBeLessThanOrEqual(DISCORD_EMBED_LIMITS.MAX_TOTAL_CHARS); + } + + expect(totalFieldsAcrossPages).toBe(100); + expect(pages[0].data.footer?.text).toBe("Page 1/10 • Total Servers: 100"); + expect(pages[9].data.footer?.text).toBe("Page 10/10 • Total Servers: 100"); + }); +}); diff --git a/tests/permissions.test.ts b/tests/permissions.test.ts index 8ee2d59..d41a596 100644 --- a/tests/permissions.test.ts +++ b/tests/permissions.test.ts @@ -1,113 +1,244 @@ -import { describe, it, expect } from "vitest"; +import { describe, it, expect, beforeEach, afterEach } from "vitest"; import { PermissionFlagsBits, PermissionsBitField } from "discord.js"; -import { isDevOpsOrAdmin, checkDevOpsAuthorization } from "../src/utils/permissions.js"; +import { PermissionRepository } from "../src/repositories/permission.repository.js"; +import { + ALL_VPS_PERMISSIONS, + authorizeAction, + createDefaultPermissionConfig, + getMemberPermissions, + hasPermission, + RolePermissionConfig, +} from "../src/utils/permissions.js"; -describe("Permissions Utilities", () => { +describe("Granular Action-Based Permissions System", () => { const DEVOPS_ROLE_ID = "role-devops-123"; + const VIEWER_ROLE_ID = "role-viewer-456"; + const defaultConfig = createDefaultPermissionConfig(DEVOPS_ROLE_ID); - 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); + describe("getMemberPermissions & hasPermission (in-memory config)", () => { + it("should return empty set if member is null or undefined", () => { + expect(getMemberPermissions(null as any, defaultConfig).size).toBe(0); + expect(hasPermission(undefined as any, "vps:list", defaultConfig)).toBe(false); }); - it("should return true if member has Administrator permission via PermissionsBitField", () => { + it("should grant all 10 granular permissions to Server Administrator", () => { const member = { permissions: new PermissionsBitField(PermissionFlagsBits.Administrator), roles: { cache: new Map() }, }; - expect(isDevOpsOrAdmin(member as any, DEVOPS_ROLE_ID)).toBe(true); + + for (const perm of ALL_VPS_PERMISSIONS) { + expect(hasPermission(member as any, perm, defaultConfig)).toBe(true); + } }); - it("should return true if member has Administrator permission via string bitfield", () => { + it("should grant all permissions to Administrator 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); + + expect(hasPermission(member as any, "vps:connect", defaultConfig)).toBe(true); + expect(hasPermission(member as any, "vps:delete", defaultConfig)).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" }); - + it("should grant DevOps role all 10 granular VPS permissions via role cache", () => { + const roleMap = new Map([[DEVOPS_ROLE_ID, { id: DEVOPS_ROLE_ID }]]); const member = { permissions: new PermissionsBitField(), - roles: { - cache: { - has: (id: string) => roleMap.has(id), - }, - }, + roles: { cache: roleMap }, }; - expect(isDevOpsOrAdmin(member as any, DEVOPS_ROLE_ID)).toBe(true); + + for (const perm of ALL_VPS_PERMISSIONS) { + expect(hasPermission(member as any, perm, defaultConfig)).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", () => { + it("should grant new/regular guild members zero permissions by default (zero-trust)", () => { const member = { permissions: new PermissionsBitField(), - roles: { - cache: { - has: (_id: string) => false, - }, - }, + roles: ["some-other-role"], }; - expect(isDevOpsOrAdmin(member as any, DEVOPS_ROLE_ID)).toBe(false); + + for (const perm of ALL_VPS_PERMISSIONS) { + expect(hasPermission(member as any, perm, defaultConfig)).toBe(false); + } }); - it("should fail securely (return false) if devopsRoleId is empty or not provided and member is not admin", () => { + it("should support per-feature Role -> Permission mappings", () => { + const granularConfig: RolePermissionConfig = { + defaultGuildPermissions: [], + rolePermissions: { + [VIEWER_ROLE_ID]: ["vps:list", "vps:info"], + [DEVOPS_ROLE_ID]: [...ALL_VPS_PERMISSIONS], + }, + adminBypass: true, + }; + + const noRoleMember = { permissions: "0", roles: [] }; + const viewerMember = { permissions: "0", roles: [VIEWER_ROLE_ID] }; + + expect(hasPermission(noRoleMember as any, "vps:list", granularConfig)).toBe(false); + expect(hasPermission(viewerMember as any, "vps:list", granularConfig)).toBe(true); + expect(hasPermission(viewerMember as any, "vps:info", granularConfig)).toBe(true); + expect(hasPermission(viewerMember as any, "vps:search", granularConfig)).toBe(false); + expect(hasPermission(viewerMember as any, "vps:filter", granularConfig)).toBe(false); + expect(hasPermission(viewerMember as any, "vps:stats", granularConfig)).toBe(false); + expect(hasPermission(viewerMember as any, "vps:connect", granularConfig)).toBe(false); + }); + + it("should fail securely when devopsRoleId is missing", () => { + const configWithoutDevops = createDefaultPermissionConfig(undefined); const member = { permissions: new PermissionsBitField(), roles: ["some-role"], }; - expect(isDevOpsOrAdmin(member as any, undefined)).toBe(false); - expect(isDevOpsOrAdmin(member as any, "")).toBe(false); + + expect(hasPermission(member as any, "vps:connect", configWithoutDevops)).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); + describe("authorizeAction (in-memory config)", () => { + it("should deny access when executed outside a guild (e.g. DM)", () => { + const mockInteraction = { guildId: null, member: null }; + const result = authorizeAction(mockInteraction as any, "vps:list", defaultConfig); + 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", () => { + it("should deny vps:connect for unassigned member and include missing permission in reason", () => { const mockInteraction = { guildId: "guild-123", member: { permissions: new PermissionsBitField(), - roles: { cache: { has: () => false } }, + roles: { cache: new Map() }, }, }; - const result = checkDevOpsAuthorization(mockInteraction as any, DEVOPS_ROLE_ID); + + const result = authorizeAction(mockInteraction as any, "vps:connect", defaultConfig); expect(result.authorized).toBe(false); - expect(result.reason).toContain("Permission Denied"); + expect(result.reason).toContain("vps:connect"); }); - it("should grant access when member has DevOps role in a guild", () => { + it("should allow vps:connect for member with DevOps role", () => { const mockInteraction = { guildId: "guild-123", member: { permissions: new PermissionsBitField(), - roles: { cache: { has: (id: string) => id === DEVOPS_ROLE_ID } }, + roles: { cache: new Map([[DEVOPS_ROLE_ID, { id: DEVOPS_ROLE_ID }]]) }, }, }; - const result = checkDevOpsAuthorization(mockInteraction as any, DEVOPS_ROLE_ID); + + const result = authorizeAction(mockInteraction as any, "vps:connect", defaultConfig); expect(result.authorized).toBe(true); expect(result.reason).toBeUndefined(); }); }); + + describe("SQLite PermissionRepository integration", () => { + let permRepo: PermissionRepository; + + beforeEach(() => { + permRepo = new PermissionRepository(":memory:"); + permRepo.init(); + permRepo.seedIfEmpty(DEVOPS_ROLE_ID); + }); + + afterEach(() => { + permRepo.close(); + }); + + it("should enforce zero-trust for new members and grant DevOps role all 10 permissions", () => { + const newMember = { permissions: "0", roles: ["unassigned-role"] }; + const devopsMember = { permissions: "0", roles: [DEVOPS_ROLE_ID] }; + + expect(hasPermission(newMember as any, "vps:list", permRepo)).toBe(false); + expect(hasPermission(newMember as any, "vps:connect", permRepo)).toBe(false); + + for (const perm of ALL_VPS_PERMISSIONS) { + expect(hasPermission(devopsMember as any, perm, permRepo)).toBe(true); + } + }); + + it("should isolate individual feature permissions (list vs info vs search vs add/update/delete)", () => { + const customRole = "role-custom-999"; + const customMember = { permissions: "0", roles: [customRole] }; + + permRepo.grantRolePermission(customRole, "vps:list"); + permRepo.grantRolePermission(customRole, "vps:add"); + + expect(hasPermission(customMember as any, "vps:list", permRepo)).toBe(true); + expect(hasPermission(customMember as any, "vps:add", permRepo)).toBe(true); + expect(hasPermission(customMember as any, "vps:info", permRepo)).toBe(false); + expect(hasPermission(customMember as any, "vps:search", permRepo)).toBe(false); + expect(hasPermission(customMember as any, "vps:update", permRepo)).toBe(false); + expect(hasPermission(customMember as any, "vps:delete", permRepo)).toBe(false); + + permRepo.revokeRolePermission(customRole, "vps:list"); + expect(hasPermission(customMember as any, "vps:list", permRepo)).toBe(false); + + permRepo.revokeAllRolePermissions(customRole); + expect(hasPermission(customMember as any, "vps:add", permRepo)).toBe(false); + }); + + it("should deny new members and authorize roles assigned in SQLite", () => { + const newMemberInteraction = { + guildId: "guild-123", + member: { permissions: "0", roles: [] }, + }; + const devopsInteraction = { + guildId: "guild-123", + member: { permissions: "0", roles: [DEVOPS_ROLE_ID] }, + }; + + expect(authorizeAction(newMemberInteraction as any, "vps:list", permRepo).authorized).toBe(false); + expect(authorizeAction(newMemberInteraction as any, "vps:connect", permRepo).authorized).toBe(false); + expect(authorizeAction(devopsInteraction as any, "vps:list", permRepo).authorized).toBe(true); + expect(authorizeAction(devopsInteraction as any, "vps:connect", permRepo).authorized).toBe(true); + }); + + it("should enforce strict foreign keys on role_permissions (roles and permissions)", () => { + const db = permRepo.getDb(); + + expect(() => + db + .prepare("INSERT INTO role_permissions (role_id, permission_name) VALUES (?, ?)") + .run("non-existent-role", "vps:list") + ).toThrow(/FOREIGN KEY constraint failed/); + + expect(() => + db + .prepare("INSERT INTO role_permissions (role_id, permission_name) VALUES (?, ?)") + .run(DEVOPS_ROLE_ID, "invalid:perm") + ).toThrow(/FOREIGN KEY constraint failed/); + }); + + it("should join role names and record audit logs", () => { + permRepo.grantRolePermission("role-auditor-777", "vps:info", { + roleName: "Auditor", + grantedBy: "admin-1", + }); + + const entries = permRepo.listRolePermissions(); + const auditorEntry = entries.find((e) => e.roleId === "role-auditor-777"); + expect(auditorEntry).toBeDefined(); + expect(auditorEntry?.roleName).toBe("Auditor"); + expect(auditorEntry?.grantedBy).toBe("admin-1"); + + permRepo.logAudit({ + actorId: "user-1", + actorTag: "khuong#0001", + action: "vps:connect", + target: "shop-prod-01", + status: "ALLOWED", + }); + + const logs = permRepo.getRecentAuditLogs(5); + expect(logs).toHaveLength(1); + expect(logs[0].action).toBe("vps:connect"); + expect(logs[0].status).toBe("ALLOWED"); + }); + }); }); diff --git a/tests/vps.service.test.ts b/tests/vps.service.test.ts index fb4a465..b8d8dfa 100644 --- a/tests/vps.service.test.ts +++ b/tests/vps.service.test.ts @@ -1,34 +1,93 @@ -import { describe, it, expect, beforeEach } from "vitest"; -import path from "node:path"; -import { VPSRepository } from "../src/repositories/vps.repository.js"; +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { SEED_VPS_RECORDS, 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", () => { +const CORE_FIXTURE: VPS[] = [ + { + 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", + }, +]; + +describe("SQLite 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); + repository = new VPSRepository(":memory:"); + repository.init(); + repository.seedIfEmpty(CORE_FIXTURE); 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); + afterEach(() => { + repository.close(); + }); + + describe("SQLite initialization and 100-VPS seeding", () => { + it("should seed 100 sample VPS records when default SEED_VPS_RECORDS is used", () => { + const fullRepo = new VPSRepository(":memory:"); + fullRepo.init(); + const inserted = fullRepo.seedIfEmpty(); + + expect(SEED_VPS_RECORDS).toHaveLength(100); + expect(inserted).toBe(100); + expect(fullRepo.getAll()).toHaveLength(100); + expect(fullRepo.getByName("shop-prod-01")?.id).toBe("vps-001"); + expect(fullRepo.getById("vps-100")).toBeDefined(); + + fullRepo.close(); }); - 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"); + it("should not duplicate records if seedIfEmpty is called multiple times", () => { + const inserted = repository.seedIfEmpty(CORE_FIXTURE); + expect(inserted).toBe(0); + expect(repository.getAll()).toHaveLength(3); + }); + + it("should find a VPS by exact ID", () => { + const vps = repository.getById("vps-002"); + expect(vps).toBeDefined(); + expect(vps?.name).toBe("staging-01"); }); }); describe("listAll", () => { - it("should return all three VPS with correct properties", () => { + it("should return all fixture VPS with correct properties", () => { const list = service.listAll(); expect(list).toHaveLength(3); @@ -88,31 +147,12 @@ describe("VPS Repository and Service", () => { 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); + it("should search by IP address when IP is configured and allowed", () => { + const byIp = service.search("203.0.113", true); expect(byIp).toHaveLength(1); - expect(byIp[0].name).toBe("test-vps"); + expect(byIp[0].name).toBe("shop-prod-01"); - // When IP search is not permitted (e.g. unauthenticated) - const noIp = testService.search("192.0.2", false); + const noIp = service.search("203.0.113", false); expect(noIp).toHaveLength(0); }); @@ -169,25 +209,19 @@ describe("VPS Repository and Service", () => { }); describe("getStats", () => { - it("should accurately compute all aggregate statistics for seed data", () => { + it("should accurately compute all aggregate statistics for fixture 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,