feat(rcon): add command history navigation
This commit is contained in:
@@ -1,10 +1,21 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
|
||||||
|
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||||
import { renderToStaticMarkup } from "react-dom/server";
|
import { renderToStaticMarkup } from "react-dom/server";
|
||||||
import { describe, expect, it, vi } from "vitest";
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
const actionMocks = vi.hoisted(() => ({
|
||||||
|
execute: vi.fn(async (_previous: unknown, formData: FormData) => ({
|
||||||
|
status: "success" as const,
|
||||||
|
message: `Executed ${String(formData.get("command") ?? "")}`,
|
||||||
|
serverId: String(formData.get("serverId") ?? ""),
|
||||||
|
})),
|
||||||
|
}));
|
||||||
|
|
||||||
vi.mock("@/app/admin/(console)/rcon/actions", () => ({
|
vi.mock("@/app/admin/(console)/rcon/actions", () => ({
|
||||||
createRconServer: vi.fn(),
|
createRconServer: vi.fn(),
|
||||||
deleteRconServer: vi.fn(),
|
deleteRconServer: vi.fn(),
|
||||||
executeRconCommand: vi.fn(),
|
executeRconCommand: actionMocks.execute,
|
||||||
setRconServerEnabled: vi.fn(),
|
setRconServerEnabled: vi.fn(),
|
||||||
testSavedRconServer: vi.fn(),
|
testSavedRconServer: vi.fn(),
|
||||||
updateRconServer: vi.fn(),
|
updateRconServer: vi.fn(),
|
||||||
@@ -12,6 +23,8 @@ vi.mock("@/app/admin/(console)/rcon/actions", () => ({
|
|||||||
|
|
||||||
import { RconConsole } from "./rcon-console";
|
import { RconConsole } from "./rcon-console";
|
||||||
|
|
||||||
|
afterEach(() => cleanup());
|
||||||
|
|
||||||
const server = {
|
const server = {
|
||||||
id: "11111111-1111-4111-8111-111111111111",
|
id: "11111111-1111-4111-8111-111111111111",
|
||||||
name: "Season 4",
|
name: "Season 4",
|
||||||
@@ -20,6 +33,13 @@ const server = {
|
|||||||
enabled: true,
|
enabled: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const creative = {
|
||||||
|
...server,
|
||||||
|
id: "22222222-2222-4222-8222-222222222222",
|
||||||
|
name: "Creative",
|
||||||
|
host: "creative.example.com",
|
||||||
|
};
|
||||||
|
|
||||||
describe("RconConsole", () => {
|
describe("RconConsole", () => {
|
||||||
it("renders one wide terminal workspace with connection controls and modal forms", () => {
|
it("renders one wide terminal workspace with connection controls and modal forms", () => {
|
||||||
const markup = renderToStaticMarkup(<RconConsole servers={[server]} />);
|
const markup = renderToStaticMarkup(<RconConsole servers={[server]} />);
|
||||||
@@ -56,4 +76,37 @@ describe("RconConsole", () => {
|
|||||||
expect(markup).not.toContain("Edit");
|
expect(markup).not.toContain("Edit");
|
||||||
expect(markup).not.toContain("Delete");
|
expect(markup).not.toContain("Delete");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("navigates page-memory command history and restores the unsent draft", async () => {
|
||||||
|
render(<RconConsole servers={[server]} />);
|
||||||
|
const input = screen.getByLabelText("Command") as HTMLInputElement;
|
||||||
|
|
||||||
|
fireEvent.change(input, { target: { value: "list" } });
|
||||||
|
fireEvent.submit(input.form!);
|
||||||
|
await waitFor(() => expect(screen.getByText("Executed list")).toBeTruthy());
|
||||||
|
expect(document.activeElement).toBe(input);
|
||||||
|
expect(input.value).toBe("");
|
||||||
|
|
||||||
|
fireEvent.change(input, { target: { value: "say hello" } });
|
||||||
|
fireEvent.submit(input.form!);
|
||||||
|
await waitFor(() => expect(screen.getByText("Executed say hello")).toBeTruthy());
|
||||||
|
|
||||||
|
fireEvent.change(input, { target: { value: "draft command" } });
|
||||||
|
fireEvent.keyDown(input, { key: "ArrowUp" });
|
||||||
|
expect(input.value).toBe("say hello");
|
||||||
|
fireEvent.keyDown(input, { key: "ArrowUp" });
|
||||||
|
expect(input.value).toBe("list");
|
||||||
|
fireEvent.keyDown(input, { key: "ArrowDown" });
|
||||||
|
expect(input.value).toBe("say hello");
|
||||||
|
fireEvent.keyDown(input, { key: "ArrowDown" });
|
||||||
|
expect(input.value).toBe("draft command");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns focus to the command prompt after changing servers", async () => {
|
||||||
|
render(<RconConsole servers={[server, creative]} />);
|
||||||
|
const select = screen.getByLabelText("Server");
|
||||||
|
select.focus();
|
||||||
|
fireEvent.change(select, { target: { value: creative.id } });
|
||||||
|
await waitFor(() => expect(document.activeElement).toBe(screen.getByLabelText("Command")));
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useActionState, useState } from "react";
|
import { useActionState, useEffect, useRef, useState } from "react";
|
||||||
import {
|
import {
|
||||||
createRconServer,
|
createRconServer,
|
||||||
deleteRconServer,
|
deleteRconServer,
|
||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
import { AdminModalForm } from "@/components/admin-modal-form";
|
import { AdminModalForm } from "@/components/admin-modal-form";
|
||||||
|
|
||||||
const initialState: RconCommandState = { status: "idle", message: "", serverId: "" };
|
const initialState: RconCommandState = { status: "idle", message: "", serverId: "" };
|
||||||
|
const MAX_COMMAND_HISTORY = 50;
|
||||||
|
|
||||||
export type RconServerOption = {
|
export type RconServerOption = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -36,10 +37,52 @@ export function RconConsole({
|
|||||||
}) {
|
}) {
|
||||||
const [selectedId, setSelectedId] = useState(servers[0]?.id ?? "");
|
const [selectedId, setSelectedId] = useState(servers[0]?.id ?? "");
|
||||||
const [state, action, pending] = useActionState(executeRconCommand, initialState);
|
const [state, action, pending] = useActionState(executeRconCommand, initialState);
|
||||||
|
const [command, setCommand] = useState("");
|
||||||
|
const [history, setHistory] = useState<string[]>([]);
|
||||||
|
const [historyIndex, setHistoryIndex] = useState<number | null>(null);
|
||||||
|
const draftRef = useRef("");
|
||||||
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
const selected = servers.find((server) => server.id === selectedId) ?? servers[0];
|
const selected = servers.find((server) => server.id === selectedId) ?? servers[0];
|
||||||
const responseServer = servers.find((server) => server.id === state.serverId);
|
const responseServer = servers.find((server) => server.id === state.serverId);
|
||||||
const output = terminalOutput({ notice, pending, responseServer, selected, state });
|
const output = terminalOutput({ notice, pending, responseServer, selected, state });
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
inputRef.current?.focus();
|
||||||
|
}, [selectedId]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!pending && state.status !== "idle") inputRef.current?.focus();
|
||||||
|
}, [pending, state.status]);
|
||||||
|
|
||||||
|
function navigateHistory(direction: "older" | "newer") {
|
||||||
|
if (!history.length) return;
|
||||||
|
if (direction === "older") {
|
||||||
|
const nextIndex = historyIndex === null ? history.length - 1 : Math.max(0, historyIndex - 1);
|
||||||
|
if (historyIndex === null) draftRef.current = command;
|
||||||
|
setHistoryIndex(nextIndex);
|
||||||
|
setCommand(history[nextIndex]!);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (historyIndex === null) return;
|
||||||
|
if (historyIndex < history.length - 1) {
|
||||||
|
const nextIndex = historyIndex + 1;
|
||||||
|
setHistoryIndex(nextIndex);
|
||||||
|
setCommand(history[nextIndex]!);
|
||||||
|
} else {
|
||||||
|
setHistoryIndex(null);
|
||||||
|
setCommand(draftRef.current);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function rememberSubmittedCommand() {
|
||||||
|
const submitted = command.trim();
|
||||||
|
if (!submitted) return;
|
||||||
|
setHistory((current) => [...current, submitted].slice(-MAX_COMMAND_HISTORY));
|
||||||
|
setHistoryIndex(null);
|
||||||
|
draftRef.current = "";
|
||||||
|
setCommand("");
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section aria-label="RCON terminal" className="mt-8 w-full overflow-hidden border-2 border-ink bg-panel shadow-[8px_8px_0_var(--color-shadow)]">
|
<section aria-label="RCON terminal" className="mt-8 w-full overflow-hidden border-2 border-ink bg-panel shadow-[8px_8px_0_var(--color-shadow)]">
|
||||||
<div className="flex flex-col gap-4 border-b-2 border-ink bg-canvas px-4 py-4 lg:flex-row lg:items-center lg:justify-between">
|
<div className="flex flex-col gap-4 border-b-2 border-ink bg-canvas px-4 py-4 lg:flex-row lg:items-center lg:justify-between">
|
||||||
@@ -102,7 +145,7 @@ export function RconConsole({
|
|||||||
<pre className="mt-3 whitespace-pre-wrap break-words font-mono text-xs leading-5">{output.message}</pre>
|
<pre className="mt-3 whitespace-pre-wrap break-words font-mono text-xs leading-5">{output.message}</pre>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<form action={action} className="flex items-center gap-3 border-t-2 border-ink bg-canvas p-3">
|
<form action={action} className="flex items-center gap-3 border-t-2 border-ink bg-canvas p-3" onSubmit={rememberSubmittedCommand}>
|
||||||
<input name="serverId" type="hidden" value={selected?.id ?? ""} />
|
<input name="serverId" type="hidden" value={selected?.id ?? ""} />
|
||||||
<span aria-hidden="true" className="font-mono text-lg font-black text-accent">$</span>
|
<span aria-hidden="true" className="font-mono text-lg font-black text-accent">$</span>
|
||||||
<label className="sr-only" htmlFor="rcon-command">Command</label>
|
<label className="sr-only" htmlFor="rcon-command">Command</label>
|
||||||
@@ -115,9 +158,18 @@ export function RconConsole({
|
|||||||
key={selected?.id ?? "no-server"}
|
key={selected?.id ?? "no-server"}
|
||||||
maxLength={1024}
|
maxLength={1024}
|
||||||
name="command"
|
name="command"
|
||||||
|
onChange={(event) => setCommand(event.target.value)}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === "ArrowUp" || event.key === "ArrowDown") {
|
||||||
|
event.preventDefault();
|
||||||
|
navigateHistory(event.key === "ArrowUp" ? "older" : "newer");
|
||||||
|
}
|
||||||
|
}}
|
||||||
placeholder={selected ? (selected.enabled ? "list" : "Enable this connection to run commands") : "Add a connection to begin"}
|
placeholder={selected ? (selected.enabled ? "list" : "Enable this connection to run commands") : "Add a connection to begin"}
|
||||||
|
ref={inputRef}
|
||||||
required
|
required
|
||||||
spellCheck={false}
|
spellCheck={false}
|
||||||
|
value={command}
|
||||||
/>
|
/>
|
||||||
<button className="border border-ink bg-ink px-4 py-2 font-mono text-[9px] font-bold uppercase tracking-wider text-canvas disabled:cursor-not-allowed disabled:opacity-50" disabled={!selected?.enabled || pending} type="submit">{pending ? "Running…" : "Enter ↵"}</button>
|
<button className="border border-ink bg-ink px-4 py-2 font-mono text-[9px] font-bold uppercase tracking-wider text-canvas disabled:cursor-not-allowed disabled:opacity-50" disabled={!selected?.enabled || pending} type="submit">{pending ? "Running…" : "Enter ↵"}</button>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
* **Verify**: Confirmed the RCON console uses an authenticated internal ClusterIP deployment with secret-backed credentials and no public RCON exposure.
|
* **Verify**: Confirmed the RCON console uses an authenticated internal ClusterIP deployment with secret-backed credentials and no public RCON exposure.
|
||||||
* **Refine**: Renamed RCON host configuration to server addresses, documented internal and external targets, and redesigned the console as a portal-colored terminal with a target bar, command prompt, and latest-response viewport.
|
* **Refine**: Renamed RCON host configuration to server addresses, documented internal and external targets, and redesigned the console as a portal-colored terminal with a target bar, command prompt, and latest-response viewport.
|
||||||
* **Refine**: Consolidated RCON connection management into a full-width terminal workspace with header controls, modal add/edit/delete flows, terminal-contained notices, and no duplicate configuration panels.
|
* **Refine**: Consolidated RCON connection management into a full-width terminal workspace with header controls, modal add/edit/delete flows, terminal-contained notices, and no duplicate configuration panels.
|
||||||
|
* **Extend**: Added bounded page-memory RCON command recall with Arrow Up/Arrow Down navigation, unsent-draft restoration, and prompt focus retention after results and server changes.
|
||||||
|
|
||||||
## 2026-08-07
|
## 2026-08-07
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ type: User Story
|
|||||||
title: Operate servers through an RCON console
|
title: Operate servers through an RCON console
|
||||||
description: Administrators execute bounded RCON commands through the server-side portal proxy.
|
description: Administrators execute bounded RCON commands through the server-side portal proxy.
|
||||||
tags: [admin, rcon, minecraft, console, security]
|
tags: [admin, rcon, minecraft, console, security]
|
||||||
timestamp: 2026-08-08T13:40:43Z
|
timestamp: 2026-08-08T14:06:09Z
|
||||||
story_id: US-022
|
story_id: US-022
|
||||||
status: verified
|
status: verified
|
||||||
---
|
---
|
||||||
@@ -18,21 +18,23 @@ As an administrator, I want an RCON console in the portal, so that I can operate
|
|||||||
- [x] Browsers never connect to RCON directly; commands pass through the authenticated Next.js server runtime to the configured endpoint.
|
- [x] Browsers never connect to RCON directly; commands pass through the authenticated Next.js server runtime to the configured endpoint.
|
||||||
- [x] Every command independently rechecks administrator authorization and the selected connection's enabled state.
|
- [x] Every command independently rechecks administrator authorization and the selected connection's enabled state.
|
||||||
- [x] Commands are length-limited, reject control characters, execute with bounded concurrency and a timeout, and return bounded output.
|
- [x] Commands are length-limited, reject control characters, execute with bounded concurrency and a timeout, and return bounded output.
|
||||||
- [x] Command responses are displayed safely and are not persisted in console history, audit data, or application logs.
|
- [x] Command responses are displayed safely, and commands and responses are not persisted in browser storage, audit data, or application logs.
|
||||||
- [x] Audit events record the administrator, connection, command verb and digest, success, and duration without recording complete commands or responses.
|
- [x] Audit events record the administrator, connection, command verb and digest, success, and duration without recording complete commands or responses.
|
||||||
- [x] Authentication, timeout, and connection failures return safe operator-facing messages without credentials or stack traces.
|
- [x] Authentication, timeout, and connection failures return safe operator-facing messages without credentials or stack traces.
|
||||||
- [x] The console spans the available content width and uses the portal color palette to present a terminal-style server header with connection controls, a single keyboard-accessible prompt, pending state, and scrollable latest-response viewport.
|
- [x] The console spans the available content width and uses the portal color palette to present a terminal-style server header with connection controls, a single keyboard-accessible prompt, pending state, and scrollable latest-response viewport.
|
||||||
- [x] Configured server addresses may be internal or external, and operators receive guidance that RCON network exposure and transport security remain their responsibility.
|
- [x] Configured server addresses may be internal or external, and operators receive guidance that RCON network exposure and transport security remain their responsibility.
|
||||||
- [x] Command responses, connection errors, and connection-operation results appear in the terminal viewport, including an actionable empty state when no connection exists.
|
- [x] Command responses, connection errors, and connection-operation results appear in the terminal viewport, including an actionable empty state when no connection exists.
|
||||||
- [x] The page has no duplicate connection form or connection-list panel outside the terminal workspace.
|
- [x] The page has no duplicate connection form or connection-list panel outside the terminal workspace.
|
||||||
|
- [x] A bounded page-memory-only history lets administrators use Arrow Up and Arrow Down to recall and edit commands, then restore the unsent draft after the newest history entry.
|
||||||
|
- [x] After each command result and server selection change, focus returns to the command input for immediate editing or resubmission.
|
||||||
|
|
||||||
# Implementation
|
# Implementation
|
||||||
|
|
||||||
The full-width portal-colored terminal workspace identifies and manages the selected server in its header, accepts one command through a keyboard-focused prompt, and displays command responses plus connection-operation notices in one scrollable viewport. It retains an actionable terminal and Add control when no connections exist, with no duplicate configuration panels. The client invokes an authenticated server action that revalidates the enabled connection, decrypts its credential only in the server runtime, and executes one bounded command. The gateway limits each process to one operation per server and eight total operations, applies a five-second end-to-end deadline plus bounded cleanup, sanitizes and truncates output, and records keyed command lifecycle audits without command or response content.
|
The full-width portal-colored terminal workspace identifies and manages the selected server in its header, accepts one command through a keyboard-focused prompt, and displays command responses plus connection-operation notices in one scrollable viewport. It retains an actionable terminal and Add control when no connections exist, with no duplicate configuration panels. Up to 50 submitted commands remain only in page memory for editable Arrow Up/Arrow Down recall, including restoration of the current unsent draft; focus returns to the prompt after command results and server changes. The client invokes an authenticated server action that revalidates the enabled connection, decrypts its credential only in the server runtime, and executes one bounded command. The gateway limits each process to one operation per server and eight total operations, applies a five-second end-to-end deadline plus bounded cleanup, sanitizes and truncates output, and records keyed command lifecycle audits without command or response content.
|
||||||
|
|
||||||
# Validation
|
# Validation
|
||||||
|
|
||||||
Application behavior is verified with gateway, validation, component, credential, and server-action tests; full workspace tests and type checks; web lint; OKF validation; Semgrep; dependency audit; and a production Next.js build on 2026-08-08. Component validation confirms the full-width workspace, labelled server and command controls, header actions, accessible modal forms, terminal-contained notices, and the actionable no-server state. The SoMC GitOps deployment verifies Season 4 RCON through an authenticated internal ClusterIP Service backed by a Kubernetes Secret while product guidance also covers external server addresses.
|
Application behavior is verified with gateway, validation, component, credential, and server-action tests; full workspace tests and type checks; web lint; OKF validation; Semgrep; dependency audit; and a production Next.js build on 2026-08-08. Component validation confirms the full-width workspace, labelled server and command controls, header actions, accessible modal forms, terminal-contained notices, the actionable no-server state, editable command-history navigation with draft restoration, and prompt focus after command results and server changes. The SoMC GitOps deployment verifies Season 4 RCON through an authenticated internal ClusterIP Service backed by a Kubernetes Secret while product guidance also covers external server addresses.
|
||||||
|
|
||||||
# Related Stories
|
# Related Stories
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -23,7 +23,7 @@ The password entered in the administrator connection form must match the server
|
|||||||
- Each web process allows one operation per connection and at most eight RCON operations total. Size replica counts with that aggregate ceiling in mind.
|
- Each web process allows one operation per connection and at most eight RCON operations total. Size replica counts with that aggregate ceiling in mind.
|
||||||
- Each complete connect-and-response operation times out after five seconds and tears down the socket; cleanup is independently capped at one second.
|
- Each complete connect-and-response operation times out after five seconds and tears down the socket; cleanup is independently capped at one second.
|
||||||
- Responses are sanitized and limited to 64 KiB.
|
- Responses are sanitized and limited to 64 KiB.
|
||||||
- Full commands and responses are not persisted or logged. Audit events contain the command verb and a domain-separated HMAC digest.
|
- Up to 50 submitted commands remain only in page memory for Arrow Up/Arrow Down recall and are discarded on reload; commands and responses are never written to browser storage, application persistence, or logs. Audit events contain the command verb and a domain-separated HMAC digest.
|
||||||
- Connection passwords are never selected by page queries or returned to the browser.
|
- Connection passwords are never selected by page queries or returned to the browser.
|
||||||
|
|
||||||
RCON is plaintext TCP. Internal deployments should use network policy; external connections should use private routing, a VPN, or an encrypted tunnel rather than direct public exposure.
|
RCON is plaintext TCP. Internal deployments should use network policy; external connections should use private routing, a VPN, or an encrypted tunnel rather than direct public exposure.
|
||||||
|
|||||||
Reference in New Issue
Block a user