feat(rcon): add admin server console
This commit is contained in:
@@ -38,6 +38,7 @@ export default async function AdminConsoleLayout({ children }: { children: React
|
||||
<Link className="hover:text-accent" href="/admin/settings">Settings</Link>
|
||||
<Link className="hover:text-accent" href="/admin/users">Users</Link>
|
||||
<Link className="hover:text-accent" href="/admin/groups">Groups</Link>
|
||||
<Link className="hover:text-accent" href="/admin/rcon">RCON</Link>
|
||||
<Link className="hover:text-accent" href="/admin/events">Events</Link>
|
||||
</nav>
|
||||
<AdminSignOutButton />
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const actionState = vi.hoisted(() => ({
|
||||
authorized: 0,
|
||||
selected: [] as unknown[],
|
||||
transactionSelected: [] as unknown[],
|
||||
updates: [] as Record<string, unknown>[],
|
||||
inserts: [] as unknown[],
|
||||
audits: [] as Array<{ admin: unknown; subject: string; type: string; data: Record<string, unknown> }>,
|
||||
executions: [] as Array<{ connection: Record<string, unknown>; command: string }>,
|
||||
gatewayResult: { ok: true, response: "private response" } as
|
||||
| { ok: true; response: string }
|
||||
| { ok: false; reason: "busy" | "timeout" | "unavailable" },
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/require-admin", () => ({
|
||||
requireAdminSession: async () => {
|
||||
actionState.authorized += 1;
|
||||
return { email: "admin@example.test", name: "Admin" };
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("next/headers", () => ({ headers: async () => new Headers() }));
|
||||
vi.mock("next/navigation", () => ({
|
||||
redirect: (path: string) => {
|
||||
throw new Error(`REDIRECT:${path}`);
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/database", () => {
|
||||
function selection(result: unknown[]) {
|
||||
const chain = {
|
||||
from: () => chain,
|
||||
where: () => chain,
|
||||
limit: async () => result,
|
||||
};
|
||||
return chain;
|
||||
}
|
||||
const tx = {
|
||||
execute: async () => undefined,
|
||||
select: () => selection(actionState.transactionSelected),
|
||||
update: () => ({
|
||||
set: (value: Record<string, unknown>) => ({
|
||||
where: async () => { actionState.updates.push(value); },
|
||||
}),
|
||||
}),
|
||||
insert: () => ({
|
||||
values: async (value: unknown) => { actionState.inserts.push(value); },
|
||||
}),
|
||||
};
|
||||
return {
|
||||
db: {
|
||||
select: () => selection(actionState.selected),
|
||||
transaction: async (callback: (transaction: typeof tx) => Promise<unknown>) => callback(tx),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/lib/rcon-validation", () => ({
|
||||
validateRconCommand: (value: unknown) => typeof value === "string" && value.trim() ? value.trim() : null,
|
||||
validateRconConnection: (input: { name?: string; host?: string; port?: number; password?: string }) => {
|
||||
if (!input.name || !input.host || !input.port) return null;
|
||||
return input;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/rcon-credentials", () => ({
|
||||
decryptRconPassword: () => "decrypted-password",
|
||||
encryptRconPassword: vi.fn(),
|
||||
rconCommandDigest: () => "hmac-sha256:v1:digest",
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/rcon-gateway", () => ({
|
||||
executeRcon: async (connection: Record<string, unknown>, command: string) => {
|
||||
actionState.executions.push({ connection, command });
|
||||
return actionState.gatewayResult;
|
||||
},
|
||||
testRconConnection: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/audit", () => ({
|
||||
recordAdminSubjectEvent: async (
|
||||
admin: unknown,
|
||||
subject: string,
|
||||
type: string,
|
||||
data: Record<string, unknown>,
|
||||
) => {
|
||||
actionState.audits.push({ admin, subject, type, data });
|
||||
},
|
||||
}));
|
||||
|
||||
import {
|
||||
createRconServer,
|
||||
deleteRconServer,
|
||||
executeRconCommand,
|
||||
setRconServerEnabled,
|
||||
testSavedRconServer,
|
||||
updateRconServer,
|
||||
} from "./actions";
|
||||
|
||||
const serverId = "11111111-1111-4111-8111-111111111111";
|
||||
const savedServer = {
|
||||
id: serverId,
|
||||
name: "Season 4",
|
||||
host: "season4.somc.svc.cluster.local",
|
||||
port: 25575,
|
||||
encryptedPassword: "ciphertext",
|
||||
enabled: true,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
describe("RCON server actions", () => {
|
||||
beforeEach(() => {
|
||||
actionState.authorized = 0;
|
||||
actionState.selected = [];
|
||||
actionState.transactionSelected = [];
|
||||
actionState.updates = [];
|
||||
actionState.inserts = [];
|
||||
actionState.audits = [];
|
||||
actionState.executions = [];
|
||||
actionState.gatewayResult = { ok: true, response: "private response" };
|
||||
});
|
||||
|
||||
it("independently authorizes every exported operation before accepting input", async () => {
|
||||
await expect(createRconServer(new FormData())).rejects.toThrow("REDIRECT:/admin/rcon?error=invalid-connection");
|
||||
await expect(updateRconServer(new FormData())).rejects.toThrow("REDIRECT:/admin/rcon?error=invalid-connection");
|
||||
await expect(setRconServerEnabled(new FormData())).rejects.toThrow("REDIRECT:/admin/rcon?error=unknown-connection");
|
||||
await expect(deleteRconServer(new FormData())).rejects.toThrow("REDIRECT:/admin/rcon?error=confirmation-required");
|
||||
await expect(testSavedRconServer(new FormData())).rejects.toThrow("REDIRECT:/admin/rcon?error=connection-unavailable");
|
||||
await expect(executeRconCommand({ status: "idle", message: "", serverId: "" }, new FormData())).resolves.toEqual({
|
||||
status: "error",
|
||||
message: "Enter one command of at most 1,024 bytes without control characters.",
|
||||
serverId: "",
|
||||
});
|
||||
expect(actionState.authorized).toBe(6);
|
||||
});
|
||||
|
||||
it("preserves the encrypted password on an unrelated connection update", async () => {
|
||||
actionState.transactionSelected = [savedServer];
|
||||
const formData = new FormData();
|
||||
formData.set("serverId", serverId);
|
||||
formData.set("name", "Renamed server");
|
||||
formData.set("host", "season4.somc.svc.cluster.local");
|
||||
formData.set("port", "25575");
|
||||
formData.set("password", "");
|
||||
formData.set("enabled", "yes");
|
||||
|
||||
await expect(updateRconServer(formData)).rejects.toThrow("REDIRECT:/admin/rcon?saved=updated");
|
||||
expect(actionState.updates).toEqual([
|
||||
expect.objectContaining({ encryptedPassword: "ciphertext", enabled: true }),
|
||||
]);
|
||||
expect(JSON.stringify(actionState.inserts)).not.toContain("ciphertext");
|
||||
expect(JSON.stringify(actionState.inserts)).not.toContain("decrypted-password");
|
||||
});
|
||||
|
||||
it("rechecks enabled saved state and records credential-safe command lifecycle audits", async () => {
|
||||
actionState.selected = [savedServer];
|
||||
const formData = new FormData();
|
||||
formData.set("serverId", serverId);
|
||||
formData.set("command", "say private value");
|
||||
|
||||
await expect(executeRconCommand({ status: "idle", message: "", serverId: "" }, formData)).resolves.toEqual({
|
||||
status: "success",
|
||||
message: "private response",
|
||||
serverId,
|
||||
});
|
||||
|
||||
expect(actionState.authorized).toBe(1);
|
||||
expect(actionState.executions).toEqual([{
|
||||
connection: expect.objectContaining({ id: serverId, enabled: true, password: "decrypted-password" }),
|
||||
command: "say private value",
|
||||
}]);
|
||||
expect(actionState.audits).toEqual([
|
||||
expect.objectContaining({
|
||||
admin: { email: "admin@example.test", name: "Admin" },
|
||||
subject: `rcon-server/${serverId}`,
|
||||
type: "games.minecraft.account-manager.rcon.command.requested",
|
||||
data: expect.objectContaining({ verb: "say", commandDigest: "hmac-sha256:v1:digest" }),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
subject: `rcon-server/${serverId}`,
|
||||
type: "games.minecraft.account-manager.rcon.command.completed",
|
||||
data: expect.objectContaining({ success: true, durationMs: expect.any(Number) }),
|
||||
}),
|
||||
]);
|
||||
const serializedAudits = JSON.stringify(actionState.audits);
|
||||
expect(serializedAudits).not.toContain("private value");
|
||||
expect(serializedAudits).not.toContain("private response");
|
||||
expect(serializedAudits).not.toContain("decrypted-password");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["busy", "Another command is already running for this server."],
|
||||
["timeout", "The RCON request timed out."],
|
||||
["unavailable", "The RCON server was unavailable or rejected authentication."],
|
||||
] as const)("returns a safe %s failure without exposing transport details", async (reason, message) => {
|
||||
actionState.selected = [savedServer];
|
||||
actionState.gatewayResult = { ok: false, reason };
|
||||
const formData = new FormData();
|
||||
formData.set("serverId", serverId);
|
||||
formData.set("command", "list");
|
||||
|
||||
await expect(executeRconCommand({ status: "idle", message: "", serverId: "" }, formData)).resolves.toEqual({
|
||||
status: "error",
|
||||
message,
|
||||
serverId,
|
||||
});
|
||||
expect(JSON.stringify(actionState.audits)).not.toContain("decrypted-password");
|
||||
});
|
||||
|
||||
it("does not execute or audit when the enabled connection is unavailable", async () => {
|
||||
const formData = new FormData();
|
||||
formData.set("serverId", serverId);
|
||||
formData.set("command", "list");
|
||||
|
||||
await expect(executeRconCommand({ status: "idle", message: "", serverId: "" }, formData)).resolves.toEqual({
|
||||
status: "error",
|
||||
message: "That RCON connection is disabled or unavailable.",
|
||||
serverId,
|
||||
});
|
||||
expect(actionState.executions).toEqual([]);
|
||||
expect(actionState.audits).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,256 @@
|
||||
"use server";
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { events, rconServers } from "@minecraft-account-manager/database";
|
||||
import { getClientIp } from "@minecraft-account-manager/network";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { headers } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import { requireAdminSession } from "@/lib/auth/require-admin";
|
||||
import { db } from "@/lib/database";
|
||||
import { isUniqueConstraintViolation } from "@/lib/database-errors";
|
||||
import { decryptRconPassword, encryptRconPassword, rconCommandDigest } from "@/lib/rcon-credentials";
|
||||
import { executeRcon, testRconConnection } from "@/lib/rcon-gateway";
|
||||
import { recordAdminSubjectEvent } from "@/lib/audit";
|
||||
import { validateRconCommand, validateRconConnection } from "@/lib/rcon-validation";
|
||||
|
||||
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
|
||||
type Admin = Awaited<ReturnType<typeof requireAdminSession>>;
|
||||
export type RconCommandState = {
|
||||
status: "idle" | "success" | "error";
|
||||
message: string;
|
||||
serverId: string;
|
||||
};
|
||||
|
||||
function formConnection(formData: FormData, passwordRequired: boolean) {
|
||||
return validateRconConnection({
|
||||
name: formData.get("name"),
|
||||
host: formData.get("host"),
|
||||
port: formData.get("port"),
|
||||
password: formData.get("password"),
|
||||
}, { passwordRequired });
|
||||
}
|
||||
|
||||
async function auditContext() {
|
||||
const requestHeaders = await headers();
|
||||
return getClientIp(requestHeaders, process.env.TRUST_PROXY === "true");
|
||||
}
|
||||
|
||||
function auditData(admin: Admin, data: Record<string, unknown>) {
|
||||
return { ...data, adminEmail: admin.email, adminName: admin.name };
|
||||
}
|
||||
|
||||
function rconPath(query: string) {
|
||||
return `/admin/rcon?${query}`;
|
||||
}
|
||||
|
||||
export async function createRconServer(formData: FormData) {
|
||||
const admin = await requireAdminSession();
|
||||
const details = formConnection(formData, true);
|
||||
if (!details?.password) redirect(rconPath("error=invalid-connection"));
|
||||
const id = randomUUID();
|
||||
let encryptedPassword: string;
|
||||
try {
|
||||
encryptedPassword = encryptRconPassword(details.password, id);
|
||||
} catch {
|
||||
redirect(rconPath("error=configuration"));
|
||||
}
|
||||
const ipAddress = await auditContext();
|
||||
|
||||
try {
|
||||
await db.transaction(async (tx) => {
|
||||
await tx.insert(rconServers).values({
|
||||
id,
|
||||
name: details.name,
|
||||
host: details.host,
|
||||
port: details.port,
|
||||
encryptedPassword,
|
||||
enabled: formData.get("enabled") === "yes",
|
||||
});
|
||||
await tx.insert(events).values({
|
||||
id: randomUUID(),
|
||||
source: "/web/admin",
|
||||
type: "games.minecraft.account-manager.rcon.connection.created",
|
||||
subject: `rcon-server/${id}`,
|
||||
time: new Date(),
|
||||
data: auditData(admin, { name: details.name, host: details.host, port: details.port }),
|
||||
ipAddress: ipAddress ?? null,
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
if (isUniqueConstraintViolation(error, "rcon_servers_name_uidx")) redirect(rconPath("error=duplicate-name"));
|
||||
redirect(rconPath("error=save-failed"));
|
||||
}
|
||||
redirect(rconPath("saved=created"));
|
||||
}
|
||||
|
||||
export async function updateRconServer(formData: FormData) {
|
||||
const admin = await requireAdminSession();
|
||||
const serverId = String(formData.get("serverId") ?? "");
|
||||
const details = formConnection(formData, false);
|
||||
if (!UUID_PATTERN.test(serverId) || !details) redirect(rconPath("error=invalid-connection"));
|
||||
const ipAddress = await auditContext();
|
||||
|
||||
let result: string | null;
|
||||
try {
|
||||
result = await db.transaction(async (tx) => {
|
||||
await tx.execute(sql`select ${rconServers.id} from ${rconServers} where ${rconServers.id} = ${serverId} for update`);
|
||||
const [current] = await tx.select().from(rconServers).where(eq(rconServers.id, serverId)).limit(1);
|
||||
if (!current) return null;
|
||||
let encryptedPassword = current.encryptedPassword;
|
||||
if (details.password) encryptedPassword = encryptRconPassword(details.password, current.id);
|
||||
const enabled = formData.get("enabled") === "yes";
|
||||
await tx.update(rconServers).set({
|
||||
name: details.name,
|
||||
host: details.host,
|
||||
port: details.port,
|
||||
encryptedPassword,
|
||||
enabled,
|
||||
updatedAt: new Date(),
|
||||
}).where(eq(rconServers.id, current.id));
|
||||
await tx.insert(events).values({
|
||||
id: randomUUID(),
|
||||
source: "/web/admin",
|
||||
type: "games.minecraft.account-manager.rcon.connection.updated",
|
||||
subject: `rcon-server/${current.id}`,
|
||||
time: new Date(),
|
||||
data: auditData(admin, {
|
||||
name: details.name,
|
||||
host: details.host,
|
||||
port: details.port,
|
||||
enabled,
|
||||
passwordReplaced: Boolean(details.password),
|
||||
}),
|
||||
ipAddress: ipAddress ?? null,
|
||||
});
|
||||
return current.id;
|
||||
});
|
||||
} catch (error) {
|
||||
if (isUniqueConstraintViolation(error, "rcon_servers_name_uidx")) redirect(rconPath("error=duplicate-name"));
|
||||
redirect(rconPath("error=save-failed"));
|
||||
}
|
||||
if (!result) redirect(rconPath("error=unknown-connection"));
|
||||
redirect(rconPath("saved=updated"));
|
||||
}
|
||||
|
||||
export async function setRconServerEnabled(formData: FormData) {
|
||||
const admin = await requireAdminSession();
|
||||
const serverId = String(formData.get("serverId") ?? "");
|
||||
if (!UUID_PATTERN.test(serverId)) redirect(rconPath("error=unknown-connection"));
|
||||
const enabled = formData.get("enabled") === "yes";
|
||||
const ipAddress = await auditContext();
|
||||
|
||||
const result = await db.transaction(async (tx) => {
|
||||
await tx.execute(sql`select ${rconServers.id} from ${rconServers} where ${rconServers.id} = ${serverId} for update`);
|
||||
const [current] = await tx.select().from(rconServers).where(eq(rconServers.id, serverId)).limit(1);
|
||||
if (!current) return "missing" as const;
|
||||
if (enabled && !validateRconConnection({ ...current, password: "placeholder" }, { passwordRequired: true })) return "invalid" as const;
|
||||
await tx.update(rconServers).set({ enabled, updatedAt: new Date() }).where(eq(rconServers.id, current.id));
|
||||
await tx.insert(events).values({
|
||||
id: randomUUID(), source: "/web/admin", type: "games.minecraft.account-manager.rcon.connection.enabled-updated",
|
||||
subject: `rcon-server/${current.id}`, time: new Date(), data: auditData(admin, { name: current.name, enabled }), ipAddress: ipAddress ?? null,
|
||||
});
|
||||
return "updated" as const;
|
||||
});
|
||||
if (result === "missing") redirect(rconPath("error=unknown-connection"));
|
||||
if (result === "invalid") redirect(rconPath("error=invalid-connection"));
|
||||
redirect(rconPath(`saved=${enabled ? "enabled" : "disabled"}`));
|
||||
}
|
||||
|
||||
export async function deleteRconServer(formData: FormData) {
|
||||
const admin = await requireAdminSession();
|
||||
const serverId = String(formData.get("serverId") ?? "");
|
||||
if (!UUID_PATTERN.test(serverId) || formData.get("confirmation") !== serverId) redirect(rconPath("error=confirmation-required"));
|
||||
const ipAddress = await auditContext();
|
||||
|
||||
const deleted = await db.transaction(async (tx) => {
|
||||
const [server] = await tx.delete(rconServers).where(eq(rconServers.id, serverId)).returning({ id: rconServers.id, name: rconServers.name });
|
||||
if (!server) return null;
|
||||
await tx.insert(events).values({
|
||||
id: randomUUID(), source: "/web/admin", type: "games.minecraft.account-manager.rcon.connection.deleted",
|
||||
subject: `rcon-server/${server.id}`, time: new Date(), data: auditData(admin, { name: server.name }), ipAddress: ipAddress ?? null,
|
||||
});
|
||||
return server;
|
||||
});
|
||||
if (!deleted) redirect(rconPath("error=unknown-connection"));
|
||||
redirect(rconPath("saved=deleted"));
|
||||
}
|
||||
|
||||
async function savedConnection(serverId: string, requireEnabled: boolean) {
|
||||
if (!UUID_PATTERN.test(serverId)) return null;
|
||||
const [server] = await db.select().from(rconServers).where(requireEnabled
|
||||
? and(eq(rconServers.id, serverId), eq(rconServers.enabled, true))
|
||||
: eq(rconServers.id, serverId)).limit(1);
|
||||
if (!server) return null;
|
||||
const validated = validateRconConnection({ ...server, password: "placeholder" }, { passwordRequired: true });
|
||||
if (!validated) return null;
|
||||
try {
|
||||
return { ...server, password: decryptRconPassword(server.encryptedPassword, server.id) };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function testSavedRconServer(formData: FormData) {
|
||||
const admin = await requireAdminSession();
|
||||
const serverId = String(formData.get("serverId") ?? "");
|
||||
const server = await savedConnection(serverId, false);
|
||||
if (!server) redirect(rconPath("error=connection-unavailable"));
|
||||
const started = Date.now();
|
||||
const result = await testRconConnection(server);
|
||||
await recordAdminSubjectEvent(admin, `rcon-server/${server.id}`, "games.minecraft.account-manager.rcon.connection.tested", {
|
||||
serverId: server.id,
|
||||
name: server.name,
|
||||
success: result.ok,
|
||||
reason: result.ok ? null : result.reason,
|
||||
durationMs: Date.now() - started,
|
||||
});
|
||||
redirect(rconPath(result.ok ? "saved=tested" : `error=test-${result.reason}`));
|
||||
}
|
||||
|
||||
export async function executeRconCommand(
|
||||
_previous: RconCommandState,
|
||||
formData: FormData,
|
||||
): Promise<RconCommandState> {
|
||||
const admin = await requireAdminSession();
|
||||
const serverId = String(formData.get("serverId") ?? "");
|
||||
const command = validateRconCommand(formData.get("command"));
|
||||
if (!command) return { status: "error", message: "Enter one command of at most 1,024 bytes without control characters.", serverId };
|
||||
const server = await savedConnection(serverId, true);
|
||||
if (!server) return { status: "error", message: "That RCON connection is disabled or unavailable.", serverId };
|
||||
const verb = command.split(/\s+/u, 1)[0]!.toLowerCase().slice(0, 64);
|
||||
let commandDigest: string;
|
||||
try {
|
||||
commandDigest = rconCommandDigest(command);
|
||||
} catch {
|
||||
return { status: "error", message: "RCON command auditing is not configured.", serverId };
|
||||
}
|
||||
const started = Date.now();
|
||||
|
||||
await recordAdminSubjectEvent(admin, `rcon-server/${server.id}`, "games.minecraft.account-manager.rcon.command.requested", {
|
||||
serverId: server.id,
|
||||
name: server.name,
|
||||
verb,
|
||||
commandDigest,
|
||||
});
|
||||
const result = await executeRcon(server, command);
|
||||
await recordAdminSubjectEvent(admin, `rcon-server/${server.id}`, "games.minecraft.account-manager.rcon.command.completed", {
|
||||
serverId: server.id,
|
||||
name: server.name,
|
||||
verb,
|
||||
commandDigest,
|
||||
success: result.ok,
|
||||
reason: result.ok ? null : result.reason,
|
||||
durationMs: Date.now() - started,
|
||||
});
|
||||
if (!result.ok) {
|
||||
const message = result.reason === "busy"
|
||||
? "Another command is already running for this server."
|
||||
: result.reason === "timeout"
|
||||
? "The RCON request timed out."
|
||||
: "The RCON server was unavailable or rejected authentication.";
|
||||
return { status: "error", message, serverId };
|
||||
}
|
||||
return { status: "success", message: result.response || "Command completed with no response.", serverId };
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { rconServers } from "@minecraft-account-manager/database";
|
||||
import { asc } from "drizzle-orm";
|
||||
import { RconConsole } from "@/components/rcon-console";
|
||||
import { db } from "@/lib/database";
|
||||
import {
|
||||
createRconServer,
|
||||
deleteRconServer,
|
||||
setRconServerEnabled,
|
||||
testSavedRconServer,
|
||||
updateRconServer,
|
||||
} from "./actions";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const savedMessages: Record<string, string> = {
|
||||
created: "RCON connection created.",
|
||||
updated: "RCON connection updated.",
|
||||
enabled: "RCON connection enabled.",
|
||||
disabled: "RCON connection disabled.",
|
||||
deleted: "RCON connection deleted.",
|
||||
tested: "RCON authentication succeeded.",
|
||||
};
|
||||
|
||||
const errorMessages: Record<string, string> = {
|
||||
"invalid-connection": "Enter a valid allowlisted hostname, port, name, and password.",
|
||||
"duplicate-name": "Connection names must be unique.",
|
||||
configuration: "RCON credential encryption is not configured.",
|
||||
"save-failed": "The RCON connection could not be saved.",
|
||||
"unknown-connection": "That RCON connection no longer exists.",
|
||||
"confirmation-required": "Confirm the connection before deleting it.",
|
||||
"connection-unavailable": "The connection is invalid or its credential is unavailable.",
|
||||
"test-busy": "Another RCON operation is already using that server.",
|
||||
"test-timeout": "RCON authentication timed out.",
|
||||
"test-unavailable": "The RCON server was unavailable or rejected authentication.",
|
||||
};
|
||||
|
||||
function queryValue(value: string | string[] | undefined) {
|
||||
return Array.isArray(value) ? value[0] : value;
|
||||
}
|
||||
|
||||
export default async function RconPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<Record<string, string | string[] | undefined>>;
|
||||
}) {
|
||||
const query = await searchParams;
|
||||
const saved = queryValue(query.saved);
|
||||
const error = queryValue(query.error);
|
||||
const servers = await db.select({
|
||||
id: rconServers.id,
|
||||
name: rconServers.name,
|
||||
host: rconServers.host,
|
||||
port: rconServers.port,
|
||||
enabled: rconServers.enabled,
|
||||
updatedAt: rconServers.updatedAt,
|
||||
}).from(rconServers).orderBy(asc(rconServers.name));
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-6xl px-6 py-14">
|
||||
<header className="border-b border-line pb-8">
|
||||
<p className="font-mono text-xs font-bold uppercase tracking-[0.25em] text-accent">Server operations</p>
|
||||
<h1 className="mt-4 font-display text-5xl font-black uppercase sm:text-7xl">RCON</h1>
|
||||
<p className="mt-5 max-w-2xl text-sm leading-6 text-muted">Run commands through the portal backend. RCON endpoints remain internal and credentials are never sent to the browser.</p>
|
||||
</header>
|
||||
|
||||
{saved && <p className="mt-7 border-l-2 border-signal bg-panel px-5 py-4 font-mono text-xs font-bold uppercase tracking-wider" role="status">{savedMessages[saved] ?? "RCON settings saved."}</p>}
|
||||
{error && <p className="mt-7 border-l-2 border-accent bg-panel px-5 py-4 text-sm text-accent" role="alert">{errorMessages[error] ?? "The RCON operation failed."}</p>}
|
||||
|
||||
<div className="mt-10 grid gap-10 lg:grid-cols-[1.1fr_0.9fr]">
|
||||
<section className="border border-line bg-panel p-6 shadow-[6px_6px_0_var(--color-shadow)]">
|
||||
<p className="font-mono text-[9px] font-bold uppercase tracking-widest text-muted">Command proxy</p>
|
||||
<h2 className="mt-2 font-display text-3xl font-black uppercase">Console</h2>
|
||||
<p className="mt-3 text-xs leading-5 text-muted">Only the latest bounded response is shown. Commands and responses are not saved as console history.</p>
|
||||
<RconConsole servers={servers.filter((server) => server.enabled).map(({ id, name }) => ({ id, name }))} />
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<p className="font-mono text-[9px] font-bold uppercase tracking-widest text-muted">Configuration</p>
|
||||
<h2 className="mt-2 font-display text-3xl font-black uppercase">Add connection</h2>
|
||||
<form action={createRconServer} className="mt-5 space-y-4 border border-line bg-panel p-6">
|
||||
<ConnectionFields prefix="new" />
|
||||
<label className="flex items-center gap-3 font-mono text-[10px] font-bold uppercase"><input className="size-4" name="enabled" type="checkbox" value="yes" />Enable immediately</label>
|
||||
<button className="border border-ink bg-ink px-5 py-3 font-mono text-[10px] font-bold uppercase tracking-wider text-canvas" type="submit">Add connection</button>
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section className="mt-12">
|
||||
<div className="flex items-end justify-between border-b border-line pb-4">
|
||||
<div><p className="font-mono text-[9px] font-bold uppercase tracking-widest text-muted">Saved endpoints</p><h2 className="mt-2 font-display text-3xl font-black uppercase">Connections</h2></div>
|
||||
<span className="font-mono text-xs text-muted">{servers.length} configured</span>
|
||||
</div>
|
||||
<div className="divide-y divide-line">
|
||||
{servers.map((server) => (
|
||||
<article className="grid gap-5 py-6 lg:grid-cols-[1fr_auto] lg:items-start" key={server.id}>
|
||||
<div>
|
||||
<div className="flex flex-wrap items-center gap-3"><h3 className="font-mono text-lg font-bold">{server.name}</h3><span className={`px-2 py-1 font-mono text-[9px] font-bold uppercase ${server.enabled ? "bg-signal text-ink" : "border border-line text-muted"}`}>{server.enabled ? "Enabled" : "Disabled"}</span></div>
|
||||
<p className="mt-2 font-mono text-[10px] text-muted">{server.host}:{server.port}</p>
|
||||
<p className="mt-1 font-mono text-[9px] text-muted">Updated {server.updatedAt.toISOString()}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-start gap-4">
|
||||
<form action={testSavedRconServer}><input name="serverId" type="hidden" value={server.id} /><button className="font-mono text-[9px] font-bold uppercase underline underline-offset-4" type="submit">Test</button></form>
|
||||
<form action={setRconServerEnabled}><input name="serverId" type="hidden" value={server.id} /><input name="enabled" type="hidden" value={server.enabled ? "no" : "yes"} /><button className="font-mono text-[9px] font-bold uppercase underline underline-offset-4" type="submit">{server.enabled ? "Disable" : "Enable"}</button></form>
|
||||
<details className="relative">
|
||||
<summary className="cursor-pointer list-none font-mono text-[9px] font-bold uppercase underline underline-offset-4">Edit</summary>
|
||||
<form action={updateRconServer} className="relative z-10 mt-3 w-[min(28rem,80vw)] space-y-4 border border-line bg-panel p-5 shadow-[5px_5px_0_var(--color-shadow)] lg:absolute lg:right-0">
|
||||
<input name="serverId" type="hidden" value={server.id} />
|
||||
<ConnectionFields defaults={server} prefix={server.id} />
|
||||
<label className="flex items-center gap-3 font-mono text-[10px] font-bold uppercase"><input className="size-4" defaultChecked={server.enabled} name="enabled" type="checkbox" value="yes" />Enabled</label>
|
||||
<button className="border border-ink px-4 py-2 font-mono text-[9px] font-bold uppercase" type="submit">Save connection</button>
|
||||
</form>
|
||||
</details>
|
||||
<details className="relative">
|
||||
<summary className="cursor-pointer list-none font-mono text-[9px] font-bold uppercase text-accent underline underline-offset-4">Delete</summary>
|
||||
<form action={deleteRconServer} className="relative z-10 mt-3 w-64 border border-accent bg-panel p-5 shadow-[5px_5px_0_var(--color-accent)] lg:absolute lg:right-0">
|
||||
<input name="serverId" type="hidden" value={server.id} /><input name="confirmation" type="hidden" value={server.id} />
|
||||
<p className="text-xs leading-5">Delete {server.name}? Its encrypted credential will be removed.</p>
|
||||
<button className="mt-4 bg-accent px-4 py-2 font-mono text-[9px] font-bold uppercase text-canvas" type="submit">Confirm deletion</button>
|
||||
</form>
|
||||
</details>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
{!servers.length && <p className="py-8 text-sm text-muted">No RCON connections configured.</p>}
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function ConnectionFields({
|
||||
prefix,
|
||||
defaults,
|
||||
}: {
|
||||
prefix: string;
|
||||
defaults?: { name: string; host: string; port: number };
|
||||
}) {
|
||||
const fieldClass = "mt-2 block w-full border border-line bg-canvas px-4 py-3 font-mono text-sm outline-none focus:border-accent";
|
||||
return (
|
||||
<>
|
||||
<label className="block font-mono text-[10px] font-bold uppercase" htmlFor={`${prefix}-rcon-name`}>Name<input className={fieldClass} defaultValue={defaults?.name} id={`${prefix}-rcon-name`} maxLength={100} name="name" required /></label>
|
||||
<label className="block font-mono text-[10px] font-bold uppercase" htmlFor={`${prefix}-rcon-host`}>Internal hostname<input autoCapitalize="none" autoCorrect="off" className={fieldClass} defaultValue={defaults?.host} id={`${prefix}-rcon-host`} maxLength={253} name="host" placeholder="season4.somc.svc.cluster.local" required spellCheck={false} /></label>
|
||||
<label className="block font-mono text-[10px] font-bold uppercase" htmlFor={`${prefix}-rcon-port`}>Port<input className={fieldClass} defaultValue={defaults?.port ?? 25575} id={`${prefix}-rcon-port`} max={65535} min={1} name="port" required type="number" /></label>
|
||||
<label className="block font-mono text-[10px] font-bold uppercase" htmlFor={`${prefix}-rcon-password`}>{defaults ? "Replacement password" : "Password"}<input autoComplete="new-password" className={fieldClass} id={`${prefix}-rcon-password`} maxLength={512} name="password" required={!defaults} type="password" />{defaults && <span className="mt-2 block font-sans text-[10px] font-normal normal-case text-muted">Leave blank to preserve the current password.</span>}</label>
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user