Files
Termix/src/backend/ssh/docker-container-routes.ts
T
52f4e51ae0 v2.3.2 (#874)
* fix: patch critical security vulnerabilities (GHSA-5fqh, GHSA-ccm8, GHSA-wqfw, GHSA-xmjh)

- Remove passwordHash from /users/list API response
- Require both password and TOTP code for MFA-critical operations
- Restrict tunnel kill commands to tunnelMarker-only matching
- Add session ownership middleware for file manager endpoints

* fix: allow navigating away from split-view to non-pane tabs

Show the normal view container on top of the split view when the active
tab is not assigned to any pane, so users can switch to dashboard or
other tabs while split mode is active.

Closes #739

* fix: add inline quick-action buttons on host name row

Show Terminal, Files, RDP, and VNC shortcut icons on the host name row
on hover, so users can launch connections with a single click without
expanding the full action tray.

Closes #736

* fix: restore SSH keepalive interval to 30s to prevent random disconnects

Revert keepalive defaults from 60s/5 to 30s/3 across terminal, tunnel,
and server-stats SSH connections. The 60s interval introduced in 2.3.0
causes firewalls and NAT devices to drop idle connections before the
next keepalive probe.

Closes #733

* fix: apply guacamole-lite protocol patch in Docker builds

The Dockerfile uses --ignore-scripts which skips the postinstall hook
that patches guacamole-lite for guacd 1.6.0 protocol VERSION_1_5_0.
Without this patch, the timezone handshake instruction is not sent for
protocol versions above 1.1.0, causing VNC connections to fail
immediately on connect.

Closes #734

* fix: show correct icons for network interface types

Detect interface type from name pattern and show appropriate icons:
WiFi for wlan/wl*, Ethernet (Cable) for eth/en*, Container for
docker/bridge/virtual, generic Network for others.

Closes #720

* fix: resolve sudo password for shared host users

The password endpoint required hosts.userId to match the requesting
user, which fails for shared hosts. Now falls back to decrypting with
the owner's key when the requesting user doesn't own the host.

Closes #717

* fix: use jump hosts for online status check and metrics collection

Status polling now pings the first jump host instead of the unreachable
target when jump hosts are configured. The /metrics/start endpoint now
tunnels through the jump host chain to reach the target host.

Closes #716

* fix: broaden sudo prompt detection for newer distros

Add patterns for 'password for <user>:' and bare 'Password:' prompts
in addition to the existing [sudo] and sudo: patterns. Covers Ubuntu
26.04 and other distros that use different sudo prompt formats.

Closes #718

* fix: recalculate terminal layout after web fonts load

xterm.js measures character widths at open() time. If custom fonts
haven't loaded yet, measurements use the fallback font and spacing
becomes incorrect. Now refresh and re-fit the terminal once
document.fonts.ready resolves.

Closes #710

* fix: improve terminal cwd detection and initial directory command

Remove '&& pwd' from initial directory command — the shell prompt
shows the new directory naturally. Fixes PowerShell 5.1 which doesn't
support '&&' as a statement separator.

Prepend Ctrl+U to get_cwd command to clear any pending input before
injecting the cwd probe, reducing interference with foreground programs.

Closes #713, #714

* fix: decode base64 file content as UTF-8 in file manager

Replace bare atob() with TextDecoder('utf-8') for base64 content
decoding. atob() only handles Latin-1, so multi-byte UTF-8 characters
like 'é' were decoded as 'é'.

Closes #719

* fix: normalize lazy import default exports for iOS compatibility

Wrap all lazy() imports with explicit .then(m => ({ default: m.default }))
to ensure consistent module resolution across platforms. iOS Safari/WebView
may handle bare lazy(() => import(...)) differently, returning the module
object instead of extracting the default export.

Closes #721

* fix: prevent RDP display from snapping back after container resize

Remove immediate rescaleDisplay() from ResizeObserver callback. The
display.onresize event already triggers rescaling when the RDP server
responds with the new resolution. Calling rescaleDisplay before the
server responds uses stale display dimensions, causing the bottom of
the screen to be truncated.

Closes #725

* fix: add portal Desktop DBus permission for Flatpak URL opening

Flatpak sandbox blocks window.open() without the portal permission,
causing terminal link clicks to open about:blank. Add talk-name for
org.freedesktop.portal.Desktop to enable xdg-desktop-portal URL
handling.

Closes #704

* chore: remove unused code and fix PR checks (#851)

* chore: remove unused frontend code

* chore: prune unused theme exports

* ci: fix pr check failures

* chore: reduce lint warnings

* feat(oidc): expose admin_group via OIDC_ADMIN_GROUP env var (#828)

The admin-group OIDC sync added in 2.3.0 (#782) reads `config.admin_group`
to sync the user's admin flag from OIDC group membership on each login.
That field is only populated when the OIDC config is stored in the
in-app DB — `getOIDCConfigFromEnv()` does not expose it, so deployments
using the env-var config path (declarative IaC: Helm/Compose/Puppet)
cannot enable the feature without abandoning env vars and pasting the
client_secret into the admin UI.

Add `admin_group: process.env.OIDC_ADMIN_GROUP || ""` to the env-config
return type and object. Backward compatible: when unset, the existing
`if (config.admin_group)` guard at users.ts:1336 keeps the sync block
skipped, matching today's behavior.

* chore: reduce explicit-any warnings

* chore: reduce more explicit-any warnings

* chore: reduce lint warnings

* chore: silence intentional hook dependency warnings

* chore: clean dependency tooling

* chore: narrow frontend tsconfig scope

* chore: reduce type assertion debt

* refactor: split host manager components

* refactor: split host editor sections

* refactor: split api client modules

* refactor: split more api clients

* refactor: split user settings api clients

* refactor: split tab and history api clients

* refactor: split tunnel api clients

* refactor: split server stats api client

* refactor: split file manager data api

* refactor: split ssh file operations api

* refactor: split host editor general tab

* refactor: split host editor guacamole tabs

* refactor: split ssh host management api

* refactor: split admin general settings sections

* refactor: split admin database section

* refactor: split admin management sections

* refactor: split admin keys and dialogs

* refactor: split system status api clients

* refactor: split user route helpers

* refactor: split host route helpers

* refactor: split file manager ssh helpers

* refactor: split file manager session helpers

* refactor: split file manager listing routes

* refactor: split host opkssh routes

* refactor: split file manager content routes

* refactor: split user api key routes

* refactor: split host folder routes

* refactor: split user settings routes

* refactor: split user totp routes

* refactor: split host file manager bookmark routes

* refactor: split file manager operation routes

* refactor: split server stats settings routes

* refactor: split user session routes

* refactor: split host command history routes

* refactor: split server stats viewer routes

* refactor: split docker container routes

* refactor: split user oidc account routes

* refactor: split host autostart routes

* refactor: split host internal routes

* refactor: split host network routes

* refactor: split user password reset routes

* refactor: split user admin routes

* refactor: split user data access routes

* refactor: split credential key routes

* refactor: split credential deploy routes

* refactor: split host bulk routes

* refactor: split server stats connection helpers

* refactor: split tunnel helpers

* refactor: split file manager action routes

* refactor: split terminal auth helpers

* refactor: split terminal jump host helpers

* refactor: split tunnel relay helpers

* refactor: split tunnel socks relay helpers

* refactor: split tunnel c2s relay handlers

* refactor: split server stats session helpers

* refactor: split terminal presentation helpers

* refactor: split file manager presentation helpers

* refactor: split file manager toolbar

* fix(guacamole-lite): send name instruction for protocol >= 1.3.0

The Guacamole protocol added the `name` handshake instruction in 1.3.0
(an optional human-readable identifier for the joining user). guacd 1.6.0
began requiring it during the VNC handshake even when negotiating older
protocol versions, causing connections to silently drop right after the
"User joined" log line with no client-visible error.

This patch extends scripts/patch-guacamole-lite.cjs with a third
idempotent string-replacement that injects the `name` instruction send
when guacamole-lite has negotiated protocol VERSION_1_3_0 or VERSION_1_5_0.

Verified end-to-end: guacd debug logs now show `Processing instruction:
name` and `Client is using protocol version "VERSION_1_5_0"` (previously
stuck at VERSION_1_1_0). VNC session connects successfully against
guacd 1.5.5 / macOS Tahoe target.

Related: Termix-SSH/Support#567, #734

* fix: resolve recent support bugs

* fix(admin): wire up OIDC-to-password link dialog submit + visibility

The admin user-management UI already shipped a link icon and a "Link
Account" dialog, but two things blocked the flow:

1. The submit button had no onClick handler and the username input was
   uncontrolled (no value/onChange). Clicking "Link Accounts" was a
   no-op — no network request, no console error, no toast.
2. The link icon's visibility condition was `user.isOidc &&
   !user.passwordHash`, which hid the button on OIDC users that had
   been auto-provisioned with a passwordHash. Termix's OIDC provisioning
   sets a passwordHash by default, so the button was hidden on virtually
   every OIDC-provisioned user.

This change:
- Adds `linkOIDCToPasswordAccount` to the imports from `@/main-axios`.
- Adds two pieces of dialog state: `linkAccountTargetUsername` and
  `linkAccountSubmitting`.
- Makes the dialog's Input field a controlled component.
- Wires the submit Button's onClick to call `linkOIDCToPasswordAccount`,
  emit success/error toasts, refresh the local user list, and close
  the dialog.
- Loosens the visibility condition to `user.isOidc` (the backend
  handler already enforces all integrity checks).
- Adds `linkAccountSuccess`, `linkAccountFailed`, and
  `linkAccountInProgress` translation keys to `en.json`.

Verified locally: full Docker build via docker/Dockerfile passes;
`tsc --noEmit` is clean; `prettier --check .` is clean; ESLint produces
the same warning count as upstream (16 pre-existing `any`-type warnings,
0 errors).

* fix: support native oidc callbacks (#856)

* docs: add cloudflare tunnel guidance (#857)

* fix: sync appearance preferences (#858)

* fix: pass through terminal tab completion (#859)

* fix: resolve terminal jump hosts server-side (#860)

* fix(electron): auto-allow SSL certificates for private network hosts (#861)

Add private network IP detection (RFC 1918, link-local, loopback, IPv6
ULA) to the Electron certificate-error handler so that connections to
local/private servers like 192.168.x.x bypass SSL validation
automatically. Also add an explicit "Allow invalid certificate" toggle
in the server config UI for public HTTPS servers with self-signed certs.

* fix: restore host password copy actions (#862)

* feat: support single-host direct tunnels (ssh -L style) (#863)

Add direct tunnel mode that uses a single SSH host for port forwarding,
matching the behavior of ssh -L / ssh -R / ssh -D without requiring a
second endpoint host in the Termix database. The Termix server creates a
local TCP listener and forwards through the SSH channel directly.

* Merge commit from fork

* Merge commit from fork

* Merge commit from fork

* Merge commit from fork

* Merge commit from fork

* Merge commit from fork

* Merge commit from fork

* Merge commit from fork

* Merge commit from fork

* fix: backend build errors (Type)

* fix: mobile auth failing to login with webview

* fix: mobile app geting incorrectly sent auth token

* feat: commit existing frontend/backend e2e/unit tests (skipped tests containing private info like OIDC and real server testing)

* feat: host-to-host file transfer via server relay

* feat: removed host management from command palette, fixed command palette opening wrong protocol, export/import failing for ssh key hosts, docker ssh2 native crypto not compiled, persisted terminal tabs attempt SSh on RDP hosts after migration, improved layout for click to expand hosts, show ip/username without having to hover over hosts

* fix: credentials not indexing into host manager until refresh

* feat: update credentials lists to match hosts list UI/UX

* feat: add rename folder UI

* feat: improve transfer to host UI/UX

* chore: increment ver

* feat: improve transfer to host UI

* feat: implement initial auto release system

---------

Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com>
Co-authored-by: nicodarge <43711429+nicodarge@users.noreply.github.com>
Co-authored-by: Raman Gupta <7243222+raman325@users.noreply.github.com>
Co-authored-by: luc <luc_cook@hotmail.co.uk>
2026-06-04 14:16:53 -05:00

1094 lines
29 KiB
TypeScript

import type express from "express";
import { logger } from "../utils/logger.js";
const sshLogger = logger;
type DockerSession = {
isConnected: boolean;
lastActive: number;
activeOperations: number;
hostId?: number;
};
type PendingDockerTotpSession = unknown;
type ExecuteDockerCommand = (
session: DockerSession,
command: string,
sessionId: string,
userId: string,
hostId?: number,
) => Promise<string>;
type DockerContainerRoutesDeps = {
sshSessions: Record<string, DockerSession>;
pendingTOTPSessions: Record<string, PendingDockerTotpSession>;
getRequestUserId: (req: express.Request) => string | undefined;
executeDockerCommand: ExecuteDockerCommand;
dockerTimestampPattern: RegExp;
};
export function registerDockerContainerRoutes(
app: express.Express,
{
sshSessions,
pendingTOTPSessions,
getRequestUserId,
executeDockerCommand,
dockerTimestampPattern: DOCKER_TIMESTAMP_RE,
}: DockerContainerRoutesDeps,
): void {
/**
* @openapi
* /docker/containers/{sessionId}:
* get:
* summary: List all containers
* description: Lists all Docker containers on the host.
* tags:
* - Docker
* parameters:
* - in: path
* name: sessionId
* required: true
* schema:
* type: string
* - in: query
* name: all
* schema:
* type: boolean
* responses:
* 200:
* description: A list of containers.
* 400:
* description: SSH session not found or not connected.
* 500:
* description: Failed to list containers.
*/
app.get("/docker/containers/:sessionId", async (req, res) => {
const { sessionId } = req.params;
const all = req.query.all !== "false";
const userId = getRequestUserId(req);
if (!userId) {
return res.status(401).json({ error: "Authentication required" });
}
if (pendingTOTPSessions[sessionId]) {
return res.status(400).json({
error: "Connection pending authentication",
code: "AUTH_PENDING",
});
}
const session = sshSessions[sessionId];
if (!session || !session.isConnected) {
return res.status(400).json({
error: "SSH session not found or not connected",
});
}
session.lastActive = Date.now();
session.activeOperations++;
try {
const allFlag = all ? "-a " : "";
const command = `docker ps ${allFlag}--format '{"id":"{{.ID}}","name":"{{.Names}}","image":"{{.Image}}","status":"{{.Status}}","state":"{{.State}}","ports":"{{.Ports}}","created":"{{.CreatedAt}}"}'`;
const output = await executeDockerCommand(
session,
command,
sessionId,
userId,
session.hostId,
);
const containers = output
.split("\n")
.filter((line) => line.trim())
.map((line) => {
try {
return JSON.parse(line);
} catch {
sshLogger.warn("Failed to parse container line", {
operation: "parse_container",
line,
});
return null;
}
})
.filter((c) => c !== null);
session.activeOperations--;
res.json(containers);
} catch (error) {
session.activeOperations--;
sshLogger.error("Failed to list Docker containers", error, {
operation: "list_containers",
sessionId,
userId,
});
res.status(500).json({
error:
error instanceof Error ? error.message : "Failed to list containers",
});
}
});
/**
* @openapi
* /docker/containers/{sessionId}/{containerId}:
* get:
* summary: Get container details
* description: Retrieves detailed information about a specific container.
* tags:
* - Docker
* parameters:
* - in: path
* name: sessionId
* required: true
* schema:
* type: string
* - in: path
* name: containerId
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Container details.
* 400:
* description: SSH session not found or not connected.
* 404:
* description: Container not found.
* 500:
* description: Failed to get container details.
*/
app.get("/docker/containers/:sessionId/:containerId", async (req, res) => {
const { sessionId, containerId } = req.params;
const userId = getRequestUserId(req);
if (!userId) {
return res.status(401).json({ error: "Authentication required" });
}
const session = sshSessions[sessionId];
if (!session || !session.isConnected) {
return res.status(400).json({
error: "SSH session not found or not connected",
});
}
session.lastActive = Date.now();
session.activeOperations++;
try {
const command = `docker inspect ${containerId}`;
const output = await executeDockerCommand(
session,
command,
sessionId,
userId,
session.hostId,
);
const details = JSON.parse(output);
session.activeOperations--;
if (details && details.length > 0) {
res.json(details[0]);
} else {
res.status(404).json({
error: "Container not found",
code: "CONTAINER_NOT_FOUND",
});
}
} catch (error) {
session.activeOperations--;
const errorMsg = error instanceof Error ? error.message : "";
if (errorMsg.includes("No such container")) {
return res.status(404).json({
error: "Container not found",
code: "CONTAINER_NOT_FOUND",
});
}
sshLogger.error("Failed to get container details", error, {
operation: "get_container_details",
sessionId,
containerId,
userId,
});
res.status(500).json({
error: errorMsg || "Failed to get container details",
});
}
});
/**
* @openapi
* /docker/containers/{sessionId}/{containerId}/start:
* post:
* summary: Start container
* description: Starts a specific container.
* tags:
* - Docker
* parameters:
* - in: path
* name: sessionId
* required: true
* schema:
* type: string
* - in: path
* name: containerId
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Container started successfully.
* 400:
* description: SSH session not found or not connected.
* 404:
* description: Container not found.
* 500:
* description: Failed to start container.
*/
app.post(
"/docker/containers/:sessionId/:containerId/start",
async (req, res) => {
const { sessionId, containerId } = req.params;
const userId = getRequestUserId(req);
if (!userId) {
return res.status(401).json({ error: "Authentication required" });
}
const session = sshSessions[sessionId];
if (!session || !session.isConnected) {
return res.status(400).json({
error: "SSH session not found or not connected",
});
}
session.lastActive = Date.now();
session.activeOperations++;
try {
sshLogger.info("Docker container operation", {
operation: "docker_container_op",
sessionId,
userId,
hostId: session.hostId,
containerId,
action: "start",
});
await executeDockerCommand(
session,
`docker start ${containerId}`,
sessionId,
userId,
session.hostId,
);
session.activeOperations--;
res.json({
success: true,
message: "Container started successfully",
});
} catch (error) {
session.activeOperations--;
const errorMsg = error instanceof Error ? error.message : "";
if (errorMsg.includes("No such container")) {
return res.status(404).json({
success: false,
error: "Container not found",
code: "CONTAINER_NOT_FOUND",
});
}
sshLogger.error("Failed to start container", error, {
operation: "start_container",
sessionId,
containerId,
userId,
});
res.status(500).json({
success: false,
error: errorMsg || "Failed to start container",
});
}
},
);
/**
* @openapi
* /docker/containers/{sessionId}/{containerId}/stop:
* post:
* summary: Stop container
* description: Stops a specific container.
* tags:
* - Docker
* parameters:
* - in: path
* name: sessionId
* required: true
* schema:
* type: string
* - in: path
* name: containerId
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Container stopped successfully.
* 400:
* description: SSH session not found or not connected.
* 404:
* description: Container not found.
* 500:
* description: Failed to stop container.
*/
app.post(
"/docker/containers/:sessionId/:containerId/stop",
async (req, res) => {
const { sessionId, containerId } = req.params;
const userId = getRequestUserId(req);
if (!userId) {
return res.status(401).json({ error: "Authentication required" });
}
const session = sshSessions[sessionId];
if (!session || !session.isConnected) {
return res.status(400).json({
error: "SSH session not found or not connected",
});
}
session.lastActive = Date.now();
session.activeOperations++;
try {
sshLogger.info("Docker container operation", {
operation: "docker_container_op",
sessionId,
userId,
hostId: session.hostId,
containerId,
action: "stop",
});
await executeDockerCommand(
session,
`docker stop ${containerId}`,
sessionId,
userId,
session.hostId,
);
session.activeOperations--;
res.json({
success: true,
message: "Container stopped successfully",
});
} catch (error) {
session.activeOperations--;
const errorMsg = error instanceof Error ? error.message : "";
if (errorMsg.includes("No such container")) {
return res.status(404).json({
success: false,
error: "Container not found",
code: "CONTAINER_NOT_FOUND",
});
}
sshLogger.error("Failed to stop container", error, {
operation: "stop_container",
sessionId,
containerId,
userId,
});
res.status(500).json({
success: false,
error: errorMsg || "Failed to stop container",
});
}
},
);
/**
* @openapi
* /docker/containers/{sessionId}/{containerId}/restart:
* post:
* summary: Restart container
* description: Restarts a specific container.
* tags:
* - Docker
* parameters:
* - in: path
* name: sessionId
* required: true
* schema:
* type: string
* - in: path
* name: containerId
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Container restarted successfully.
* 400:
* description: SSH session not found or not connected.
* 404:
* description: Container not found.
* 500:
* description: Failed to restart container.
*/
app.post(
"/docker/containers/:sessionId/:containerId/restart",
async (req, res) => {
const { sessionId, containerId } = req.params;
const userId = getRequestUserId(req);
if (!userId) {
return res.status(401).json({ error: "Authentication required" });
}
const session = sshSessions[sessionId];
if (!session || !session.isConnected) {
return res.status(400).json({
error: "SSH session not found or not connected",
});
}
session.lastActive = Date.now();
session.activeOperations++;
try {
sshLogger.info("Docker container operation", {
operation: "docker_container_op",
sessionId,
userId,
hostId: session.hostId,
containerId,
action: "restart",
});
await executeDockerCommand(
session,
`docker restart ${containerId}`,
sessionId,
userId,
session.hostId,
);
session.activeOperations--;
res.json({
success: true,
message: "Container restarted successfully",
});
} catch (error) {
session.activeOperations--;
const errorMsg = error instanceof Error ? error.message : "";
if (errorMsg.includes("No such container")) {
return res.status(404).json({
success: false,
error: "Container not found",
code: "CONTAINER_NOT_FOUND",
});
}
sshLogger.error("Failed to restart container", error, {
operation: "restart_container",
sessionId,
containerId,
userId,
});
res.status(500).json({
success: false,
error: errorMsg || "Failed to restart container",
});
}
},
);
/**
* @openapi
* /docker/containers/{sessionId}/{containerId}/pause:
* post:
* summary: Pause container
* description: Pauses a specific container.
* tags:
* - Docker
* parameters:
* - in: path
* name: sessionId
* required: true
* schema:
* type: string
* - in: path
* name: containerId
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Container paused successfully.
* 400:
* description: SSH session not found or not connected.
* 404:
* description: Container not found.
* 500:
* description: Failed to pause container.
*/
app.post(
"/docker/containers/:sessionId/:containerId/pause",
async (req, res) => {
const { sessionId, containerId } = req.params;
const userId = getRequestUserId(req);
if (!userId) {
return res.status(401).json({ error: "Authentication required" });
}
const session = sshSessions[sessionId];
if (!session || !session.isConnected) {
return res.status(400).json({
error: "SSH session not found or not connected",
});
}
session.lastActive = Date.now();
session.activeOperations++;
try {
sshLogger.info("Docker container operation", {
operation: "docker_container_op",
sessionId,
userId,
hostId: session.hostId,
containerId,
action: "pause",
});
await executeDockerCommand(
session,
`docker pause ${containerId}`,
sessionId,
userId,
session.hostId,
);
session.activeOperations--;
res.json({
success: true,
message: "Container paused successfully",
});
} catch (error) {
session.activeOperations--;
const errorMsg = error instanceof Error ? error.message : "";
if (errorMsg.includes("No such container")) {
return res.status(404).json({
success: false,
error: "Container not found",
code: "CONTAINER_NOT_FOUND",
});
}
sshLogger.error("Failed to pause container", error, {
operation: "pause_container",
sessionId,
containerId,
userId,
});
res.status(500).json({
success: false,
error: errorMsg || "Failed to pause container",
});
}
},
);
/**
* @openapi
* /docker/containers/{sessionId}/{containerId}/unpause:
* post:
* summary: Unpause container
* description: Unpauses a specific container.
* tags:
* - Docker
* parameters:
* - in: path
* name: sessionId
* required: true
* schema:
* type: string
* - in: path
* name: containerId
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Container unpaused successfully.
* 400:
* description: SSH session not found or not connected.
* 404:
* description: Container not found.
* 500:
* description: Failed to unpause container.
*/
app.post(
"/docker/containers/:sessionId/:containerId/unpause",
async (req, res) => {
const { sessionId, containerId } = req.params;
const userId = getRequestUserId(req);
if (!userId) {
return res.status(401).json({ error: "Authentication required" });
}
const session = sshSessions[sessionId];
if (!session || !session.isConnected) {
return res.status(400).json({
error: "SSH session not found or not connected",
});
}
session.lastActive = Date.now();
session.activeOperations++;
try {
sshLogger.info("Docker container operation", {
operation: "docker_container_op",
sessionId,
userId,
hostId: session.hostId,
containerId,
action: "unpause",
});
await executeDockerCommand(
session,
`docker unpause ${containerId}`,
sessionId,
userId,
session.hostId,
);
session.activeOperations--;
res.json({
success: true,
message: "Container unpaused successfully",
});
} catch (error) {
session.activeOperations--;
const errorMsg = error instanceof Error ? error.message : "";
if (errorMsg.includes("No such container")) {
return res.status(404).json({
success: false,
error: "Container not found",
code: "CONTAINER_NOT_FOUND",
});
}
sshLogger.error("Failed to unpause container", error, {
operation: "unpause_container",
sessionId,
containerId,
userId,
});
res.status(500).json({
success: false,
error: errorMsg || "Failed to unpause container",
});
}
},
);
/**
* @openapi
* /docker/containers/{sessionId}/{containerId}/remove:
* delete:
* summary: Remove container
* description: Removes a specific container.
* tags:
* - Docker
* parameters:
* - in: path
* name: sessionId
* required: true
* schema:
* type: string
* - in: path
* name: containerId
* required: true
* schema:
* type: string
* - in: query
* name: force
* schema:
* type: boolean
* responses:
* 200:
* description: Container removed successfully.
* 400:
* description: SSH session not found or not connected, or cannot remove a running container.
* 404:
* description: Container not found.
* 500:
* description: Failed to remove container.
*/
app.delete(
"/docker/containers/:sessionId/:containerId/remove",
async (req, res) => {
const { sessionId, containerId } = req.params;
const force = req.query.force === "true";
const userId = getRequestUserId(req);
if (!userId) {
return res.status(401).json({ error: "Authentication required" });
}
const session = sshSessions[sessionId];
if (!session || !session.isConnected) {
return res.status(400).json({
error: "SSH session not found or not connected",
});
}
session.lastActive = Date.now();
session.activeOperations++;
try {
sshLogger.info("Docker container operation", {
operation: "docker_container_op",
sessionId,
userId,
hostId: session.hostId,
containerId,
action: "remove",
});
const forceFlag = force ? "-f " : "";
await executeDockerCommand(
session,
`docker rm ${forceFlag}${containerId}`,
sessionId,
userId,
session.hostId,
);
session.activeOperations--;
res.json({
success: true,
message: "Container removed successfully",
});
} catch (error) {
session.activeOperations--;
const errorMsg = error instanceof Error ? error.message : "";
if (errorMsg.includes("No such container")) {
return res.status(404).json({
success: false,
error: "Container not found",
code: "CONTAINER_NOT_FOUND",
});
}
if (errorMsg.includes("cannot remove a running container")) {
return res.status(400).json({
success: false,
error:
"Cannot remove a running container. Stop it first or use force.",
code: "CONTAINER_RUNNING",
});
}
sshLogger.error("Failed to remove container", error, {
operation: "remove_container",
sessionId,
containerId,
userId,
});
res.status(500).json({
success: false,
error: errorMsg || "Failed to remove container",
});
}
},
);
/**
* @openapi
* /docker/containers/{sessionId}/{containerId}/logs:
* get:
* summary: Get container logs
* description: Retrieves logs for a specific container.
* tags:
* - Docker
* parameters:
* - in: path
* name: sessionId
* required: true
* schema:
* type: string
* - in: path
* name: containerId
* required: true
* schema:
* type: string
* - in: query
* name: tail
* schema:
* type: integer
* - in: query
* name: timestamps
* schema:
* type: boolean
* - in: query
* name: since
* schema:
* type: string
* - in: query
* name: until
* schema:
* type: string
* responses:
* 200:
* description: Container logs.
* 400:
* description: SSH session not found or not connected.
* 404:
* description: Container not found.
* 500:
* description: Failed to get container logs.
*/
app.get(
"/docker/containers/:sessionId/:containerId/logs",
async (req, res) => {
const { sessionId, containerId } = req.params;
const tail = req.query.tail ? parseInt(req.query.tail as string) : 100;
const timestamps = req.query.timestamps === "true";
const since = req.query.since as string;
const until = req.query.until as string;
const userId = getRequestUserId(req);
if (!userId) {
return res.status(401).json({ error: "Authentication required" });
}
const session = sshSessions[sessionId];
if (!session || !session.isConnected) {
return res.status(400).json({
error: "SSH session not found or not connected",
});
}
session.lastActive = Date.now();
session.activeOperations++;
try {
let command = `docker logs ${containerId} 2>&1`;
if (tail && tail > 0) {
command += ` --tail ${Math.floor(tail)}`;
}
if (timestamps) {
command += " --timestamps";
}
if (since && DOCKER_TIMESTAMP_RE.test(since)) {
command += ` --since ${since}`;
}
if (until && DOCKER_TIMESTAMP_RE.test(until)) {
command += ` --until ${until}`;
}
const logs = await executeDockerCommand(
session,
command,
sessionId,
userId,
session.hostId,
);
session.activeOperations--;
res.json({
success: true,
logs,
});
} catch (error) {
session.activeOperations--;
const errorMsg = error instanceof Error ? error.message : "";
if (errorMsg.includes("No such container")) {
return res.status(404).json({
success: false,
error: "Container not found",
code: "CONTAINER_NOT_FOUND",
});
}
sshLogger.error("Failed to get container logs", error, {
operation: "get_logs",
sessionId,
containerId,
userId,
});
res.status(500).json({
success: false,
error: errorMsg || "Failed to get container logs",
});
}
},
);
/**
* @openapi
* /docker/containers/{sessionId}/{containerId}/stats:
* get:
* summary: Get container stats
* description: Retrieves stats for a specific container.
* tags:
* - Docker
* parameters:
* - in: path
* name: sessionId
* required: true
* schema:
* type: string
* - in: path
* name: containerId
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Container stats.
* 400:
* description: SSH session not found or not connected.
* 404:
* description: Container not found.
* 500:
* description: Failed to get container stats.
*/
app.get(
"/docker/containers/:sessionId/:containerId/stats",
async (req, res) => {
const { sessionId, containerId } = req.params;
const userId = getRequestUserId(req);
if (!userId) {
return res.status(401).json({ error: "Authentication required" });
}
const session = sshSessions[sessionId];
if (!session || !session.isConnected) {
return res.status(400).json({
error: "SSH session not found or not connected",
});
}
session.lastActive = Date.now();
session.activeOperations++;
try {
const command = `docker stats ${containerId} --no-stream --format '{"cpu":"{{.CPUPerc}}","memory":"{{.MemUsage}}","memoryPercent":"{{.MemPerc}}","netIO":"{{.NetIO}}","blockIO":"{{.BlockIO}}","pids":"{{.PIDs}}"}'`;
const output = await executeDockerCommand(
session,
command,
sessionId,
userId,
session.hostId,
);
const rawStats = JSON.parse(output.trim());
const memoryParts = rawStats.memory.split(" / ");
const memoryUsed = memoryParts[0]?.trim() || "0B";
const memoryLimit = memoryParts[1]?.trim() || "0B";
const netIOParts = rawStats.netIO.split(" / ");
const netInput = netIOParts[0]?.trim() || "0B";
const netOutput = netIOParts[1]?.trim() || "0B";
const blockIOParts = rawStats.blockIO.split(" / ");
const blockRead = blockIOParts[0]?.trim() || "0B";
const blockWrite = blockIOParts[1]?.trim() || "0B";
const stats = {
cpu: rawStats.cpu,
memoryUsed,
memoryLimit,
memoryPercent: rawStats.memoryPercent,
netInput,
netOutput,
blockRead,
blockWrite,
pids: rawStats.pids,
};
session.activeOperations--;
res.json(stats);
} catch (error) {
session.activeOperations--;
const errorMsg = error instanceof Error ? error.message : "";
if (errorMsg.includes("No such container")) {
return res.status(404).json({
success: false,
error: "Container not found",
code: "CONTAINER_NOT_FOUND",
});
}
sshLogger.error("Failed to get container stats", error, {
operation: "get_stats",
sessionId,
containerId,
userId,
});
res.status(500).json({
success: false,
error: errorMsg || "Failed to get container stats",
});
}
},
);
}