feat: SQLite RBAC, granular permissions, 100-VPS seeder, DM pagination

This commit is contained in:
khuongnguyen committed 2026-12-02 10:26:56 +07:00
1 parent 41d9e9e8eb
commit 4ccb35a44c
16 files changed
+1682 -319

No files matched your search

+3
View File
@@ -9,3 +9,6 @@ DISCORD_GUILD_ID=your_guild_id_here
# Discord Role ID permitted to execute sensitive commands like `/vps connect` # Discord Role ID permitted to execute sensitive commands like `/vps connect`
DEVOPS_ROLE_ID=your_devops_role_id_here 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
+3
View File
@@ -2,6 +2,9 @@ node_modules/
dist/ dist/
.env .env
.env.local .env.local
data/*.db
data/*.db-wal
data/*.db-shm
*.log *.log
npm-debug.log* npm-debug.log*
yarn-debug.log* yarn-debug.log*
-39
View File
@@ -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"
}
]
+1
View File
@@ -7,6 +7,7 @@
"dev": "tsx watch src/index.ts", "dev": "tsx watch src/index.ts",
"start": "tsx src/index.ts", "start": "tsx src/index.ts",
"deploy:commands": "tsx src/deploy-commands.ts", "deploy:commands": "tsx src/deploy-commands.ts",
"db:seed": "tsx src/seed.ts",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
"test": "vitest run" "test": "vitest run"
}, },
+385 -32
View File
@@ -1,7 +1,14 @@
import { import {
ActionRowBuilder,
ButtonBuilder,
ButtonInteraction,
ButtonStyle,
ChatInputCommandInteraction, ChatInputCommandInteraction,
EmbedBuilder,
SlashCommandBuilder, SlashCommandBuilder,
} from "discord.js"; } from "discord.js";
import { getDataConfig } from "../config/env.js";
import { PermissionRepository } from "../repositories/permission.repository.js";
import { VPSService } from "../services/vps.service.js"; import { VPSService } from "../services/vps.service.js";
import { VPSEnvironment } from "../types/vps.js"; import { VPSEnvironment } from "../types/vps.js";
import { import {
@@ -9,14 +16,49 @@ import {
createSSHConnectEmbed, createSSHConnectEmbed,
createVPSFilterEmbed, createVPSFilterEmbed,
createVPSInfoEmbed, createVPSInfoEmbed,
createVPSListEmbed, createVPSListPages,
createVPSSearchEmbed, createVPSSearchEmbed,
createVPSStatsEmbed, createVPSStatsEmbed,
createWarningEmbed, createWarningEmbed,
EMBED_COLORS,
} from "../utils/embeds.js"; } 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"; import { generateSSHCommand } from "../utils/ssh.js";
/**
* Action-based permission requirement per subcommand.
*/
export const SUBCOMMAND_PERMISSIONS: Record<string, VPSPermission> = {
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() export const vpsCommandData = new SlashCommandBuilder()
.setName("vps") .setName("vps")
.setDescription("VPS Inventory Assistant management commands") .setDescription("VPS Inventory Assistant management commands")
@@ -73,29 +115,103 @@ export const vpsCommandData = new SlashCommandBuilder()
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName("connect") .setName("connect")
.setDescription("Generate SSH connection command (DevOps / Admin only)") .setDescription("Generate SSH connection command (requires vps:connect permission)")
.addStringOption((opt) => .addStringOption((opt) =>
opt opt
.setName("name") .setName("name")
.setDescription("The name of the VPS") .setDescription("The name of the VPS")
.setRequired(true) .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 { export class VPSCommandHandler {
private vpsService: VPSService; private vpsService: VPSService;
private permissionSource: PermissionSource;
constructor(vpsService?: VPSService) { constructor(vpsService?: VPSService, permissionSource?: PermissionSource) {
if (!vpsService) {
getDataConfig();
}
this.vpsService = vpsService || new VPSService(); 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<void> { public async handle(interaction: ChatInputCommandInteraction): Promise<void> {
const subcommandGroup = interaction.options.getSubcommandGroup(false);
const subcommand = interaction.options.getSubcommand(); const subcommand = interaction.options.getSubcommand();
try { 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) { switch (subcommand) {
case "list": case "list":
await this.handleList(interaction); await this.handleList(interaction);
@@ -115,14 +231,12 @@ export class VPSCommandHandler {
case "connect": case "connect":
await this.handleConnect(interaction); await this.handleConnect(interaction);
break; break;
default:
await interaction.reply({
embeds: [createErrorEmbed("Unknown Subcommand", "The requested subcommand is not recognized.")],
ephemeral: true,
});
} }
} catch (error) { } 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( const errorEmbed = createErrorEmbed(
"Internal Processing Error", "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<void> {
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<string, { roleName: string; perms: string[] }>();
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<ButtonBuilder>().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<void> {
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<void> { private async handleList(interaction: ChatInputCommandInteraction): Promise<void> {
const servers = this.vpsService.listAll(); const servers = this.vpsService.listAll();
const embed = createVPSListEmbed(servers); const pages = createVPSListPages(servers);
await interaction.reply({ embeds: [embed] });
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<void> { private async handleInfo(interaction: ChatInputCommandInteraction): Promise<void> {
@@ -156,17 +499,40 @@ export class VPSCommandHandler {
return; return;
} }
const isAuthorized = isDevOpsOrAdmin(interaction.member, process.env.DEVOPS_ROLE_ID); const canViewSensitive = hasPermission(
const embed = createVPSInfoEmbed(vps, isAuthorized); interaction.member,
"vps:read_sensitive",
this.permissionSource
);
const embed = createVPSInfoEmbed(vps, canViewSensitive);
await interaction.reply({ embeds: [embed] }); await interaction.reply({ embeds: [embed] });
} }
private async handleSearch(interaction: ChatInputCommandInteraction): Promise<void> { private async handleSearch(interaction: ChatInputCommandInteraction): Promise<void> {
const query = interaction.options.getString("query", true); const query = interaction.options.getString("query", true);
const isAuthorized = isDevOpsOrAdmin(interaction.member, process.env.DEVOPS_ROLE_ID); const canSearchIP = hasPermission(
const results = this.vpsService.search(query, isAuthorized); interaction.member,
"vps:read_sensitive",
this.permissionSource
);
const results = this.vpsService.search(query, canSearchIP);
const embed = createVPSSearchEmbed(query, results); 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<void> { private async handleFilter(interaction: ChatInputCommandInteraction): Promise<void> {
@@ -194,18 +560,6 @@ export class VPSCommandHandler {
} }
private async handleConnect(interaction: ChatInputCommandInteraction): Promise<void> { 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 name = interaction.options.getString("name", true);
const vps = this.vpsService.getByName(name); const vps = this.vpsService.getByName(name);
@@ -218,7 +572,6 @@ export class VPSCommandHandler {
return; return;
} }
// 3. Generate SSH Command securely
const sshResult = generateSSHCommand(vps); const sshResult = generateSSHCommand(vps);
if (!sshResult.success || !sshResult.command) { if (!sshResult.success || !sshResult.command) {
const warningEmbed = createWarningEmbed( const warningEmbed = createWarningEmbed(
@@ -229,7 +582,7 @@ export class VPSCommandHandler {
return; return;
} }
// 4. Return Ephemeral Response with SSH details this.recordAudit(interaction, "vps:connect", vps.name, "ALLOWED");
const connectEmbed = createSSHConnectEmbed(vps, sshResult.command); const connectEmbed = createSSHConnectEmbed(vps, sshResult.command);
await interaction.reply({ embeds: [connectEmbed], ephemeral: true }); await interaction.reply({ embeds: [connectEmbed], ephemeral: true });
} }
+24 -2
View File
@@ -3,18 +3,40 @@ import { z } from "zod";
dotenv.config(); 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_TOKEN: z.string().min(1, "DISCORD_TOKEN is required"),
DISCORD_CLIENT_ID: z.string().min(1, "DISCORD_CLIENT_ID 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"), DISCORD_GUILD_ID: z.string().min(1, "DISCORD_GUILD_ID is required"),
DEVOPS_ROLE_ID: z.string().optional(), DEVOPS_ROLE_ID: z.string().optional(),
VPS_DATA_PATH: z.string().default("data/vps.json"),
}); });
export type DataConfig = z.infer<typeof dataConfigSchema>;
export type EnvConfig = z.infer<typeof envSchema>; export type EnvConfig = z.infer<typeof envSchema>;
let cachedEnv: EnvConfig | null = null; 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 { export function getEnv(): EnvConfig {
if (cachedEnv) { if (cachedEnv) {
return cachedEnv; return cachedEnv;
+46 -11
View File
@@ -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 { VPSCommandHandler } from "./commands/vps.command.js";
import { getEnv } from "./config/env.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() { async function bootstrap() {
console.log("⚡ Starting VPS Inventory Assistant Discord Bot..."); console.log("⚡ Starting VPS Inventory Assistant Discord Bot...");
// Validate environment configuration // 1. Validate environment configuration up front
let env; let env;
try { try {
env = getEnv(); env = getEnv();
@@ -14,12 +17,39 @@ async function bootstrap() {
process.exit(1); process.exit(1);
} }
// Initialize Discord Client with minimal required intents for slash commands // 2. Initialize SQLite data sources up front (VPS inventory & Permission tables)
const client = new Client({ let vpsRepository: VPSRepository;
intents: [GatewayIntentBits.Guilds], 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 // Ready event
client.once(Events.ClientReady, (readyClient) => { client.once(Events.ClientReady, (readyClient) => {
@@ -30,12 +60,13 @@ async function bootstrap() {
// Interaction Create event // Interaction Create event
client.on(Events.InteractionCreate, async (interaction) => { client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand()) { if (interaction.isChatInputCommand() && interaction.commandName === "vps") {
await commandHandler.handle(interaction);
return; return;
} }
if (interaction.commandName === "vps") { if (interaction.isButton() && interaction.customId.startsWith("vps_list_")) {
await commandHandler.handle(interaction); await commandHandler.handleListPaginationButton(interaction);
} }
}); });
@@ -43,7 +74,9 @@ async function bootstrap() {
const handleShutdown = (signal: string) => { const handleShutdown = (signal: string) => {
console.log(`\n🛑 Received ${signal}. Shutting down gracefully...`); console.log(`\n🛑 Received ${signal}. Shutting down gracefully...`);
client.destroy(); client.destroy();
console.log("👋 Discord client disconnected. Goodbye!"); vpsRepository.close();
permissionRepository.close();
console.log("👋 Discord client & SQLite closed. Goodbye!");
process.exit(0); process.exit(0);
}; };
@@ -55,6 +88,8 @@ async function bootstrap() {
await client.login(env.DISCORD_TOKEN); await client.login(env.DISCORD_TOKEN);
} catch (err) { } catch (err) {
console.error("❌ Failed to log in to Discord:", (err as Error).message); console.error("❌ Failed to log in to Discord:", (err as Error).message);
vpsRepository.close();
permissionRepository.close();
process.exit(1); process.exit(1);
} }
} }
+353
View File
@@ -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<VPSPermission> {
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;
}
}
}
+257 -44
View File
@@ -1,81 +1,294 @@
import fs from "node:fs"; import fs from "node:fs";
import path from "node:path"; import path from "node:path";
import { VPS, vpsListSchema } from "../types/vps.js"; import { DatabaseSync } from "node:sqlite";
import { getDataConfig } from "../config/env.js";
export class VPSRepository { import { VPS, vpsListSchema, vpsSchema } from "../types/vps.js";
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. * Storage-agnostic repository contract.
*/ */
public load(): VPS[] { export interface IVPSRepository {
const resolvedPath = path.resolve(this.filePath); getAll(): VPS[];
getById(id: string): VPS | undefined;
if (!fs.existsSync(resolvedPath)) { getByName(name: string): VPS | undefined;
throw new Error(`Inventory data file not found at path: ${resolvedPath}`); close?(): void;
} }
let rawData: string; interface VPSRow {
try { id: string;
rawData = fs.readFileSync(resolvedPath, "utf-8"); name: string;
} catch (err) { provider: string;
throw new Error(`Failed to read inventory data file: ${(err as Error).message}`); region: string;
environment: string;
cpu: number;
ramGB: number;
diskGB: number;
ip: string | null;
sshUser: string | null;
sshPort: number | null;
} }
let parsed: unknown; const CORE_SEED_RECORDS: readonly VPS[] = [
try { {
parsed = JSON.parse(rawData); id: "vps-001",
} catch (err) { name: "shop-prod-01",
throw new Error(`Corrupted JSON inventory data file: ${(err as Error).message}`); 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,
});
} }
const validation = vpsListSchema.safeParse(parsed); return records;
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; export const SEED_VPS_RECORDS: readonly VPS[] = buildGeneratedSeedRecords(100);
return this.cache;
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);
} }
/** /**
* Returns all VPS records. * Opens the SQLite database connection and ensures the `vps` table exists.
*/
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 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 initialize SQLite database: ${(err as Error).message}`);
}
}
private getDb(): DatabaseSync {
if (!this.db) {
this.init();
}
return this.db!;
}
/**
* 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[] { public getAll(): VPS[] {
if (!this.cache) { try {
return this.load(); 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. * Finds a VPS by exact ID.
*/ */
public getById(id: string): VPS | undefined { 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). * Finds a VPS by name (case-insensitive).
*/ */
public getByName(name: string): VPS | undefined { public getByName(name: string): VPS | undefined {
const trimmed = name.trim().toLowerCase(); const trimmed = name.trim();
return this.getAll().find((vps) => vps.name.toLowerCase() === trimmed); 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[] { public close(): void {
this.cache = null; if (this.db) {
return this.load(); this.db.close();
this.db = null;
}
} }
} }
+36
View File
@@ -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();
+3 -3
View File
@@ -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"; import { VPS, VPSFilterOptions, VPSStats } from "../types/vps.js";
export class VPSService { export class VPSService {
private repository: VPSRepository; private repository: IVPSRepository;
constructor(repository?: VPSRepository) { constructor(repository?: IVPSRepository) {
this.repository = repository || new VPSRepository(); this.repository = repository || new VPSRepository();
} }
+108 -40
View File
@@ -8,59 +8,111 @@ export const EMBED_COLORS = {
ERROR: 0xe74c3c, // Red ERROR: 0xe74c3c, // Red
} as const; } as const;
/** export const DISCORD_EMBED_LIMITS = {
* Creates an embed for the inventory list command. MAX_FIELDS: 25,
*/ MAX_TOTAL_CHARS: 6000,
export function createVPSListEmbed(servers: VPS[]): EmbedBuilder { SAFE_PAGE_CHARS: 5400, // Leave headroom for title, description, and footer
const embed = new EmbedBuilder() DEFAULT_PAGE_SIZE: 10,
.setTitle("🖥️ VPS Inventory Overview") } as const;
.setColor(EMBED_COLORS.PRIMARY)
.setTimestamp()
.setFooter({ text: `Total Servers: ${servers.length}` });
if (servers.length === 0) { function formatEnvironmentBadge(env: VPS["environment"]): string {
embed.setDescription("ℹ️ No VPS records found in the inventory."); if (env === "Production") return "🔴 Production";
return embed; if (env === "Staging") return "🟡 Staging";
return "🟢 Development";
} }
embed.setDescription( function formatVPSListField(vps: VPS): { name: string; value: string; inline: boolean } {
`Displaying **${servers.length}** VPS server(s) currently managed in the inventory:\n` const envBadge = formatEnvironmentBadge(vps.environment);
);
for (const vps of servers) {
const envBadge =
vps.environment === "Production"
? "🔴 Production"
: vps.environment === "Staging"
? "🟡 Staging"
: "🟢 Development";
const value = [ const value = [
`• **Provider:** ${vps.provider} (${vps.region})`, `• **Provider:** ${vps.provider} (${vps.region})`,
`• **Environment:** ${envBadge}`, `• **Environment:** ${envBadge}`,
`• **Hardware:** ${vps.cpu} vCPU | ${vps.ramGB} GB RAM | ${vps.diskGB} GB Disk`, `• **Hardware:** ${vps.cpu} vCPU | ${vps.ramGB} GB RAM | ${vps.diskGB} GB Disk`,
].join("\n"); ].join("\n");
embed.addFields({ return {
name: `📌 ${vps.name}`, name: `📌 ${vps.name}`,
value, value,
inline: false, 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) {
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];
}
const effectivePageSize = Math.min(Math.max(1, pageSize), DISCORD_EMBED_LIMITS.MAX_FIELDS);
const chunks: Array<Array<{ name: string; value: string; inline: boolean }>> = [];
let currentChunk: Array<{ name: string; value: string; inline: boolean }> = [];
let currentChars = 0;
for (const vps of servers) {
const field = formatVPSListField(vps);
const fieldChars = field.name.length + field.value.length;
const wouldExceedCount = currentChunk.length >= effectivePageSize;
const wouldExceedChars = currentChars + fieldChars > DISCORD_EMBED_LIMITS.SAFE_PAGE_CHARS;
if (currentChunk.length > 0 && (wouldExceedCount || wouldExceedChars)) {
chunks.push(currentChunk);
currentChunk = [];
currentChars = 0;
}
currentChunk.push(field);
currentChars += fieldChars;
}
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 });
}); });
} }
return embed; /**
* 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. * Creates a detailed embed for a specific VPS.
*/ */
export function createVPSInfoEmbed(vps: VPS, isAuthorized = false): EmbedBuilder { export function createVPSInfoEmbed(vps: VPS, isAuthorized = false): EmbedBuilder {
const envBadge = const envBadge = formatEnvironmentBadge(vps.environment);
vps.environment === "Production"
? "🔴 Production"
: vps.environment === "Staging"
? "🟡 Staging"
: "🟢 Development";
let ipDisplay = "Not configured"; let ipDisplay = "Not configured";
if (vps.ip) { 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 { export function createVPSSearchEmbed(query: string, results: VPS[]): EmbedBuilder {
const embed = new 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.`); .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 embed
.setColor(EMBED_COLORS.PRIMARY) .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({ embed.addFields({
name: `📌 ${vps.name} (${vps.environment})`, name: `📌 ${vps.name} (${vps.environment})`,
value: `• **Provider:** ${vps.provider} (${vps.region})\n• **Specs:** ${vps.cpu} vCPU | ${vps.ramGB} GB RAM | ${vps.diskGB} GB Disk`, 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 { export function createVPSFilterEmbed(filters: VPSFilterOptions, results: VPS[]): EmbedBuilder {
const activeFilters: string[] = []; 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 embed
.setColor(EMBED_COLORS.PRIMARY) .setColor(EMBED_COLORS.PRIMARY)
.setDescription( .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({ embed.addFields({
name: `📌 ${vps.name}`, name: `📌 ${vps.name}`,
value: `• **Provider:** ${vps.provider} (${vps.region})\n• **Environment:** ${vps.environment}\n• **Specs:** ${vps.cpu} vCPU | ${vps.ramGB} GB | ${vps.diskGB} GB`, value: `• **Provider:** ${vps.provider} (${vps.region})\n• **Environment:** ${vps.environment}\n• **Specs:** ${vps.cpu} vCPU | ${vps.ramGB} GB | ${vps.diskGB} GB`,
@@ -178,11 +244,13 @@ export function createVPSFilterEmbed(filters: VPSFilterOptions, results: VPS[]):
* Creates an embed displaying dynamic inventory statistics. * Creates an embed displaying dynamic inventory statistics.
*/ */
export function createVPSStatsEmbed(stats: VPSStats): EmbedBuilder { export function createVPSStatsEmbed(stats: VPSStats): EmbedBuilder {
const providerBreakdown = Object.entries(stats.byProvider) const providerBreakdown =
Object.entries(stats.byProvider)
.map(([provider, count]) => `• **${provider}:** ${count} server(s)`) .map(([provider, count]) => `• **${provider}:** ${count} server(s)`)
.join("\n") || "None"; .join("\n") || "None";
const envBreakdown = Object.entries(stats.byEnvironment) const envBreakdown =
Object.entries(stats.byEnvironment)
.map(([env, count]) => `• **${env}:** ${count} server(s)`) .map(([env, count]) => `• **${env}:** ${count} server(s)`)
.join("\n") || "None"; .join("\n") || "None";
+154 -50
View File
@@ -6,55 +6,51 @@ import {
} from "discord.js"; } from "discord.js";
/** /**
* Checks whether a guild member has Administrator permissions or the designated DevOps role. * Granular action-based permissions for VPS Inventory operations (one permission per feature).
* Fails securely if permissions or role configurations are missing.
*/ */
export function isDevOpsOrAdmin( export type VPSPermission =
member: GuildMember | ChatInputCommandInteraction["member"], | "vps:list"
devopsRoleId?: string | "vps:info"
): boolean { | "vps:search"
if (!member) { | "vps:filter"
return false; | "vps:stats"
| "vps:read_sensitive"
| "vps:connect"
| "vps:add"
| "vps:update"
| "vps:delete";
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;
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<string, readonly VPSPermission[]>;
/** Whether Discord Server Administrators automatically receive all permissions */
adminBypass?: boolean;
} }
// Check Discord Administrator permission /**
if ("permissions" in member && member.permissions) { * Storage-backed permission provider contract (implemented by SQLite PermissionRepository).
try { */
if (typeof member.permissions === "string") { export interface IPermissionStore {
const bitfield = new PermissionsBitField(BigInt(member.permissions)); getPermissionsForRoles(roleIds: string[]): Set<VPSPermission>;
if (bitfield.has(PermissionFlagsBits.Administrator)) { adminBypass?: boolean;
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 export type PermissionSource = RolePermissionConfig | IPermissionStore;
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 { export interface AuthorizationResult {
authorized: boolean; authorized: boolean;
@@ -62,11 +58,120 @@ export interface AuthorizationResult {
} }
/** /**
* 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<string, readonly VPSPermission[]> = {};
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<VPSPermission> {
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<VPSPermission>(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, interaction: ChatInputCommandInteraction,
devopsRoleId?: string permission: VPSPermission,
source: PermissionSource
): AuthorizationResult { ): AuthorizationResult {
if (!interaction.guildId || !interaction.member) { if (!interaction.guildId || !interaction.member) {
return { return {
@@ -75,11 +180,10 @@ export function checkDevOpsAuthorization(
}; };
} }
const authorized = isDevOpsOrAdmin(interaction.member, devopsRoleId); if (!hasPermission(interaction.member, permission, source)) {
if (!authorized) {
return { return {
authorized: false, 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.`,
}; };
} }
+46
View File
@@ -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");
});
});
+184 -53
View File
@@ -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 { 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 DEVOPS_ROLE_ID = "role-devops-123";
const VIEWER_ROLE_ID = "role-viewer-456";
const defaultConfig = createDefaultPermissionConfig(DEVOPS_ROLE_ID);
describe("isDevOpsOrAdmin", () => { describe("getMemberPermissions & hasPermission (in-memory config)", () => {
it("should return false if member is null or undefined", () => { it("should return empty set if member is null or undefined", () => {
expect(isDevOpsOrAdmin(null as any, DEVOPS_ROLE_ID)).toBe(false); expect(getMemberPermissions(null as any, defaultConfig).size).toBe(0);
expect(isDevOpsOrAdmin(undefined as any, DEVOPS_ROLE_ID)).toBe(false); 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 = { const member = {
permissions: new PermissionsBitField(PermissionFlagsBits.Administrator), permissions: new PermissionsBitField(PermissionFlagsBits.Administrator),
roles: { cache: new Map() }, 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 bitfield = new PermissionsBitField(PermissionFlagsBits.Administrator).bitfield.toString();
const member = { const member = {
permissions: bitfield, permissions: bitfield,
roles: [], 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", () => { it("should grant DevOps role all 10 granular VPS permissions via role cache", () => {
const roleMap = new Map(); const roleMap = new Map([[DEVOPS_ROLE_ID, { id: DEVOPS_ROLE_ID }]]);
roleMap.set(DEVOPS_ROLE_ID, { id: DEVOPS_ROLE_ID, name: "DevOps" });
const member = { const member = {
permissions: new PermissionsBitField(), permissions: new PermissionsBitField(),
roles: { roles: { cache: roleMap },
cache: {
has: (id: string) => roleMap.has(id),
},
},
}; };
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)", () => { it("should grant new/regular guild members zero permissions by default (zero-trust)", () => {
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 = { const member = {
permissions: new PermissionsBitField(), permissions: new PermissionsBitField(),
roles: { roles: ["some-other-role"],
cache: {
has: (_id: string) => false,
},
},
}; };
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 = { const member = {
permissions: new PermissionsBitField(), permissions: new PermissionsBitField(),
roles: ["some-role"], 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", () => { describe("authorizeAction (in-memory config)", () => {
it("should deny access when command is executed outside a guild (e.g. DM)", () => { it("should deny access when executed outside a guild (e.g. DM)", () => {
const mockInteraction = { const mockInteraction = { guildId: null, member: null };
guildId: null, const result = authorizeAction(mockInteraction as any, "vps:list", defaultConfig);
member: null,
};
const result = checkDevOpsAuthorization(mockInteraction as any, DEVOPS_ROLE_ID);
expect(result.authorized).toBe(false); expect(result.authorized).toBe(false);
expect(result.reason).toContain("only be executed within an authorized Discord Server"); 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 = { const mockInteraction = {
guildId: "guild-123", guildId: "guild-123",
member: { member: {
permissions: new PermissionsBitField(), 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.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 = { const mockInteraction = {
guildId: "guild-123", guildId: "guild-123",
member: { member: {
permissions: new PermissionsBitField(), 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.authorized).toBe(true);
expect(result.reason).toBeUndefined(); 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");
});
});
}); });
+79 -45
View File
@@ -1,34 +1,93 @@
import { describe, it, expect, beforeEach } from "vitest"; import { describe, it, expect, beforeEach, afterEach } from "vitest";
import path from "node:path"; import { SEED_VPS_RECORDS, VPSRepository } from "../src/repositories/vps.repository.js";
import { VPSRepository } from "../src/repositories/vps.repository.js";
import { VPSService } from "../src/services/vps.service.js"; import { VPSService } from "../src/services/vps.service.js";
import { VPS } from "../src/types/vps.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 repository: VPSRepository;
let service: VPSService; let service: VPSService;
beforeEach(() => { beforeEach(() => {
// Point to data/vps.json repository = new VPSRepository(":memory:");
const seedPath = path.resolve(process.cwd(), "data/vps.json"); repository.init();
repository = new VPSRepository(seedPath); repository.seedIfEmpty(CORE_FIXTURE);
service = new VPSService(repository); service = new VPSService(repository);
}); });
describe("Repository loading and validation", () => { afterEach(() => {
it("should load exactly the 3 seed VPS records", () => { repository.close();
const all = repository.getAll();
expect(all).toHaveLength(3);
}); });
it("should throw a descriptive error when file is missing", () => { describe("SQLite initialization and 100-VPS seeding", () => {
const invalidRepo = new VPSRepository("non-existent-path.json"); it("should seed 100 sample VPS records when default SEED_VPS_RECORDS is used", () => {
expect(() => invalidRepo.getAll()).toThrow("Inventory data file not found"); 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 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", () => { describe("listAll", () => {
it("should return all three VPS with correct properties", () => { it("should return all fixture VPS with correct properties", () => {
const list = service.listAll(); const list = service.listAll();
expect(list).toHaveLength(3); expect(list).toHaveLength(3);
@@ -88,31 +147,12 @@ describe("VPS Repository and Service", () => {
expect(results[0].name).toBe("staging-01"); expect(results[0].name).toBe("staging-01");
}); });
it("should search by IP address when IP is configured", () => { it("should search by IP address when IP is configured and allowed", () => {
// Mock repository with an IP configured const byIp = service.search("203.0.113", true);
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).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 = service.search("203.0.113", false);
const noIp = testService.search("192.0.2", false);
expect(noIp).toHaveLength(0); expect(noIp).toHaveLength(0);
}); });
@@ -169,25 +209,19 @@ describe("VPS Repository and Service", () => {
}); });
describe("getStats", () => { 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(); 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.totalVPS).toBe(3);
expect(stats.totalVCPU).toBe(10); expect(stats.totalVCPU).toBe(10);
expect(stats.totalRamGB).toBe(28); expect(stats.totalRamGB).toBe(28);
expect(stats.totalDiskGB).toBe(560); expect(stats.totalDiskGB).toBe(560);
// Environment breakdown
expect(stats.byEnvironment).toEqual({ expect(stats.byEnvironment).toEqual({
Production: 2, Production: 2,
Staging: 1, Staging: 1,
}); });
// Provider breakdown
expect(stats.byProvider).toEqual({ expect(stats.byProvider).toEqual({
Vultr: 2, Vultr: 2,
DigitalOcean: 1, DigitalOcean: 1,