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 { 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 { const servers = this.vpsService.listAll(); const embed = createVPSListEmbed(servers); await interaction.reply({ embeds: [embed] }); } private async handleInfo(interaction: ChatInputCommandInteraction): Promise { 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 { 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 { 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 { const stats = this.vpsService.getStats(); const embed = createVPSStatsEmbed(stats); await interaction.reply({ embeds: [embed] }); } 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); 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 }); } }