mirror of
https://github.com/andwati/dokploy.git
synced 2026-10-18 03:02:56 +00:00
Fixes #5092 — typing in the database/docker terminal overwrote text instead of continuing on new lines. The xterm.js client never told the backend PTY its actual size (node-pty/ssh2 always defaulted to 80x24 and were never resized), so whenever the rendered terminal width differed from that, the remote shell's cursor math diverged from what the client displayed. - docker-container-terminal.ts / terminal.ts: pass the client's initial cols/rows into node-pty spawn and ssh2 exec/shell, and resize the PTY on a {type:"resize"} control message sent over the same ws channel. - docker-terminal.tsx / settings/web-server/terminal.tsx: send cols/rows on connect and on every term.onResize, and watch the container with a ResizeObserver to refit on dialog/window resize. Also fixes two related terminal/logs bugs surfaced while testing this: - docker-terminal.tsx no longer opens a connection with the "select-a-container" placeholder ID before a real container is selected, and defers terminal creation a frame so React StrictMode's dev-only phantom mount doesn't hit a known xterm.js dispose race (xtermjs/xterm.js#5011, "Cannot read properties of undefined (reading 'dimensions')"). - docker-logs-id.tsx (shared by application/compose/compose-stack logs) had the same placeholder-ID issue, surfacing Docker's raw "No such container: select-a-container" daemon error instead of a proper empty state.
218 lines
5.7 KiB
TypeScript
218 lines
5.7 KiB
TypeScript
import type http from "node:http";
|
|
import { findServerById, IS_CLOUD, validateRequest } from "@dokploy/server";
|
|
import { spawn } from "node-pty";
|
|
import { Client } from "ssh2";
|
|
import { WebSocketServer } from "ws";
|
|
import { canAccessDockerOverWss } from "./authorize";
|
|
import {
|
|
isValidContainerId,
|
|
isValidShell,
|
|
parseResizeMessage,
|
|
parseTerminalSize,
|
|
} from "./utils";
|
|
|
|
export const setupDockerContainerTerminalWebSocketServer = (
|
|
server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>,
|
|
) => {
|
|
const wssTerm = new WebSocketServer({
|
|
noServer: true,
|
|
path: "/docker-container-terminal",
|
|
});
|
|
|
|
server.on("upgrade", (req, socket, head) => {
|
|
const { pathname } = new URL(req.url || "", `http://${req.headers.host}`);
|
|
|
|
if (pathname === "/_next/webpack-hmr") {
|
|
return;
|
|
}
|
|
if (pathname === "/docker-container-terminal") {
|
|
wssTerm.handleUpgrade(req, socket, head, function done(ws) {
|
|
wssTerm.emit("connection", ws, req);
|
|
});
|
|
}
|
|
});
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
wssTerm.on("connection", async (ws, req) => {
|
|
const url = new URL(req.url || "", `http://${req.headers.host}`);
|
|
const containerId = url.searchParams.get("containerId");
|
|
const activeWay = url.searchParams.get("activeWay");
|
|
const serverId = url.searchParams.get("serverId");
|
|
const serviceId = url.searchParams.get("serviceId");
|
|
const { cols, rows } = parseTerminalSize(
|
|
url.searchParams.get("cols"),
|
|
url.searchParams.get("rows"),
|
|
);
|
|
const { user, session } = await validateRequest(req);
|
|
|
|
if (!containerId) {
|
|
ws.close(4000, "containerId not provided");
|
|
return;
|
|
}
|
|
|
|
// Security: Validate containerId to prevent command injection
|
|
if (!isValidContainerId(containerId)) {
|
|
ws.close(4000, "Invalid container ID format");
|
|
return;
|
|
}
|
|
|
|
// Security: Validate shell to prevent command injection
|
|
if (activeWay && !isValidShell(activeWay)) {
|
|
ws.close(4000, "Invalid shell specified");
|
|
return;
|
|
}
|
|
|
|
// Default to 'sh' if no shell specified
|
|
const shell = activeWay || "sh";
|
|
|
|
if (!user || !session) {
|
|
ws.close();
|
|
return;
|
|
}
|
|
|
|
if (!(await canAccessDockerOverWss(user, session, serverId, serviceId))) {
|
|
ws.close(4003, "Not authorized");
|
|
return;
|
|
}
|
|
try {
|
|
if (serverId) {
|
|
const server = await findServerById(serverId);
|
|
|
|
if (server.organizationId !== session.activeOrganizationId) {
|
|
ws.close();
|
|
return;
|
|
}
|
|
|
|
if (!server.sshKeyId)
|
|
throw new Error("No SSH key available for this server");
|
|
|
|
const conn = new Client();
|
|
let _stdout = "";
|
|
let _stderr = "";
|
|
conn
|
|
.once("ready", () => {
|
|
// Use array-style arguments to prevent shell injection
|
|
const dockerCommand = [
|
|
"docker",
|
|
"exec",
|
|
"-it",
|
|
"-w",
|
|
"/",
|
|
containerId,
|
|
shell,
|
|
].join(" ");
|
|
conn.exec(dockerCommand, { pty: { cols, rows } }, (err, stream) => {
|
|
if (err) {
|
|
console.error("SSH exec error:", err);
|
|
ws.close();
|
|
conn.end();
|
|
return;
|
|
}
|
|
|
|
stream
|
|
.on("close", (code: number, _signal: string) => {
|
|
ws.send(`\nContainer closed with code: ${code}\n`);
|
|
conn.end();
|
|
})
|
|
.on("data", (data: string) => {
|
|
_stdout += data.toString();
|
|
ws.send(data.toString());
|
|
})
|
|
.stderr.on("data", (data) => {
|
|
_stderr += data.toString();
|
|
ws.send(data.toString());
|
|
console.error("Error: ", data.toString());
|
|
});
|
|
|
|
ws.on("message", (message) => {
|
|
try {
|
|
let command: string | Buffer[] | Buffer | ArrayBuffer;
|
|
if (Buffer.isBuffer(message)) {
|
|
command = message.toString("utf8");
|
|
} else {
|
|
command = message;
|
|
}
|
|
const text = command.toString();
|
|
const resize = parseResizeMessage(text);
|
|
if (resize) {
|
|
stream.setWindow(resize.rows, resize.cols, 0, 0);
|
|
return;
|
|
}
|
|
stream.write(text);
|
|
} catch (error) {
|
|
// @ts-ignore
|
|
const errorMessage = error?.message as unknown as string;
|
|
ws.send(errorMessage);
|
|
}
|
|
});
|
|
|
|
ws.on("close", () => {
|
|
stream.end();
|
|
// Ensure SSH connection is closed when WebSocket closes
|
|
conn.end();
|
|
});
|
|
});
|
|
})
|
|
.on("error", (err) => {
|
|
console.error("SSH connection error:", err);
|
|
if (ws.readyState === ws.OPEN) {
|
|
ws.send(`SSH error: ${err.message}`);
|
|
ws.close();
|
|
}
|
|
conn.end();
|
|
})
|
|
.connect({
|
|
host: server.ipAddress,
|
|
port: server.port,
|
|
username: server.username,
|
|
privateKey: server.sshKey?.privateKey,
|
|
});
|
|
} else {
|
|
if (IS_CLOUD) {
|
|
ws.send("This feature is not available in the cloud version.");
|
|
ws.close();
|
|
return;
|
|
}
|
|
const ptyProcess = spawn(
|
|
"docker",
|
|
["exec", "-it", "-w", "/", containerId, shell],
|
|
{ cols, rows },
|
|
);
|
|
|
|
ptyProcess.onData((data) => {
|
|
ws.send(data);
|
|
});
|
|
ws.on("close", () => {
|
|
ptyProcess.kill();
|
|
});
|
|
ws.on("message", (message) => {
|
|
try {
|
|
let command: string | Buffer[] | Buffer | ArrayBuffer;
|
|
if (Buffer.isBuffer(message)) {
|
|
command = message.toString("utf8");
|
|
} else {
|
|
command = message;
|
|
}
|
|
const text = command.toString();
|
|
const resize = parseResizeMessage(text);
|
|
if (resize) {
|
|
ptyProcess.resize(resize.cols, resize.rows);
|
|
return;
|
|
}
|
|
ptyProcess.write(text);
|
|
} catch (error) {
|
|
// @ts-ignore
|
|
const errorMessage = error?.message as unknown as string;
|
|
ws.send(errorMessage);
|
|
}
|
|
});
|
|
}
|
|
} catch (error) {
|
|
// @ts-ignore
|
|
const errorMessage = error?.message as unknown as string;
|
|
|
|
ws.send(errorMessage);
|
|
}
|
|
});
|
|
};
|