Merge pull request #959 from szwabodev/feat/localServerTerminal

feat: local server terminal access
This commit is contained in:
Mauricio Siu
2024-12-29 18:06:32 -06:00
committed by GitHub
12 changed files with 341 additions and 34 deletions

View File

@@ -16,6 +16,7 @@ import { useTranslation } from "next-i18next";
import { toast } from "sonner";
import { ShowModalLogs } from "../../web-server/show-modal-logs";
import { GPUSupportModal } from "../gpu-support-modal";
import { TerminalModal } from "../../web-server/terminal-modal";
export const ShowDokployActions = () => {
const { t } = useTranslation("settings");
@@ -49,6 +50,9 @@ export const ShowDokployActions = () => {
>
<span>{t("settings.server.webServer.reload")}</span>
</DropdownMenuItem>
<TerminalModal serverId="local">
<span>{t("settings.common.enterTerminal")}</span>
</TerminalModal>
<ShowModalLogs appName="dokploy">
<DropdownMenuItem
className="cursor-pointer"

View File

@@ -31,8 +31,8 @@ import { Textarea } from "@/components/ui/textarea";
import { api } from "@/utils/api";
import { zodResolver } from "@hookform/resolvers/zod";
import { PlusIcon } from "lucide-react";
import { useTranslation } from "next-i18next";
import Link from "next/link";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
@@ -56,6 +56,8 @@ const Schema = z.object({
type Schema = z.infer<typeof Schema>;
export const AddServer = () => {
const { t } = useTranslation("settings");
const utils = api.useUtils();
const [isOpen, setIsOpen] = useState(false);
const { data: canCreateMoreServers, refetch } =
@@ -212,7 +214,7 @@ export const AddServer = () => {
name="ipAddress"
render={({ field }) => (
<FormItem>
<FormLabel>IP Address</FormLabel>
<FormLabel>{t("settings.terminal.ipAddress")}</FormLabel>
<FormControl>
<Input placeholder="192.168.1.100" {...field} />
</FormControl>
@@ -226,7 +228,7 @@ export const AddServer = () => {
name="port"
render={({ field }) => (
<FormItem>
<FormLabel>Port</FormLabel>
<FormLabel>{t("settings.terminal.port")}</FormLabel>
<FormControl>
<Input
placeholder="22"
@@ -256,7 +258,7 @@ export const AddServer = () => {
name="username"
render={({ field }) => (
<FormItem>
<FormLabel>Username</FormLabel>
<FormLabel>{t("settings.terminal.username")}</FormLabel>
<FormControl>
<Input placeholder="root" {...field} />
</FormControl>

View File

@@ -34,8 +34,10 @@ import { ShowSwarmOverviewModal } from "./show-swarm-overview-modal";
import { ShowTraefikFileSystemModal } from "./show-traefik-file-system-modal";
import { UpdateServer } from "./update-server";
import { WelcomeSuscription } from "./welcome-stripe/welcome-suscription";
import { useTranslation } from "next-i18next";
export const ShowServers = () => {
const { t } = useTranslation("settings");
const router = useRouter();
const query = router.query;
const { data, refetch } = api.server.all.useQuery();
@@ -191,7 +193,9 @@ export const ShowServers = () => {
<>
{server.sshKeyId && (
<TerminalModal serverId={server.serverId}>
<span>Enter the terminal</span>
<span>
{t("settings.common.enterTerminal")}
</span>
</TerminalModal>
)}
<SetupServer serverId={server.serverId} />

View File

@@ -31,8 +31,7 @@ import {
import { Textarea } from "@/components/ui/textarea";
import { api } from "@/utils/api";
import { zodResolver } from "@hookform/resolvers/zod";
import { PlusIcon } from "lucide-react";
import { useRouter } from "next/router";
import { useTranslation } from "next-i18next";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
@@ -60,6 +59,8 @@ interface Props {
}
export const UpdateServer = ({ serverId }: Props) => {
const { t } = useTranslation("settings");
const utils = api.useUtils();
const [isOpen, setIsOpen] = useState(false);
const { data, isLoading } = api.server.one.useQuery(
@@ -212,7 +213,7 @@ export const UpdateServer = ({ serverId }: Props) => {
name="ipAddress"
render={({ field }) => (
<FormItem>
<FormLabel>IP Address</FormLabel>
<FormLabel>{t("settings.terminal.ipAddress")}</FormLabel>
<FormControl>
<Input placeholder="192.168.1.100" {...field} />
</FormControl>
@@ -226,7 +227,7 @@ export const UpdateServer = ({ serverId }: Props) => {
name="port"
render={({ field }) => (
<FormItem>
<FormLabel>Port</FormLabel>
<FormLabel>{t("settings.terminal.port")}</FormLabel>
<FormControl>
<Input
placeholder="22"
@@ -256,7 +257,7 @@ export const UpdateServer = ({ serverId }: Props) => {
name="username"
render={({ field }) => (
<FormItem>
<FormLabel>Username</FormLabel>
<FormLabel>{t("settings.terminal.username")}</FormLabel>
<FormControl>
<Input placeholder="root" {...field} />
</FormControl>
@@ -273,7 +274,7 @@ export const UpdateServer = ({ serverId }: Props) => {
form="hook-form-update-server"
type="submit"
>
Update
{t("settings.common.save")}
</Button>
</DialogFooter>
</Form>

View File

@@ -0,0 +1,154 @@
import { Button, buttonVariants } from "@/components/ui/button";
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
import { Input } from "@/components/ui/input";
import {
FormControl,
FormLabel,
FormField,
FormMessage,
FormItem,
Form,
} from "@/components/ui/form";
import { cn } from "@/lib/utils";
import { zodResolver } from "@hookform/resolvers/zod";
import { Settings } from "lucide-react";
import React from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { useTranslation } from "next-i18next";
const Schema = z.object({
port: z.number().min(1, "Port must be higher than 0"),
username: z.string().min(1, "Username is required"),
});
type Schema = z.infer<typeof Schema>;
const DEFAULT_LOCAL_SERVER_DATA: Schema = {
port: 22,
username: "root",
};
/** Returns local server data for use with local server terminal */
export const getLocalServerData = () => {
try {
const localServerData = localStorage.getItem("localServerData");
const parsedLocalServerData = localServerData
? (JSON.parse(localServerData) as typeof DEFAULT_LOCAL_SERVER_DATA)
: DEFAULT_LOCAL_SERVER_DATA;
return parsedLocalServerData;
} catch {
return DEFAULT_LOCAL_SERVER_DATA;
}
};
interface Props {
onSave: () => void;
}
const LocalServerConfig = ({ onSave }: Props) => {
const { t } = useTranslation("settings");
const form = useForm<Schema>({
defaultValues: getLocalServerData(),
resolver: zodResolver(Schema),
});
const onSubmit = (data: Schema) => {
localStorage.setItem("localServerData", JSON.stringify(data));
form.reset(data);
onSave();
};
return (
<Accordion collapsible type="single">
<AccordionItem value="connectionSettings">
<AccordionTrigger
className={cn(
buttonVariants({ variant: "ghost" }),
"hover:no-underline px-1 mb-2 active:hover:transform-none",
)}
>
<div className="flex flex-row items-center gap-2 justify-between w-full">
<div className="flex flex-row gap-2 items-center">
<Settings className="h-4 w-4" />
<span className=" dark:hover:text-white">
{t("settings.terminal.connectionSettings")}
</span>
</div>
</div>
</AccordionTrigger>
<AccordionContent className="px-1 flex flex-col gap-2">
<Form {...form}>
<form
id="hook-form-add-server"
onSubmit={form.handleSubmit(onSubmit)}
className="w-full grid grid-cols-2 gap-4"
>
<FormField
control={form.control}
name="port"
render={({ field }) => (
<FormItem>
<FormLabel>{t("settings.terminal.port")}</FormLabel>
<FormControl>
<Input
{...field}
onChange={(e) => {
const value = e.target.value;
if (value === "") {
field.onChange(1);
} else {
const number = Number.parseInt(value, 10);
if (!Number.isNaN(number)) {
field.onChange(number);
}
}
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="username"
render={({ field }) => (
<FormItem>
<FormLabel>{t("settings.terminal.username")}</FormLabel>
<FormControl>
<Input placeholder="root" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
<Button
form="hook-form-add-server"
type="submit"
className="ml-auto"
disabled={!form.formState.isDirty}
>
{t("settings.common.save")}
</Button>
</AccordionContent>
</AccordionItem>
</Accordion>
);
};
export default LocalServerConfig;

View File

@@ -10,24 +10,38 @@ import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { api } from "@/utils/api";
import dynamic from "next/dynamic";
import type React from "react";
import { useState } from "react";
import LocalServerConfig from "./local-server-config";
const Terminal = dynamic(() => import("./terminal").then((e) => e.Terminal), {
ssr: false,
});
const getTerminalKey = () => {
return `terminal-${Date.now()}`;
};
interface Props {
children?: React.ReactNode;
serverId: string;
}
export const TerminalModal = ({ children, serverId }: Props) => {
const [terminalKey, setTerminalKey] = useState<string>(getTerminalKey());
const isLocalServer = serverId === "local";
const { data } = api.server.one.useQuery(
{
serverId,
},
{ enabled: !!serverId },
{ enabled: !!serverId && !isLocalServer },
);
const handleLocalServerConfigSave = () => {
// Rerender Terminal component to reconnect using new component key when saving local server config
setTerminalKey(getTerminalKey());
};
return (
<Dialog>
<DialogTrigger asChild>
@@ -43,12 +57,16 @@ export const TerminalModal = ({ children, serverId }: Props) => {
onEscapeKeyDown={(event) => event.preventDefault()}
>
<DialogHeader className="flex flex-col gap-1">
<DialogTitle>Terminal ({data?.name})</DialogTitle>
<DialogTitle>Terminal ({data?.name ?? serverId})</DialogTitle>
<DialogDescription>Easy way to access the server</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-4">
<Terminal id="terminal" serverId={serverId} />
{isLocalServer && (
<LocalServerConfig onSave={handleLocalServerConfigSave} />
)}
<div className="flex flex-col gap-4 h-[552px]">
<Terminal id="terminal" key={terminalKey} serverId={serverId} />
</div>
</DialogContent>
</Dialog>

View File

@@ -5,6 +5,7 @@ import { FitAddon } from "xterm-addon-fit";
import "@xterm/xterm/css/xterm.css";
import { AttachAddon } from "@xterm/addon-attach";
import { useTheme } from "next-themes";
import { getLocalServerData } from "./local-server-config";
interface Props {
id: string;
@@ -12,9 +13,16 @@ interface Props {
}
export const Terminal: React.FC<Props> = ({ id, serverId }) => {
const termRef = useRef(null);
const termRef = useRef<HTMLDivElement>(null);
const initialized = useRef<boolean>(false);
const { resolvedTheme } = useTheme();
useEffect(() => {
if (initialized.current) {
// Required in strict mode to avoid issues due to double wss connection
return;
}
initialized.current = true;
const container = document.getElementById(id);
if (container) {
container.innerHTML = "";
@@ -33,7 +41,16 @@ export const Terminal: React.FC<Props> = ({ id, serverId }) => {
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
const wsUrl = `${protocol}//${window.location.host}/terminal?serverId=${serverId}`;
const urlParams = new URLSearchParams();
urlParams.set("serverId", serverId);
if (serverId === "local") {
const { port, username } = getLocalServerData();
urlParams.set("port", port.toString());
urlParams.set("username", username);
}
const wsUrl = `${protocol}//${window.location.host}/terminal?${urlParams}`;
const ws = new WebSocket(wsUrl);
const addonAttach = new AttachAddon(ws);

View File

@@ -2,6 +2,7 @@ import { ShowServers } from "@/components/dashboard/settings/servers/show-server
import { DashboardLayout } from "@/components/layouts/dashboard-layout";
import { SettingsLayout } from "@/components/layouts/settings-layout";
import { appRouter } from "@/server/api/root";
import { getLocale, serverSideTranslations } from "@/utils/i18n";
import { validateRequest } from "@dokploy/server";
import { createServerSideHelpers } from "@trpc/react-query/server";
import type { GetServerSidePropsContext } from "next";
@@ -29,6 +30,7 @@ export async function getServerSideProps(
ctx: GetServerSidePropsContext<{ serviceId: string }>,
) {
const { req, res } = ctx;
const locale = await getLocale(req.cookies);
const { user, session } = await validateRequest(req, res);
if (!user) {
return {
@@ -64,6 +66,7 @@ export async function getServerSideProps(
return {
props: {
trpcState: helpers.dehydrate(),
...(await serverSideTranslations(locale, ["settings"])),
},
};
}

View File

@@ -1,5 +1,6 @@
{
"settings.common.save": "Save",
"settings.common.enterTerminal": "Enter the terminal",
"settings.server.domain.title": "Server Domain",
"settings.server.domain.description": "Add a domain to your server application.",
"settings.server.domain.form.domain": "Domain",
@@ -48,5 +49,10 @@
"settings.appearance.themes.dark": "Dark",
"settings.appearance.themes.system": "System",
"settings.appearance.language": "Language",
"settings.appearance.languageDescription": "Select a language for your dashboard"
"settings.appearance.languageDescription": "Select a language for your dashboard",
"settings.terminal.connectionSettings": "Connection settings",
"settings.terminal.ipAddress": "IP Address",
"settings.terminal.port": "Port",
"settings.terminal.username": "Username"
}

View File

@@ -1,5 +1,6 @@
{
"settings.common.save": "Zapisz",
"settings.common.enterTerminal": "Otwórz terminal",
"settings.server.domain.title": "Domena",
"settings.server.domain.description": "Dodaj domenę do aplikacji",
"settings.server.domain.form.domain": "Domena",
@@ -40,5 +41,10 @@
"settings.appearance.themes.dark": "Ciemny",
"settings.appearance.themes.system": "System",
"settings.appearance.language": "Język",
"settings.appearance.languageDescription": "Wybierz język swojego pulpitu"
"settings.appearance.languageDescription": "Wybierz język swojego pulpitu",
"settings.terminal.connectionSettings": "Ustawienia połączenia",
"settings.terminal.ipAddress": "Adres IP",
"settings.terminal.port": "Port",
"settings.terminal.username": "Nazwa użytkownika"
}

View File

@@ -1,8 +1,9 @@
import type http from "node:http";
import { findServerById, validateWebSocketRequest } from "@dokploy/server";
import { publicIpv4, publicIpv6 } from "public-ip";
import { Client } from "ssh2";
import { Client, type ConnectConfig } from "ssh2";
import { WebSocketServer } from "ws";
import { setupLocalServerSSHKey } from "./utils";
export const getPublicIpWithFallback = async () => {
// @ts-ignore
@@ -55,21 +56,67 @@ export const setupTerminalWebSocketServer = (
return;
}
const server = await findServerById(serverId);
let connectionDetails: ConnectConfig = {};
if (!server) {
ws.close();
return;
const isLocalServer = serverId === "local";
if (isLocalServer) {
const port = Number(url.searchParams.get("port"));
const username = url.searchParams.get("username");
if (!port || !username) {
ws.close();
return;
}
ws.send("Setting up private SSH key...\n");
const privateKey = await setupLocalServerSSHKey();
if (!privateKey) {
ws.close();
return;
}
connectionDetails = {
host: "localhost",
port,
username,
privateKey,
};
} else {
ws.send("Getting server data...\n");
const server = await findServerById(serverId);
if (!server) {
ws.close();
return;
}
const { ipAddress: host, port, username, sshKey, sshKeyId } = server;
if (!sshKeyId) {
throw new Error("No SSH key available for this server");
}
connectionDetails = {
host,
port,
username,
privateKey: sshKey?.privateKey,
};
}
if (!server.sshKeyId)
throw new Error("No SSH key available for this server");
const conn = new Client();
let stdout = "";
let stderr = "";
ws.send("Connecting...\n");
conn
.once("ready", () => {
// Clear terminal content once connected
ws.send("\x1bc");
conn.shell({}, (err, stream) => {
if (err) throw err;
@@ -112,18 +159,13 @@ export const setupTerminalWebSocketServer = (
.on("error", (err) => {
if (err.level === "client-authentication") {
ws.send(
`Authentication failed: Invalid SSH private key. ❌ Error: ${err.message} ${err.level}`,
`Authentication failed: Unauthorized ${isLocalServer ? "" : "private SSH key or "}username.\n❌ Error: ${err.message} ${err.level}`,
);
} else {
ws.send(`SSH connection error: ${err.message}`);
}
conn.end();
})
.connect({
host: server.ipAddress,
port: server.port,
username: server.username,
privateKey: server.sshKey?.privateKey,
});
.connect(connectionDetails);
});
};

View File

@@ -1,4 +1,17 @@
import { execAsync } from "@dokploy/server/utils/process/execAsync";
import os from "node:os";
import path from "node:path";
import fs from "node:fs";
const HOME_PATH = process.env.HOME || process.env.USERPROFILE || "/";
const LOCAL_SSH_KEY_PATH = path.join(
HOME_PATH,
".ssh",
"auto_generated-dokploy-local",
);
const AUTHORIZED_KEYS_PATH = path.join(HOME_PATH, ".ssh", "authorized_keys");
export const getShell = () => {
switch (os.platform()) {
@@ -10,3 +23,40 @@ export const getShell = () => {
return "bash";
}
};
/** Returns private SSH key for dokploy local server terminal. Uses already created SSH key or generates a new SSH key, also automatically appends the public key to `authorized_keys`, creating the file if needed. */
export const setupLocalServerSSHKey = async () => {
try {
if (!fs.existsSync(LOCAL_SSH_KEY_PATH)) {
// Generate new SSH key if it hasn't been created yet
await execAsync(
`ssh-keygen -t rsa -b 4096 -f ${LOCAL_SSH_KEY_PATH} -N ""`,
);
}
const privateKey = fs.readFileSync(LOCAL_SSH_KEY_PATH, "utf8");
const publicKey = fs.readFileSync(`${LOCAL_SSH_KEY_PATH}.pub`, "utf8");
const authKeyContent = `${publicKey}\n`;
if (!fs.existsSync(AUTHORIZED_KEYS_PATH)) {
// Create authorized_keys if it doesn't exist yet
fs.writeFileSync(AUTHORIZED_KEYS_PATH, authKeyContent, { mode: 0o600 });
return privateKey;
}
const existingAuthKeys = fs.readFileSync(AUTHORIZED_KEYS_PATH, "utf8");
if (existingAuthKeys.includes(publicKey)) {
return privateKey;
}
// Append the public key to authorized_keys
fs.appendFileSync(AUTHORIZED_KEYS_PATH, authKeyContent, {
mode: 0o600,
});
return privateKey;
} catch (error) {
console.error("Error getting private SSH key for local terminal:", error);
return "";
}
};