Files
Termix/src/backend/ssh/tunnel.ts
T
Luke Gustafson 9de904dd4c release-2.5.0 (#994)
* feat(sshid) - sshid.io equivalent for termix (#919)

* feat(ssh-id): database schema, migrations and field encryption

Adds ssh_identities, ssh_identity_keys and ssh_identity_ca tables (public keys
stored plaintext for the unauthenticated resolver; CA private key registered
for per-user field encryption), with UNIQUE(user_id), an index on
ssh_identity_keys(identity_id), and idempotent CREATE TABLE migrations.

* feat(ssh-id): backend API — resolver, key management, CA and certificates

Mounts /sshid (nginx route added). Public text/plain authorized_keys resolver
(+ exact /:algo filter, HTML viewer) and CA public-key endpoint; no-store +
noindex headers on every resolver response including early 404s. Authenticated
management: claim/rename/delete handle, add/import/generate/enable/delete keys,
and a per-user CA (create/rotate/delete) with pure-Node OpenSSH certificate
issuance. Audit logging on all mutations; UNIQUE races map to a precise 409.
Unit tests for key parsing and certificate signing (ssh-keygen-validated).

* feat(ssh-id): frontend panel, API client and i18n

SSH ID panel wired into the app rail and AppShell: claim handle, resolver URL +
curl one-liner, key list, generate, paste/import, CA enable/rotate/remove with
server trust command, and per-key certificate issuance. API client re-exported
through main-axios.ts; all strings i18n'd.

* style(ssh-id): align panel and resolver page with Termix theme

- Rebuild the SSH ID sidebar panel with the theme's square components
  (SectionCard / SettingRow / FakeSwitch) instead of rounded ad-hoc cards;
  use accent-brand and destructive tokens rather than raw red/green.
- Fix panel scrolling: move overflow to a block scroll container so the
  cards keep their natural height instead of being clipped.
- Restyle the public resolver HTML page (/sshid/u/:handle) to the Termix
  dark theme: square corners, #18181b/#303032 palette, #f59145 accent,
  uppercase section labels.
- Tidy copy: 'Save To Credentials' label, drop the redundant generate intro,
  and correct the generate tooltip (the key is stored when saving to vault).

* feat: rename to Termix ID, improve UI, backend inconsistencies, and general bug fixes

---------

Co-authored-by: LukeGus <bugattiguy527@gmail.com>

* ci(deps): bump actions/checkout from 6 to 7 in the github-actions group (#922)

Bumps the github-actions group with 1 update: [actions/checkout](https://github.com/actions/checkout).


Updates `actions/checkout` from 6 to 7
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps-dev): bump the dev-patch-updates group with 11 updates (#923)

Bumps the dev-patch-updates group with 11 updates:

| Package | From | To |
| --- | --- | --- |
| [@codemirror/search](https://github.com/codemirror/search) | `6.7.0` | `6.7.1` |
| [@codemirror/view](https://github.com/codemirror/view) | `6.43.0` | `6.43.1` |
| [@tailwindcss/vite](https://github.com/tailwindlabs/tailwindcss/tree/HEAD/packages/@tailwindcss-vite) | `4.3.0` | `4.3.1` |
| [@vitest/coverage-v8](https://github.com/vitest-dev/vitest/tree/HEAD/packages/coverage-v8) | `4.1.8` | `4.1.9` |
| [@vitest/ui](https://github.com/vitest-dev/vitest/tree/HEAD/packages/ui) | `4.1.8` | `4.1.9` |
| [eslint-plugin-react-refresh](https://github.com/ArnaudBarre/eslint-plugin-react-refresh) | `0.5.2` | `0.5.3` |
| [lint-staged](https://github.com/lint-staged/lint-staged) | `17.0.7` | `17.0.8` |
| [prettier](https://github.com/prettier/prettier) | `3.8.3` | `3.8.4` |
| [sharp](https://github.com/lovell/sharp) | `0.35.1` | `0.35.2` |
| [tailwindcss](https://github.com/tailwindlabs/tailwindcss/tree/HEAD/packages/tailwindcss) | `4.3.0` | `4.3.1` |
| [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest) | `4.1.8` | `4.1.9` |


Updates `@codemirror/search` from 6.7.0 to 6.7.1
- [Changelog](https://github.com/codemirror/search/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/search/commits)

Updates `@codemirror/view` from 6.43.0 to 6.43.1
- [Changelog](https://github.com/codemirror/view/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/view/commits)

Updates `@tailwindcss/vite` from 4.3.0 to 4.3.1
- [Release notes](https://github.com/tailwindlabs/tailwindcss/releases)
- [Changelog](https://github.com/tailwindlabs/tailwindcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/tailwindlabs/tailwindcss/commits/v4.3.1/packages/@tailwindcss-vite)

Updates `@vitest/coverage-v8` from 4.1.8 to 4.1.9
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.9/packages/coverage-v8)

Updates `@vitest/ui` from 4.1.8 to 4.1.9
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.9/packages/ui)

Updates `eslint-plugin-react-refresh` from 0.5.2 to 0.5.3
- [Release notes](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/releases)
- [Changelog](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/compare/v0.5.2...v0.5.3)

Updates `lint-staged` from 17.0.7 to 17.0.8
- [Release notes](https://github.com/lint-staged/lint-staged/releases)
- [Changelog](https://github.com/lint-staged/lint-staged/blob/main/CHANGELOG.md)
- [Commits](https://github.com/lint-staged/lint-staged/compare/v17.0.7...v17.0.8)

Updates `prettier` from 3.8.3 to 3.8.4
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/3.8.3...3.8.4)

Updates `sharp` from 0.35.1 to 0.35.2
- [Release notes](https://github.com/lovell/sharp/releases)
- [Commits](https://github.com/lovell/sharp/compare/v0.35.1...v0.35.2)

Updates `tailwindcss` from 4.3.0 to 4.3.1
- [Release notes](https://github.com/tailwindlabs/tailwindcss/releases)
- [Changelog](https://github.com/tailwindlabs/tailwindcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/tailwindlabs/tailwindcss/commits/v4.3.1/packages/tailwindcss)

Updates `vitest` from 4.1.8 to 4.1.9
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.9/packages/vitest)

---
updated-dependencies:
- dependency-name: "@codemirror/search"
  dependency-version: 6.7.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@codemirror/view"
  dependency-version: 6.43.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@tailwindcss/vite"
  dependency-version: 4.3.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@vitest/coverage-v8"
  dependency-version: 4.1.9
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@vitest/ui"
  dependency-version: 4.1.9
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: eslint-plugin-react-refresh
  dependency-version: 0.5.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: lint-staged
  dependency-version: 17.0.8
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: prettier
  dependency-version: 3.8.4
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: sharp
  dependency-version: 0.35.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: tailwindcss
  dependency-version: 4.3.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: vitest
  dependency-version: 4.1.9
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps): bump nanoid in the prod-patch-updates group (#925)

Bumps the prod-patch-updates group with 1 update: [nanoid](https://github.com/ai/nanoid).


Updates `nanoid` from 5.1.11 to 5.1.15
- [Release notes](https://github.com/ai/nanoid/releases)
- [Changelog](https://github.com/ai/nanoid/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ai/nanoid/compare/5.1.11...5.1.15)

---
updated-dependencies:
- dependency-name: nanoid
  dependency-version: 5.1.15
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: prod-patch-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps): bump the major-updates group with 5 updates (#926)

Bumps the major-updates group with 5 updates:

| Package | From | To |
| --- | --- | --- |
| [js-yaml](https://github.com/nodeca/js-yaml) | `4.2.0` | `5.0.0` |
| [@eslint/js](https://github.com/eslint/eslint/tree/HEAD/packages/js) | `9.39.4` | `10.0.1` |
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `25.9.2` | `26.0.0` |
| [concurrently](https://github.com/open-cli-tools/concurrently) | `9.2.1` | `10.0.3` |
| [eslint](https://github.com/eslint/eslint) | `9.39.4` | `10.5.0` |


Updates `js-yaml` from 4.2.0 to 5.0.0
- [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/4.2.0...5.0.0)

Updates `@eslint/js` from 9.39.4 to 10.0.1
- [Release notes](https://github.com/eslint/eslint/releases)
- [Commits](https://github.com/eslint/eslint/commits/v10.0.1/packages/js)

Updates `@types/node` from 25.9.2 to 26.0.0
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Updates `concurrently` from 9.2.1 to 10.0.3
- [Release notes](https://github.com/open-cli-tools/concurrently/releases)
- [Commits](https://github.com/open-cli-tools/concurrently/compare/v9.2.1...v10.0.3)

Updates `eslint` from 9.39.4 to 10.5.0
- [Release notes](https://github.com/eslint/eslint/releases)
- [Commits](https://github.com/eslint/eslint/compare/v9.39.4...v10.5.0)

---
updated-dependencies:
- dependency-name: js-yaml
  dependency-version: 5.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: major-updates
- dependency-name: "@eslint/js"
  dependency-version: 10.0.1
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: major-updates
- dependency-name: "@types/node"
  dependency-version: 26.0.0
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: major-updates
- dependency-name: concurrently
  dependency-version: 10.0.3
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: major-updates
- dependency-name: eslint
  dependency-version: 10.5.0
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: major-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* feat(ssh): add HashiCorp Vault SSH signer authentication

* fix: small fixes to vault feature to align with Termix codebase

* chore: add view docs links for vault/termix id

* fix: file upload fails with 400 and missing schema migrations on upgrade (#929)

Two bugs introduced in v2.4.1:

1. uploadFileStream uses fileManagerApi.post() which triggers axios's
   transformRequest to JSON-serialize the FormData because the instance
   default Content-Type is application/json. Change to postForm() which
   sets Content-Type: multipart/form-data so the browser XHR sends the
   correct multipart body with boundary.

2. Two schema items added to schema.ts were not included in migrateSchema()
   in db/index.ts, causing 500 errors on existing installations upgrading
   from v2.4.0:
   - user_preferences.status_color_scheme (no such column)
   - dashboard_service_links table (no such table)

Fixes #928

Co-authored-by: sash <sash@fominykh.io>

* fix: support PuTTY PPK ssh keys (#930)

* fix: chunk large file manager uploads (#932)

* fix: route dashboard hosts by protocol (#934)

* fix: resolve tunnel endpoints reliably (#935)

* Fix Electron OIDC browser auth failures (#936)

* Allow RDP connections without stored credentials (#937)

* Sync role credential shares for OIDC users (#938)

* Fix terminal link dialog layering (#940)

* Confirm large files before opening editor (#942)

* Confirm closing active host connections (#943)

* Preserve file path case in file manager UI (#941)

* fix: preserve unicode guacamole tokens (#933)

* Persist VNC authentication settings (#944)

* Fix Guacamole websocket base path (#946)

* Promote file manager terminals to tabs (#939)

* Guard Guacamole disconnect during startup (#945)

* chore: increment ver

* feat: bitwarden ssh agent integration

* feat: serial connections support

* fix: various small bug fixes

* feat: open all sessions in a folder and terminal custom theme color support

* feat: cross host file manager clipboard and several small bug fixes

* feat: tailscale/wireguard support and added a new status state for when backend is checking status

* feat: grafana like server stats history, new alert system, ntfy/webhook support

* feat: new grid and widget based homepage function

* feat: new donate button in dashboard

* fix: alert ui incorrectly using termix css and fixed issue with alert system not loading

* chore: fix ci checks (#966)

* Fix dashboard service link creation (#950)

* Fix jump host SOCKS5 proxy selection (#951)

* Fix jump host SOCKS5 proxy selection

* fix: type jump host socks proxy config

* Fix tmux detection path handling (#949)

* Support GUACD_URL environment config (#952)

* Retry autostart tunnel host fetches (#953)

* Retry autostart tunnel host fetches

* chore: format tunnel route

* Fix PUID html ownership in Docker entrypoint (#954)

* feat: allow custom tunnel endpoints (#977)

* fix: skip metrics start for non-ssh hosts (#976)

* Fix Proxmox import auth fallback (#956)

* Fix Proxmox import auth fallback

* chore: format proxmox import auth

* Fix SSH heading syntax highlighting (#955)

* Fix SSH heading syntax highlighting

* chore: format terminal highlighter

* Initialize auth before fullscreen terminal routes (#957)

* Add WebAuthn passkey authentication (#959)

* chore: add Biome tooling (#965)

* chore: add biome tooling

* chore: support tailwind syntax in biome

* Fix VNC required argument handshake (#968)

* Prioritize host results in command palette search (#969)

* Prevent sidebar host hover layout shift (#970)

* Add terminal font zoom with mouse wheel (#971)

* Add host temperature metrics card (#972)

* Make file downloads reliable in desktop app (#973)

* Add app rail hover expansion setting (#974)

* fix: use correct translation key for nav.close (#964)

* fix(tunnel): skip endpoint credential validation for direct tunnels (#963)

* fix: SSH port connection bug (#975)

* fix: chunked upload for files >=1.5GB to bypass browser ArrayBuffer limit (#948)

* feat: support SSH agent auth across SSH features (#960)

* feat: add Podman container runtime support (#958)

* chore: update readme and release notes

* fix: stabilize Windows app icon (#978)

* Add safe host sharing export (#979)

* Add external editor support for file manager (#985)

* Rework SSH credential password handling (#984)

* Support password fallback for SSH key credentials

* Complete SSH credential password fallback

* Fix runtime base path for auth callbacks (#982)

* Fix TUI terminal output highlighting (#983)

Co-authored-by: LukeGus <bugattiguy527@gmail.com>

* Add app fullscreen mode (#993)

* Fix host metrics startup polling (#986)

* chore: update release notes

* fix: line chart text overlap

* chore: update RELEASE_NOTES.md

* chore: add donation goal to readme

* chore: update readme

* fix: hide full-screen button in electron app

* fix: failed unit tests

* chore: lint, format, and bump version to 2.5.0

* chore: remove timeout from crowdin translate

* chore: sync Crowdin translations for 2.5.0

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: DivByZero <mr.oplus@yahoo.fr>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: devdanetra <46488477+devdanetra@users.noreply.github.com>
Co-authored-by: Aleksandr Fominykh <neoformalex@users.noreply.github.com>
Co-authored-by: sash <sash@fominykh.io>
Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com>
2026-06-29 13:28:26 -05:00

2494 lines
74 KiB
TypeScript

import express, { type Response } from "express";
import { createServer } from "http";
import {
createServer as createTcpServer,
Socket as TcpSocket,
type Server as TcpServer,
} from "net";
import { createCorsMiddleware } from "../utils/cors-config.js";
import cookieParser from "cookie-parser";
import { Client, type ClientChannel } from "ssh2";
import { WebSocketServer } from "ws";
import { SSH_ALGORITHMS } from "../utils/ssh-algorithms.js";
import { ChildProcess } from "child_process";
import axios from "axios";
import { getDb } from "../database/db/index.js";
import { sshCredentials } from "../database/db/schema.js";
import { eq } from "drizzle-orm";
import type {
SSHHost,
TunnelConfig,
TunnelStatus,
VerificationData,
AuthenticatedRequest,
} from "../../types/index.js";
import { CONNECTION_STATES } from "../../types/index.js";
import { tunnelLogger } from "../utils/logger.js";
import { logAudit } from "../utils/audit-logger.js";
import { SystemCrypto } from "../utils/system-crypto.js";
import { SimpleDBOps } from "../utils/simple-db-ops.js";
import { DataCrypto } from "../utils/data-crypto.js";
import { createSocks5Connection } from "../utils/socks5-helper.js";
import { AuthManager } from "../utils/auth-manager.js";
import { PermissionManager } from "../utils/permission-manager.js";
import { withConnection } from "./ssh-connection-pool.js";
import { preparePrivateKeyForSSH2 } from "../utils/ssh-key-utils.js";
import {
applyAuthOptions,
bindForwardIn,
connectClient,
forwardOut,
getManagedTunnelAlgorithms,
pipeTunnelStreams,
unbindForwardIn,
} from "./tunnel-ssh-primitives.js";
import {
classifyTunnelError,
getTunnelBindHost,
getTunnelMarker,
getTunnelMode,
getTunnelScope,
normalizeTunnelName,
validateTunnelConfig,
} from "./tunnel-utils.js";
import {
describeC2SRelayError,
extractRequestToken,
sendC2SError,
} from "./tunnel-c2s-relay-utils.js";
import {
handleC2SRelayOpen,
handleC2SRelayTest,
type C2SOpenMessage,
} from "./tunnel-c2s-relay.js";
import { handleSocks5Connect } from "./tunnel-socks5-relay.js";
const app = express();
app.use(createCorsMiddleware(["GET", "POST", "PUT", "DELETE", "OPTIONS"]));
app.use(cookieParser());
app.use(express.json());
app.use((_req, res, next) => {
res.setHeader("Cache-Control", "no-store");
next();
});
const authManager = AuthManager.getInstance();
const permissionManager = PermissionManager.getInstance();
const authenticateJWT = authManager.createAuthMiddleware();
const activeTunnels = new Map<string, Client>();
const retryCounters = new Map<string, number>();
const connectionStatus = new Map<string, TunnelStatus>();
const tunnelVerifications = new Map<string, VerificationData>();
const manualDisconnects = new Set<string>();
const verificationTimers = new Map<string, NodeJS.Timeout>();
const activeRetryTimers = new Map<string, NodeJS.Timeout>();
const countdownIntervals = new Map<string, NodeJS.Timeout>();
const retryExhaustedTunnels = new Set<string>();
const cleanupInProgress = new Set<string>();
const tunnelConnecting = new Set<string>();
const lastTunnelErrors = new Map<string, string>();
const lastTunnelErrorTypes = new Map<string, TunnelStatus["errorType"]>();
const tunnelConfigs = new Map<string, TunnelConfig>();
const activeTunnelProcesses = new Map<string, ChildProcess>();
const pendingTunnelOperations = new Map<string, Promise<void>>();
const tunnelStatusClients = new Set<Response>();
const INTERNAL_HOST_API_BASE_URL = "http://localhost:30001/host/db/host";
const AUTOSTART_FETCH_RETRIES = 6;
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function describeAxiosError(error: unknown): string {
if (axios.isAxiosError(error)) {
return error.response
? `${error.response.status} ${error.response.statusText}`
: error.message;
}
return error instanceof Error ? error.message : "Unknown error";
}
async function fetchInternalHosts(
path: "internal" | "internal/all",
internalAuthToken: string,
): Promise<SSHHost[]> {
let lastError: unknown;
for (let attempt = 1; attempt <= AUTOSTART_FETCH_RETRIES; attempt++) {
try {
const response = await axios.get(
`${INTERNAL_HOST_API_BASE_URL}/${path}`,
{
headers: {
"Content-Type": "application/json",
"X-Internal-Auth-Token": internalAuthToken,
},
timeout: 5000,
},
);
return response.data || [];
} catch (error) {
lastError = error;
if (attempt === AUTOSTART_FETCH_RETRIES) {
break;
}
const retryDelayMs = Math.min(500 * 2 ** (attempt - 1), 5000);
tunnelLogger.warn("Internal host API unavailable, retrying", {
operation: "tunnel_autostart_fetch_retry",
path,
attempt,
maxAttempts: AUTOSTART_FETCH_RETRIES,
retryDelayMs,
error: describeAxiosError(error),
});
await sleep(retryDelayMs);
}
}
throw new Error(
`Failed to fetch ${path} hosts after ${AUTOSTART_FETCH_RETRIES} attempts: ${describeAxiosError(lastError)}`,
);
}
type ActiveTunnelRuntime = {
sourceClient: Client;
endpointClient?: Client;
bindClient?: Client;
bindHost?: string;
bindPort?: number;
tcpServer?: TcpServer;
close: () => void;
};
const activeTunnelRuntimes = new Map<string, ActiveTunnelRuntime>();
function findHostByTunnelEndpoint(
hosts: SSHHost[],
endpointHost?: string,
): SSHHost | undefined {
const value = endpointHost?.trim();
if (!value) return undefined;
return hosts.find((host) => {
const userAtIp = `${host.username}@${host.ip}`;
return (
String(host.id) === value ||
host.name === value ||
host.ip === value ||
userAtIp === value
);
});
}
function broadcastTunnelStatus(tunnelName: string, status: TunnelStatus): void {
if (
status.status === CONNECTION_STATES.CONNECTED &&
activeRetryTimers.has(tunnelName)
) {
return;
}
const nextStatus = { ...status };
if (
retryExhaustedTunnels.has(tunnelName) &&
nextStatus.status === CONNECTION_STATES.FAILED
) {
const previousReason = lastTunnelErrors.get(tunnelName);
nextStatus.reason = previousReason
? `Max retries exhausted: ${previousReason}`
: "Max retries exhausted";
}
if (nextStatus.status === CONNECTION_STATES.FAILED && nextStatus.reason) {
lastTunnelErrors.set(tunnelName, nextStatus.reason);
if (nextStatus.errorType) {
lastTunnelErrorTypes.set(tunnelName, nextStatus.errorType);
}
} else if (
(nextStatus.status === CONNECTION_STATES.CONNECTING ||
nextStatus.status === CONNECTION_STATES.RETRYING ||
nextStatus.status === CONNECTION_STATES.WAITING) &&
!nextStatus.reason
) {
nextStatus.reason = lastTunnelErrors.get(tunnelName);
nextStatus.errorType = lastTunnelErrorTypes.get(tunnelName);
} else if (
nextStatus.status === CONNECTION_STATES.CONNECTED ||
(nextStatus.status === CONNECTION_STATES.DISCONNECTED &&
nextStatus.manualDisconnect)
) {
lastTunnelErrors.delete(tunnelName);
lastTunnelErrorTypes.delete(tunnelName);
}
connectionStatus.set(tunnelName, nextStatus);
broadcastTunnelStatusSnapshot();
}
function getAllTunnelStatus(): Record<string, TunnelStatus> {
const tunnelStatus: Record<string, TunnelStatus> = {};
connectionStatus.forEach((status, key) => {
tunnelStatus[key] = status;
});
return tunnelStatus;
}
function sendTunnelStatusSnapshot(res: Response): void {
try {
res.write(
`event: statuses\ndata: ${JSON.stringify(getAllTunnelStatus())}\n\n`,
);
} catch {
tunnelStatusClients.delete(res);
}
}
function broadcastTunnelStatusSnapshot(): void {
for (const client of tunnelStatusClients) {
sendTunnelStatusSnapshot(client);
}
}
async function cleanupTunnelResources(
tunnelName: string,
forceCleanup = false,
): Promise<void> {
if (cleanupInProgress.has(tunnelName)) {
return;
}
if (!forceCleanup && tunnelConnecting.has(tunnelName)) {
return;
}
cleanupInProgress.add(tunnelName);
const tunnelConfig = tunnelConfigs.get(tunnelName);
const runtime = activeTunnelRuntimes.get(tunnelName);
if (runtime) {
try {
runtime.close();
} catch (error) {
tunnelLogger.error("Error while closing managed tunnel runtime", error, {
operation: "managed_tunnel_cleanup",
tunnelName,
});
}
activeTunnelRuntimes.delete(tunnelName);
cleanupInProgress.delete(tunnelName);
} else if (tunnelConfig) {
await new Promise<void>((resolve) => {
killRemoteTunnelByMarker(tunnelConfig, tunnelName, (err) => {
cleanupInProgress.delete(tunnelName);
if (err) {
tunnelLogger.error(
`Failed to kill remote tunnel for '${tunnelName}': ${err.message}`,
);
}
resolve();
});
});
} else {
cleanupInProgress.delete(tunnelName);
}
if (activeTunnelProcesses.has(tunnelName)) {
try {
const proc = activeTunnelProcesses.get(tunnelName);
if (proc) {
proc.kill("SIGTERM");
}
} catch (e) {
tunnelLogger.error(
`Error while killing local ssh process for tunnel '${tunnelName}'`,
e,
);
}
activeTunnelProcesses.delete(tunnelName);
}
if (activeTunnels.has(tunnelName)) {
try {
const conn = activeTunnels.get(tunnelName);
if (conn) {
conn.end();
}
} catch (e) {
tunnelLogger.error(
`Error while closing SSH2 Client for tunnel '${tunnelName}'`,
e,
);
}
activeTunnels.delete(tunnelName);
}
if (tunnelVerifications.has(tunnelName)) {
const verification = tunnelVerifications.get(tunnelName);
if (verification?.timeout) clearTimeout(verification.timeout);
try {
verification?.conn.end();
} catch (error) {
tunnelLogger.error("Error during tunnel cleanup", error, {
operation: "tunnel_cleanup_error",
tunnelName,
});
}
tunnelVerifications.delete(tunnelName);
}
const timerKeys = [
tunnelName,
`${tunnelName}_confirm`,
`${tunnelName}_retry`,
`${tunnelName}_verify_retry`,
`${tunnelName}_ping`,
];
timerKeys.forEach((key) => {
if (verificationTimers.has(key)) {
clearTimeout(verificationTimers.get(key)!);
verificationTimers.delete(key);
}
});
if (activeRetryTimers.has(tunnelName)) {
clearTimeout(activeRetryTimers.get(tunnelName)!);
activeRetryTimers.delete(tunnelName);
}
if (countdownIntervals.has(tunnelName)) {
clearInterval(countdownIntervals.get(tunnelName)!);
countdownIntervals.delete(tunnelName);
}
}
function resetRetryState(tunnelName: string): void {
retryCounters.delete(tunnelName);
retryExhaustedTunnels.delete(tunnelName);
lastTunnelErrors.delete(tunnelName);
lastTunnelErrorTypes.delete(tunnelName);
cleanupInProgress.delete(tunnelName);
tunnelConnecting.delete(tunnelName);
if (activeRetryTimers.has(tunnelName)) {
clearTimeout(activeRetryTimers.get(tunnelName)!);
activeRetryTimers.delete(tunnelName);
}
if (countdownIntervals.has(tunnelName)) {
clearInterval(countdownIntervals.get(tunnelName)!);
countdownIntervals.delete(tunnelName);
}
["", "_confirm", "_retry", "_verify_retry", "_ping"].forEach((suffix) => {
const timerKey = `${tunnelName}${suffix}`;
if (verificationTimers.has(timerKey)) {
clearTimeout(verificationTimers.get(timerKey)!);
verificationTimers.delete(timerKey);
}
});
}
async function handleDisconnect(
tunnelName: string,
tunnelConfig: TunnelConfig | null,
shouldRetry = true,
): Promise<void> {
if (tunnelVerifications.has(tunnelName)) {
try {
const verification = tunnelVerifications.get(tunnelName);
if (verification?.timeout) clearTimeout(verification.timeout);
verification?.conn.end();
} catch (error) {
tunnelLogger.error("Error during tunnel cleanup", error, {
operation: "tunnel_cleanup_error",
tunnelName,
});
}
tunnelVerifications.delete(tunnelName);
}
while (cleanupInProgress.has(tunnelName)) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
await cleanupTunnelResources(tunnelName);
if (manualDisconnects.has(tunnelName)) {
resetRetryState(tunnelName);
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.DISCONNECTED,
manualDisconnect: true,
});
return;
}
if (retryExhaustedTunnels.has(tunnelName)) {
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.FAILED,
reason: "Max retries already exhausted",
});
return;
}
if (activeRetryTimers.has(tunnelName)) {
return;
}
if (shouldRetry && tunnelConfig) {
const maxRetries = tunnelConfig.maxRetries || 3;
const retryInterval = tunnelConfig.retryInterval || 5000;
let retryCount = retryCounters.get(tunnelName) || 0;
retryCount = retryCount + 1;
if (retryCount > maxRetries) {
tunnelLogger.error(`All ${maxRetries} retries failed for ${tunnelName}`);
retryExhaustedTunnels.add(tunnelName);
activeTunnels.delete(tunnelName);
retryCounters.delete(tunnelName);
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.FAILED,
retryExhausted: true,
reason: `Max retries exhausted`,
});
return;
}
retryCounters.set(tunnelName, retryCount);
if (retryCount <= maxRetries) {
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.RETRYING,
retryCount: retryCount,
maxRetries: maxRetries,
nextRetryIn: retryInterval / 1000,
});
if (activeRetryTimers.has(tunnelName)) {
clearTimeout(activeRetryTimers.get(tunnelName)!);
activeRetryTimers.delete(tunnelName);
}
const initialNextRetryIn = Math.ceil(retryInterval / 1000);
let currentNextRetryIn = initialNextRetryIn;
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.WAITING,
retryCount: retryCount,
maxRetries: maxRetries,
nextRetryIn: currentNextRetryIn,
});
const countdownInterval = setInterval(() => {
currentNextRetryIn--;
if (currentNextRetryIn > 0) {
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.WAITING,
retryCount: retryCount,
maxRetries: maxRetries,
nextRetryIn: currentNextRetryIn,
});
}
}, 1000);
countdownIntervals.set(tunnelName, countdownInterval);
const timer = setTimeout(() => {
clearInterval(countdownInterval);
countdownIntervals.delete(tunnelName);
activeRetryTimers.delete(tunnelName);
if (!manualDisconnects.has(tunnelName)) {
activeTunnels.delete(tunnelName);
connectSSHTunnel(tunnelConfig, retryCount).catch((error) => {
tunnelLogger.error(
`Failed to connect tunnel ${tunnelConfig.name}: ${error instanceof Error ? error.message : "Unknown error"}`,
);
});
}
}, retryInterval);
activeRetryTimers.set(tunnelName, timer);
}
} else {
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.FAILED,
});
activeTunnels.delete(tunnelName);
}
}
function setupPingInterval(tunnelName: string): void {
const pingKey = `${tunnelName}_ping`;
if (verificationTimers.has(pingKey)) {
clearInterval(verificationTimers.get(pingKey)!);
verificationTimers.delete(pingKey);
}
const pingInterval = setInterval(() => {
const currentStatus = connectionStatus.get(tunnelName);
if (currentStatus?.status === CONNECTION_STATES.CONNECTED) {
if (!activeTunnels.has(tunnelName)) {
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.DISCONNECTED,
reason: "Tunnel connection lost",
});
clearInterval(pingInterval);
verificationTimers.delete(pingKey);
}
} else {
clearInterval(pingInterval);
verificationTimers.delete(pingKey);
}
}, 120000);
verificationTimers.set(pingKey, pingInterval);
}
async function connectEndpointThroughSource(
sourceClient: Client,
tunnelConfig: TunnelConfig,
endpointCredentials: {
password?: string;
sshKey?: string;
keyPassword?: string;
keyType?: string;
authMethod?: string;
},
): Promise<Client> {
const endpointSock = await forwardOut(
sourceClient,
tunnelConfig.endpointIP,
tunnelConfig.endpointSSHPort,
tunnelConfig.name,
);
const endpointOptions: Record<string, unknown> = {
sock: endpointSock,
username: tunnelConfig.endpointUsername,
tryKeyboard: true,
keepaliveInterval: tunnelConfig.keepaliveInterval ?? 30000,
keepaliveCountMax: tunnelConfig.keepaliveCountMax ?? 3,
readyTimeout: 60000,
tcpKeepAlive: true,
tcpKeepAliveInitialDelay: 30000,
algorithms: getManagedTunnelAlgorithms(),
};
applyAuthOptions(endpointOptions, endpointCredentials);
return connectClient(endpointOptions, tunnelConfig.name, "endpoint");
}
function resolveS2SLocalTargetHost(tunnelConfig: TunnelConfig): string {
const targetHost = tunnelConfig.targetHost?.trim();
if (
!targetHost ||
targetHost === tunnelConfig.endpointHost ||
targetHost === tunnelConfig.hostName
) {
return "127.0.0.1";
}
return targetHost;
}
function isSingleHostTunnel(tunnelConfig: TunnelConfig): boolean {
if (!tunnelConfig.endpointHost && !tunnelConfig.endpointIP) return true;
if (
tunnelConfig.endpointHost === "127.0.0.1" ||
tunnelConfig.endpointHost === "localhost"
) {
return true;
}
if (
tunnelConfig.endpointIP &&
tunnelConfig.endpointIP === tunnelConfig.sourceIP &&
tunnelConfig.endpointSSHPort === tunnelConfig.sourceSSHPort
) {
return true;
}
return false;
}
function shouldEstablishDirectTunnel(tunnelConfig: TunnelConfig): boolean {
if (isSingleHostTunnel(tunnelConfig)) return true;
const mode = getTunnelMode(tunnelConfig);
return mode !== "remote" && !tunnelConfig.endpointUsername;
}
async function establishDirectTunnel(
sourceClient: Client,
tunnelConfig: TunnelConfig,
): Promise<void> {
const tunnelName = tunnelConfig.name;
const mode = getTunnelMode(tunnelConfig);
const bindHost = getTunnelBindHost(tunnelConfig);
const sourcePort = tunnelConfig.sourcePort;
const targetHost =
tunnelConfig.targetHost || tunnelConfig.endpointHost || "127.0.0.1";
const targetPort = tunnelConfig.endpointPort;
if (mode === "remote") {
const remoteBindPort = await bindForwardIn(
sourceClient,
targetHost,
sourcePort,
);
const sockets = new Set<TcpSocket>();
sourceClient.on("tcp connection", (info, accept, reject) => {
if (info.destPort !== remoteBindPort) {
reject();
return;
}
const inbound = accept();
const local = new TcpSocket();
sockets.add(local);
local.connect(targetPort, bindHost, () => {
pipeTunnelStreams(inbound, Promise.resolve(local), tunnelName);
});
local.on("error", () => {
inbound.destroy();
sockets.delete(local);
});
local.on("close", () => sockets.delete(local));
});
const close = () => {
unbindForwardIn(sourceClient, targetHost, remoteBindPort);
for (const s of sockets) s.destroy();
sockets.clear();
try {
sourceClient.end();
} catch {
// expected
}
};
activeTunnelRuntimes.set(tunnelName, {
sourceClient,
bindHost: targetHost,
bindPort: remoteBindPort,
close,
});
activeTunnels.set(tunnelName, sourceClient);
return;
}
// Local and dynamic modes: listen locally, forward through SSH
const sockets = new Set<TcpSocket>();
const tcpServer = createTcpServer((socket) => {
sockets.add(socket);
socket.on("close", () => sockets.delete(socket));
socket.on("error", () => {
sockets.delete(socket);
socket.destroy();
});
if (mode === "dynamic") {
handleSocks5Connect(
socket,
(host, port) => forwardOut(sourceClient, host, port),
tunnelName,
);
return;
}
forwardOut(sourceClient, targetHost, targetPort, tunnelName)
.then((outbound) =>
pipeTunnelStreams(socket, Promise.resolve(outbound), tunnelName),
)
.catch(() => socket.destroy());
});
await new Promise<void>((resolve, reject) => {
tcpServer.once("error", reject);
tcpServer.listen({ host: bindHost, port: sourcePort }, () => {
tcpServer.removeListener("error", reject);
resolve();
});
});
tunnelLogger.info("Direct tunnel listener started", {
operation: "direct_tunnel_listen",
tunnelName,
mode,
bindHost,
sourcePort,
targetHost,
targetPort,
});
const close = () => {
for (const s of sockets) s.destroy();
sockets.clear();
tcpServer.close();
try {
sourceClient.end();
} catch {
// expected
}
};
sourceClient.on("close", () => {
close();
});
activeTunnelRuntimes.set(tunnelName, {
sourceClient,
tcpServer,
bindHost,
bindPort: sourcePort,
close,
});
activeTunnels.set(tunnelName, sourceClient);
}
async function establishManagedS2STunnel(
sourceClient: Client,
tunnelConfig: TunnelConfig,
endpointCredentials: {
password?: string;
sshKey?: string;
keyPassword?: string;
keyType?: string;
authMethod?: string;
},
): Promise<void> {
const tunnelName = tunnelConfig.name;
const mode = getTunnelMode(tunnelConfig);
const bindHost = getTunnelBindHost(tunnelConfig);
const endpointClient = await connectEndpointThroughSource(
sourceClient,
tunnelConfig,
endpointCredentials,
);
const bindClient = mode === "remote" ? endpointClient : sourceClient;
const outboundClient = mode === "remote" ? sourceClient : endpointClient;
const bindPort =
mode === "remote" ? tunnelConfig.endpointPort : tunnelConfig.sourcePort;
const staticTargetHost =
mode === "remote"
? tunnelConfig.targetHost || "127.0.0.1"
: resolveS2SLocalTargetHost(tunnelConfig);
const staticTargetPort =
mode === "remote" ? tunnelConfig.sourcePort : tunnelConfig.endpointPort;
tunnelLogger.info("Managed S2S tunnel route resolved", {
operation: "managed_tunnel_route_resolved",
tunnelName,
mode,
bindHost,
bindPort,
targetHost: staticTargetHost,
targetPort: staticTargetPort,
endpointHost: tunnelConfig.endpointHost,
endpointIP: tunnelConfig.endpointIP,
});
const actualPort = await bindForwardIn(bindClient, bindHost, bindPort);
const tcpHandler = (
info: {
destIP: string;
destPort: number;
srcIP: string;
srcPort: number;
},
accept: () => ClientChannel,
reject: () => void,
) => {
if (info.destPort !== actualPort) {
reject();
return;
}
const inbound = accept();
if (mode === "dynamic") {
handleSocks5Connect(
inbound,
(host, port) => forwardOut(outboundClient, host, port),
tunnelName,
);
return;
}
pipeTunnelStreams(
inbound,
forwardOut(
outboundClient,
staticTargetHost,
staticTargetPort,
tunnelName,
),
tunnelName,
);
};
bindClient.on("tcp connection", tcpHandler);
const close = () => {
bindClient.off("tcp connection", tcpHandler);
unbindForwardIn(bindClient, bindHost, actualPort);
try {
endpointClient.end();
} catch {
// expected during shutdown
}
try {
sourceClient.end();
} catch {
// expected during shutdown
}
};
activeTunnelRuntimes.set(tunnelName, {
sourceClient,
endpointClient,
bindClient,
bindHost,
bindPort: actualPort,
close,
});
activeTunnels.set(tunnelName, sourceClient);
}
async function connectSSHTunnel(
tunnelConfig: TunnelConfig,
retryAttempt = 0,
): Promise<void> {
const tunnelName = tunnelConfig.name;
tunnelLogger.info("Tunnel creation request received", {
operation: "tunnel_create_request",
userId: tunnelConfig.sourceUserId,
hostId: tunnelConfig.sourceHostId,
tunnelName,
tunnelType: tunnelConfig.tunnelType || "remote",
sourcePort: tunnelConfig.sourcePort,
endpointHost: tunnelConfig.endpointHost,
endpointPort: tunnelConfig.endpointPort,
});
if (manualDisconnects.has(tunnelName)) {
return;
}
tunnelConnecting.add(tunnelName);
await cleanupTunnelResources(tunnelName, true);
if (retryAttempt === 0) {
retryExhaustedTunnels.delete(tunnelName);
retryCounters.delete(tunnelName);
}
const currentStatus = connectionStatus.get(tunnelName);
if (!currentStatus || currentStatus.status !== CONNECTION_STATES.WAITING) {
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.CONNECTING,
retryCount: retryAttempt > 0 ? retryAttempt : undefined,
});
}
if (
!tunnelConfig ||
!tunnelConfig.sourceIP ||
!tunnelConfig.sourceUsername ||
!tunnelConfig.sourceSSHPort
) {
const missingFields = [];
if (!tunnelConfig) missingFields.push("tunnelConfig");
if (!tunnelConfig?.sourceIP) missingFields.push("sourceIP");
if (!tunnelConfig?.sourceUsername) missingFields.push("sourceUsername");
if (!tunnelConfig?.sourceSSHPort) missingFields.push("sourceSSHPort");
tunnelLogger.error("Invalid tunnel connection details", undefined, {
operation: "tunnel_connect_validation_failed",
tunnelName,
missingFields: missingFields.join(", "),
hasSourceIP: !!tunnelConfig?.sourceIP,
hasSourceUsername: !!tunnelConfig?.sourceUsername,
hasSourceSSHPort: !!tunnelConfig?.sourceSSHPort,
});
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.FAILED,
reason: "Missing required connection details",
});
tunnelConnecting.delete(tunnelName);
return;
}
let resolvedSourceCredentials = {
password: tunnelConfig.sourcePassword,
sshKey: tunnelConfig.sourceSSHKey,
keyPassword: tunnelConfig.sourceKeyPassword,
keyType: tunnelConfig.sourceKeyType,
authMethod: tunnelConfig.sourceAuthMethod,
};
const effectiveUserId =
tunnelConfig.requestingUserId || tunnelConfig.sourceUserId;
// Resolve source credentials server-side when not provided by frontend
if (
tunnelConfig.sourceHostId &&
effectiveUserId &&
!tunnelConfig.sourcePassword &&
!tunnelConfig.sourceSSHKey
) {
try {
const { resolveHostById } = await import("./host-resolver.js");
const resolvedHost = await resolveHostById(
tunnelConfig.sourceHostId,
effectiveUserId,
);
if (resolvedHost) {
resolvedSourceCredentials = {
password: resolvedHost.password,
sshKey: resolvedHost.key,
keyPassword: resolvedHost.keyPassword,
keyType: resolvedHost.keyType,
authMethod: resolvedHost.authType,
};
if (tunnelConfig.keepaliveInterval === undefined) {
tunnelConfig.keepaliveInterval =
typeof resolvedHost.terminalConfig?.keepaliveInterval === "number"
? resolvedHost.terminalConfig.keepaliveInterval * 1000
: 60000;
}
if (tunnelConfig.keepaliveCountMax === undefined) {
tunnelConfig.keepaliveCountMax =
typeof resolvedHost.terminalConfig?.keepaliveCountMax === "number"
? resolvedHost.terminalConfig.keepaliveCountMax
: 5;
}
}
} catch (error) {
tunnelLogger.warn("Failed to resolve source host credentials", {
operation: "tunnel_connect",
tunnelName,
sourceHostId: tunnelConfig.sourceHostId,
error: error instanceof Error ? error.message : "Unknown error",
});
}
} else if (tunnelConfig.sourceCredentialId && effectiveUserId) {
// Legacy: credential resolution from credentialId
try {
if (tunnelConfig.sourceHostId) {
const { resolveHostById } = await import("./host-resolver.js");
const resolvedHost = await resolveHostById(
tunnelConfig.sourceHostId,
effectiveUserId,
);
if (resolvedHost) {
resolvedSourceCredentials = {
password: resolvedHost.password,
sshKey: resolvedHost.key,
keyPassword: resolvedHost.keyPassword,
keyType: resolvedHost.keyType,
authMethod: resolvedHost.authType,
};
}
}
} catch (error) {
tunnelLogger.warn("Failed to resolve source credentials", {
operation: "tunnel_connect",
tunnelName,
credentialId: tunnelConfig.sourceCredentialId,
error: error instanceof Error ? error.message : "Unknown error",
});
}
}
let resolvedEndpointCredentials = {
password: tunnelConfig.endpointPassword,
sshKey: tunnelConfig.endpointSSHKey,
keyPassword: tunnelConfig.endpointKeyPassword,
keyType: tunnelConfig.endpointKeyType,
authMethod: tunnelConfig.endpointAuthMethod,
};
if (tunnelConfig.endpointCredentialId && tunnelConfig.endpointUserId) {
try {
const userDataKey = DataCrypto.getUserDataKey(
tunnelConfig.endpointUserId,
);
if (userDataKey) {
const credentials = await SimpleDBOps.select(
getDb()
.select()
.from(sshCredentials)
.where(eq(sshCredentials.id, tunnelConfig.endpointCredentialId)),
"ssh_credentials",
tunnelConfig.endpointUserId,
);
if (credentials.length > 0) {
const credential = credentials[0];
resolvedEndpointCredentials = {
password: credential.password as string | undefined,
sshKey: (credential.key || credential.privateKey) as
| string
| undefined,
keyPassword: credential.keyPassword as string | undefined,
keyType: credential.keyType as string | undefined,
authMethod: credential.authType as string,
};
} else {
tunnelLogger.warn("No endpoint credentials found in database", {
operation: "tunnel_connect",
tunnelName,
credentialId: tunnelConfig.endpointCredentialId,
});
}
}
} catch (error) {
tunnelLogger.warn(
`Failed to resolve endpoint credentials for tunnel ${tunnelName}: ${error instanceof Error ? error.message : "Unknown error"}`,
);
}
} else if (tunnelConfig.endpointCredentialId) {
tunnelLogger.warn("Missing userId for endpoint credential resolution", {
operation: "tunnel_connect",
tunnelName,
credentialId: tunnelConfig.endpointCredentialId,
hasUserId: !!tunnelConfig.endpointUserId,
});
}
if (
!shouldEstablishDirectTunnel(tunnelConfig) &&
resolvedEndpointCredentials.authMethod === "password" &&
!resolvedEndpointCredentials.password
) {
const errorMessage = `Cannot connect tunnel '${tunnelName}': endpoint host requires password authentication but no plaintext password available. Enable autostart for endpoint host or configure credentials in tunnel connection.`;
tunnelLogger.error(errorMessage, undefined, {
operation: "tunnel_endpoint_password_unavailable",
tunnelName,
endpointHost: `${tunnelConfig.endpointUsername}@${tunnelConfig.endpointIP}:${tunnelConfig.endpointPort}`,
endpointAuthMethod: resolvedEndpointCredentials.authMethod,
});
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.FAILED,
reason: errorMessage,
});
tunnelConnecting.delete(tunnelName);
return;
}
if (
!shouldEstablishDirectTunnel(tunnelConfig) &&
resolvedEndpointCredentials.authMethod === "key" &&
!resolvedEndpointCredentials.sshKey
) {
const errorMessage = `Cannot connect tunnel '${tunnelName}': endpoint host requires key authentication but no plaintext key available. Enable autostart for endpoint host or configure credentials in tunnel connection.`;
tunnelLogger.error(errorMessage, undefined, {
operation: "tunnel_endpoint_key_unavailable",
tunnelName,
endpointHost: `${tunnelConfig.endpointUsername}@${tunnelConfig.endpointIP}:${tunnelConfig.endpointPort}`,
endpointAuthMethod: resolvedEndpointCredentials.authMethod,
});
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.FAILED,
reason: errorMessage,
});
tunnelConnecting.delete(tunnelName);
return;
}
const conn = new Client();
const connectionTimeout = setTimeout(() => {
if (conn) {
if (activeRetryTimers.has(tunnelName)) {
return;
}
tunnelLogger.error(
`Tunnel connection timeout after 60 seconds for '${tunnelName}'`,
undefined,
{
operation: "tunnel_connection_timeout",
tunnelName,
sourceHost: `${tunnelConfig.sourceUsername}@${tunnelConfig.sourceIP}:${tunnelConfig.sourceSSHPort}`,
endpointHost: `${tunnelConfig.endpointUsername}@${tunnelConfig.endpointIP}:${tunnelConfig.endpointPort}`,
retryAttempt,
usingSocks5: tunnelConfig.useSocks5 || false,
},
);
try {
conn.end();
} catch {
// expected
}
activeTunnels.delete(tunnelName);
if (!activeRetryTimers.has(tunnelName)) {
handleDisconnect(
tunnelName,
tunnelConfig,
!manualDisconnects.has(tunnelName),
);
}
}
}, 60000);
conn.on("error", (err) => {
clearTimeout(connectionTimeout);
const errorType = classifyTunnelError(err.message);
tunnelLogger.error(`Tunnel connection failed for '${tunnelName}'`, err, {
operation: "tunnel_connect_error",
tunnelName,
errorType,
errorMessage: err.message,
sourceHost: `${tunnelConfig.sourceUsername}@${tunnelConfig.sourceIP}:${tunnelConfig.sourceSSHPort}`,
endpointHost: `${tunnelConfig.endpointUsername}@${tunnelConfig.endpointIP}:${tunnelConfig.endpointPort}`,
tunnelType: tunnelConfig.tunnelType || "remote",
sourcePort: tunnelConfig.sourcePort,
retryAttempt,
usingSocks5: tunnelConfig.useSocks5 || false,
authMethod: tunnelConfig.sourceAuthMethod,
});
tunnelConnecting.delete(tunnelName);
if (activeRetryTimers.has(tunnelName)) {
return;
}
if (!manualDisconnects.has(tunnelName)) {
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.FAILED,
errorType: errorType,
reason: err.message,
});
}
activeTunnels.delete(tunnelName);
const shouldNotRetry =
errorType === "AUTHENTICATION_FAILED" ||
errorType === "CONNECTION_FAILED" ||
manualDisconnects.has(tunnelName);
handleDisconnect(tunnelName, tunnelConfig, !shouldNotRetry);
});
conn.on("close", () => {
clearTimeout(connectionTimeout);
tunnelConnecting.delete(tunnelName);
if (activeRetryTimers.has(tunnelName)) {
return;
}
if (!manualDisconnects.has(tunnelName)) {
const currentStatus = connectionStatus.get(tunnelName);
if (!currentStatus || currentStatus.status !== CONNECTION_STATES.FAILED) {
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.DISCONNECTED,
});
}
if (!activeRetryTimers.has(tunnelName)) {
handleDisconnect(
tunnelName,
tunnelConfig,
!manualDisconnects.has(tunnelName),
);
}
}
});
conn.on("ready", async () => {
clearTimeout(connectionTimeout);
tunnelLogger.info("Creating managed SSH tunnel", {
operation: "managed_tunnel_connection_create",
userId: tunnelConfig.sourceUserId,
hostId: tunnelConfig.sourceHostId,
tunnelName,
scope: getTunnelScope(tunnelConfig),
mode: getTunnelMode(tunnelConfig),
});
const isAlreadyVerifying = tunnelVerifications.has(tunnelName);
if (isAlreadyVerifying) {
return;
}
try {
if (getTunnelScope(tunnelConfig) !== "s2s") {
throw new Error(
"C2S tunnels must be started from the desktop client local configuration",
);
}
if (shouldEstablishDirectTunnel(tunnelConfig)) {
await establishDirectTunnel(conn, tunnelConfig);
} else {
await establishManagedS2STunnel(
conn,
tunnelConfig,
resolvedEndpointCredentials,
);
}
tunnelConnecting.delete(tunnelName);
tunnelLogger.success("Managed tunnel creation complete", {
operation: "managed_tunnel_create_complete",
userId: tunnelConfig.sourceUserId,
hostId: tunnelConfig.sourceHostId,
tunnelName,
mode: getTunnelMode(tunnelConfig),
sourcePort: tunnelConfig.sourcePort,
endpointPort: tunnelConfig.endpointPort,
});
logAudit({
userId: tunnelConfig.sourceUserId,
username: tunnelConfig.sourceUserId,
action: "tunnel_connect",
resourceType: "tunnel",
resourceId: String(tunnelConfig.sourceHostId),
resourceName: tunnelName,
details: JSON.stringify({
mode: getTunnelMode(tunnelConfig),
sourcePort: tunnelConfig.sourcePort,
}),
success: true,
});
broadcastTunnelStatus(tunnelName, {
connected: true,
status: CONNECTION_STATES.CONNECTED,
});
setupPingInterval(tunnelName);
} catch (error) {
const message =
error instanceof Error ? error.message : "Failed to create tunnel";
const errorType = classifyTunnelError(message);
tunnelLogger.error("Failed to create managed tunnel", error, {
operation: "managed_tunnel_create_failed",
tunnelName,
errorType,
retryAttempt,
});
tunnelConnecting.delete(tunnelName);
activeTunnels.delete(tunnelName);
activeTunnelRuntimes.delete(tunnelName);
try {
conn.end();
} catch {
// expected
}
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.FAILED,
errorType,
reason: message,
});
const shouldNotRetry =
errorType === "AUTHENTICATION_FAILED" ||
errorType === "CONNECTION_FAILED";
handleDisconnect(tunnelName, tunnelConfig, !shouldNotRetry);
}
});
const connOptions: Record<string, unknown> = {
host:
tunnelConfig.sourceIP?.replace(/^\[|\]$/g, "") || tunnelConfig.sourceIP,
port: tunnelConfig.sourceSSHPort,
username: tunnelConfig.sourceUsername,
tryKeyboard: true,
keepaliveInterval: tunnelConfig.keepaliveInterval ?? 30000,
keepaliveCountMax: tunnelConfig.keepaliveCountMax ?? 3,
readyTimeout: 60000,
tcpKeepAlive: true,
tcpKeepAliveInitialDelay: 30000,
env: {
TERM: "xterm-256color",
LANG: "en_US.UTF-8",
LC_ALL: "en_US.UTF-8",
LC_CTYPE: "en_US.UTF-8",
LC_MESSAGES: "en_US.UTF-8",
LC_MONETARY: "en_US.UTF-8",
LC_NUMERIC: "en_US.UTF-8",
LC_TIME: "en_US.UTF-8",
LC_COLLATE: "en_US.UTF-8",
COLORTERM: "truecolor",
},
algorithms: {
kex: [
"curve25519-sha256",
"curve25519-sha256@libssh.org",
"ecdh-sha2-nistp521",
"ecdh-sha2-nistp384",
"ecdh-sha2-nistp256",
"diffie-hellman-group-exchange-sha256",
"diffie-hellman-group14-sha256",
"diffie-hellman-group14-sha1",
"diffie-hellman-group-exchange-sha1",
"diffie-hellman-group1-sha1",
],
serverHostKey: [
"ssh-ed25519",
"ecdsa-sha2-nistp521",
"ecdsa-sha2-nistp384",
"ecdsa-sha2-nistp256",
"rsa-sha2-512",
"rsa-sha2-256",
"ssh-rsa",
"ssh-dss",
],
cipher: SSH_ALGORITHMS.cipher,
hmac: [
"hmac-sha2-512-etm@openssh.com",
"hmac-sha2-256-etm@openssh.com",
"hmac-sha2-512",
"hmac-sha2-256",
"hmac-sha1",
"hmac-md5",
],
compress: ["none", "zlib@openssh.com", "zlib"],
},
};
if (
resolvedSourceCredentials.authMethod === "key" &&
resolvedSourceCredentials.sshKey
) {
try {
connOptions.privateKey = preparePrivateKeyForSSH2(
resolvedSourceCredentials.sshKey,
resolvedSourceCredentials.keyPassword,
);
} catch (error) {
const message =
error instanceof Error ? error.message : "Invalid SSH key format";
tunnelLogger.error(
`Invalid SSH key format for tunnel '${tunnelName}': ${message}`,
undefined,
{
operation: "tunnel_invalid_ssh_key_format",
tunnelName,
sourceHost: `${tunnelConfig.sourceUsername}@${tunnelConfig.sourceIP}:${tunnelConfig.sourceSSHPort}`,
keyType: resolvedSourceCredentials.keyType,
},
);
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.FAILED,
reason: message,
});
tunnelConnecting.delete(tunnelName);
return;
}
if (resolvedSourceCredentials.keyPassword) {
connOptions.passphrase = resolvedSourceCredentials.keyPassword;
}
if (
resolvedSourceCredentials.keyType &&
resolvedSourceCredentials.keyType !== "auto"
) {
connOptions.privateKeyType = resolvedSourceCredentials.keyType;
}
} else if (resolvedSourceCredentials.authMethod === "key") {
tunnelLogger.error(
`SSH key authentication requested but no key provided for tunnel '${tunnelName}'`,
undefined,
{
operation: "tunnel_ssh_key_missing",
tunnelName,
sourceHost: `${tunnelConfig.sourceUsername}@${tunnelConfig.sourceIP}:${tunnelConfig.sourceSSHPort}`,
authMethod: resolvedSourceCredentials.authMethod,
},
);
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.FAILED,
reason: "SSH key authentication requested but no key provided",
});
tunnelConnecting.delete(tunnelName);
return;
} else {
connOptions.password = resolvedSourceCredentials.password;
}
const finalStatus = connectionStatus.get(tunnelName);
if (!finalStatus || finalStatus.status !== CONNECTION_STATES.WAITING) {
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.CONNECTING,
retryCount: retryAttempt > 0 ? retryAttempt : undefined,
});
}
if (
tunnelConfig.useSocks5 &&
(tunnelConfig.socks5Host ||
(tunnelConfig.socks5ProxyChain &&
tunnelConfig.socks5ProxyChain.length > 0))
) {
try {
const socks5Socket = await createSocks5Connection(
tunnelConfig.sourceIP,
tunnelConfig.sourceSSHPort,
{
useSocks5: tunnelConfig.useSocks5,
socks5Host: tunnelConfig.socks5Host,
socks5Port: tunnelConfig.socks5Port,
socks5Username: tunnelConfig.socks5Username,
socks5Password: tunnelConfig.socks5Password,
socks5ProxyChain: tunnelConfig.socks5ProxyChain,
},
);
if (socks5Socket) {
connOptions.sock = socks5Socket;
conn.connect(connOptions);
return;
}
} catch (socks5Error) {
tunnelLogger.error("SOCKS5 connection failed for tunnel", socks5Error, {
operation: "tunnel_socks5_connection_failed",
tunnelName,
sourceHost: `${tunnelConfig.sourceIP}:${tunnelConfig.sourceSSHPort}`,
proxyHost: tunnelConfig.socks5Host,
proxyPort: tunnelConfig.socks5Port || 1080,
hasProxyAuth: !!(
tunnelConfig.socks5Username && tunnelConfig.socks5Password
),
errorMessage:
socks5Error instanceof Error ? socks5Error.message : "Unknown error",
});
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.FAILED,
reason:
"SOCKS5 proxy connection failed: " +
(socks5Error instanceof Error
? socks5Error.message
: "Unknown error"),
});
tunnelConnecting.delete(tunnelName);
return;
}
}
conn.connect(connOptions);
}
async function killRemoteTunnelByMarker(
tunnelConfig: TunnelConfig,
tunnelName: string,
callback: (err?: Error) => void,
) {
const tunnelMarker = getTunnelMarker(tunnelName);
tunnelLogger.info("Killing remote tunnel process", {
operation: "tunnel_remote_kill",
userId: tunnelConfig.sourceUserId,
hostId: tunnelConfig.sourceHostId,
tunnelName,
marker: tunnelMarker,
});
let resolvedSourceCredentials = {
password: tunnelConfig.sourcePassword,
sshKey: tunnelConfig.sourceSSHKey,
keyPassword: tunnelConfig.sourceKeyPassword,
keyType: tunnelConfig.sourceKeyType,
authMethod: tunnelConfig.sourceAuthMethod,
};
if (
tunnelConfig.sourceHostId &&
tunnelConfig.sourceUserId &&
!tunnelConfig.sourcePassword &&
!tunnelConfig.sourceSSHKey
) {
try {
const { resolveHostById } = await import("./host-resolver.js");
const resolvedHost = await resolveHostById(
tunnelConfig.sourceHostId,
tunnelConfig.sourceUserId,
);
if (resolvedHost) {
resolvedSourceCredentials = {
password: resolvedHost.password,
sshKey: resolvedHost.key,
keyPassword: resolvedHost.keyPassword,
keyType: resolvedHost.keyType,
authMethod: resolvedHost.authType,
};
}
} catch (error) {
tunnelLogger.warn("Failed to resolve source credentials for cleanup", {
tunnelName,
sourceHostId: tunnelConfig.sourceHostId,
error: error instanceof Error ? error.message : "Unknown error",
});
}
}
if (
resolvedSourceCredentials.authMethod === "key" &&
resolvedSourceCredentials.sshKey
) {
try {
preparePrivateKeyForSSH2(
resolvedSourceCredentials.sshKey,
resolvedSourceCredentials.keyPassword,
);
} catch (error) {
callback(
error instanceof Error ? error : new Error("Invalid SSH key format"),
);
return;
}
}
const poolKey = `tunnel:${tunnelConfig.sourceUserId}:${tunnelConfig.sourceIP}:${tunnelConfig.sourceSSHPort}:${tunnelConfig.sourceUsername}`;
const factory = async (): Promise<Client> => {
const connOptions: Record<string, unknown> = {
host:
tunnelConfig.sourceIP?.replace(/^\[|\]$/g, "") || tunnelConfig.sourceIP,
port: tunnelConfig.sourceSSHPort,
username: tunnelConfig.sourceUsername,
keepaliveInterval: tunnelConfig.keepaliveInterval ?? 60000,
keepaliveCountMax: tunnelConfig.keepaliveCountMax ?? 5,
readyTimeout: 60000,
tcpKeepAlive: true,
tcpKeepAliveInitialDelay: 30000,
algorithms: {
kex: [
"diffie-hellman-group14-sha256",
"diffie-hellman-group14-sha1",
"diffie-hellman-group1-sha1",
"diffie-hellman-group-exchange-sha256",
"diffie-hellman-group-exchange-sha1",
"ecdh-sha2-nistp256",
"ecdh-sha2-nistp384",
"ecdh-sha2-nistp521",
],
cipher: [
"aes128-ctr",
"aes192-ctr",
"aes256-ctr",
"aes128-gcm@openssh.com",
"aes256-gcm@openssh.com",
"aes128-cbc",
"aes192-cbc",
"aes256-cbc",
"3des-cbc",
],
hmac: [
"hmac-sha2-256-etm@openssh.com",
"hmac-sha2-512-etm@openssh.com",
"hmac-sha2-256",
"hmac-sha2-512",
"hmac-sha1",
"hmac-md5",
],
compress: ["none", "zlib@openssh.com", "zlib"],
},
};
if (
resolvedSourceCredentials.authMethod === "key" &&
resolvedSourceCredentials.sshKey
) {
connOptions.privateKey = preparePrivateKeyForSSH2(
resolvedSourceCredentials.sshKey,
resolvedSourceCredentials.keyPassword,
);
if (resolvedSourceCredentials.keyPassword) {
connOptions.passphrase = resolvedSourceCredentials.keyPassword;
}
if (
resolvedSourceCredentials.keyType &&
resolvedSourceCredentials.keyType !== "auto"
) {
connOptions.privateKeyType = resolvedSourceCredentials.keyType;
}
} else {
connOptions.password = resolvedSourceCredentials.password;
}
if (
tunnelConfig.useSocks5 &&
(tunnelConfig.socks5Host ||
(tunnelConfig.socks5ProxyChain &&
tunnelConfig.socks5ProxyChain.length > 0))
) {
try {
const socks5Socket = await createSocks5Connection(
tunnelConfig.sourceIP,
tunnelConfig.sourceSSHPort,
{
useSocks5: tunnelConfig.useSocks5,
socks5Host: tunnelConfig.socks5Host,
socks5Port: tunnelConfig.socks5Port,
socks5Username: tunnelConfig.socks5Username,
socks5Password: tunnelConfig.socks5Password,
socks5ProxyChain: tunnelConfig.socks5ProxyChain,
},
);
if (socks5Socket) {
connOptions.sock = socks5Socket;
} else {
throw new Error("Failed to create SOCKS5 connection");
}
} catch (socks5Error) {
tunnelLogger.error(
"SOCKS5 connection failed for killing tunnel",
socks5Error,
{
operation: "socks5_connect_kill",
tunnelName,
proxyHost: tunnelConfig.socks5Host,
proxyPort: tunnelConfig.socks5Port || 1080,
},
);
throw new Error(
"SOCKS5 proxy connection failed: " +
(socks5Error instanceof Error
? socks5Error.message
: "Unknown error"),
{ cause: socks5Error },
);
}
}
return new Promise<Client>((resolve, reject) => {
const conn = new Client();
conn.on("ready", () => resolve(conn));
conn.on("error", (err) => reject(err));
conn.connect(connOptions);
});
};
const execCommand = (client: Client, cmd: string): Promise<string> =>
new Promise((resolve, reject) => {
client.exec(cmd, (err, stream) => {
if (err) {
reject(err);
return;
}
let output = "";
stream.on("data", (data: Buffer) => {
output += data.toString();
});
stream.stderr.on("data", (data: Buffer) => {
const stderr = data.toString().trim();
if (stderr && !stderr.includes("debug1")) {
tunnelLogger.warn(
`Kill command stderr for '${tunnelName}': ${stderr}`,
);
}
});
stream.on("close", () => resolve(output.trim()));
});
});
try {
await withConnection(poolKey, factory, async (client) => {
const checkCmd = `ps aux | grep -F '${tunnelMarker}' | grep -v grep`;
const checkOutput = await execCommand(client, checkCmd);
if (!checkOutput) {
tunnelLogger.warn("Remote tunnel process not found", {
operation: "tunnel_remote_not_found",
userId: tunnelConfig.sourceUserId,
hostId: tunnelConfig.sourceHostId,
tunnelName,
marker: tunnelMarker,
});
return;
}
tunnelLogger.info("Remote tunnel process found, proceeding to kill", {
operation: "tunnel_remote_found",
userId: tunnelConfig.sourceUserId,
hostId: tunnelConfig.sourceHostId,
tunnelName,
marker: tunnelMarker,
});
const killCmds = [
`pkill -TERM -f '${tunnelMarker}'`,
`sleep 2 && pkill -9 -f '${tunnelMarker}'`,
];
for (const killCmd of killCmds) {
try {
await execCommand(client, killCmd);
} catch (err) {
tunnelLogger.warn(
`Kill command failed for '${tunnelName}': ${(err as Error).message}`,
);
}
}
const verifyOutput = await execCommand(client, checkCmd);
if (verifyOutput) {
tunnelLogger.warn(
`Some tunnel processes may still be running for '${tunnelName}'`,
);
} else {
tunnelLogger.success("Remote tunnel process killed", {
operation: "tunnel_remote_killed",
userId: tunnelConfig.sourceUserId,
hostId: tunnelConfig.sourceHostId,
tunnelName,
});
}
});
callback();
} catch (err) {
tunnelLogger.error(
`Failed to connect to source host for killing tunnel '${tunnelName}': ${(err as Error).message}`,
);
callback(err as Error);
}
}
/**
* @openapi
* /ssh/tunnel/status:
* get:
* summary: Get all tunnel statuses
* description: Retrieves the status of all SSH tunnels.
* tags:
* - SSH Tunnels
* responses:
* 200:
* description: A list of all tunnel statuses.
*/
app.get(
"/ssh/tunnel/status",
authenticateJWT,
(req: AuthenticatedRequest, res: Response) => {
if (!req.userId) {
return res.status(401).json({ error: "Authentication required" });
}
res.json(getAllTunnelStatus());
},
);
app.get(
"/ssh/tunnel/status/stream",
authenticateJWT,
(req: AuthenticatedRequest, res: Response) => {
if (!req.userId) {
return res.status(401).json({ error: "Authentication required" });
}
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-store, no-transform",
Connection: "keep-alive",
"X-Accel-Buffering": "no",
});
res.flushHeaders?.();
tunnelStatusClients.add(res);
sendTunnelStatusSnapshot(res);
const heartbeat = setInterval(() => {
try {
res.write(": keepalive\n\n");
} catch {
closeStream();
}
}, 30000);
const closeStream = () => {
clearInterval(heartbeat);
tunnelStatusClients.delete(res);
};
req.on("close", closeStream);
},
);
/**
* @openapi
* /ssh/tunnel/status/{tunnelName}:
* get:
* summary: Get tunnel status by name
* description: Retrieves the status of a specific SSH tunnel by its name.
* tags:
* - SSH Tunnels
* parameters:
* - in: path
* name: tunnelName
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Tunnel status.
* 404:
* description: Tunnel not found.
*/
app.get(
"/ssh/tunnel/status/:tunnelName",
authenticateJWT,
(req: AuthenticatedRequest, res: Response) => {
if (!req.userId) {
return res.status(401).json({ error: "Authentication required" });
}
const tunnelNameParam = req.params.tunnelName;
const tunnelName = Array.isArray(tunnelNameParam)
? tunnelNameParam[0]
: tunnelNameParam;
const status = connectionStatus.get(tunnelName);
if (!status) {
return res.status(404).json({ error: "Tunnel not found" });
}
res.json({ name: tunnelName, status });
},
);
/**
* @openapi
* /ssh/tunnel/connect:
* post:
* summary: Connect SSH tunnel
* description: Establishes an SSH tunnel connection with the specified configuration.
* tags:
* - SSH Tunnels
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* name:
* type: string
* sourceHostId:
* type: integer
* tunnelIndex:
* type: integer
* responses:
* 200:
* description: Connection request received.
* 400:
* description: Invalid tunnel configuration.
* 401:
* description: Authentication required.
* 403:
* description: Access denied to this host.
* 500:
* description: Failed to connect tunnel.
*/
app.post(
"/ssh/tunnel/connect",
authenticateJWT,
async (req: AuthenticatedRequest, res: Response) => {
const tunnelConfig: TunnelConfig = req.body;
const userId = req.userId;
if (!userId) {
return res.status(401).json({ error: "Authentication required" });
}
if (!tunnelConfig || !tunnelConfig.name) {
return res.status(400).json({ error: "Invalid tunnel configuration" });
}
const tunnelName = tunnelConfig.name;
try {
if (!validateTunnelConfig(tunnelName, tunnelConfig)) {
tunnelLogger.error(`Tunnel config validation failed`, {
operation: "tunnel_connect",
tunnelName,
configHostId: tunnelConfig.sourceHostId,
configTunnelIndex: tunnelConfig.tunnelIndex,
});
return res.status(400).json({
error: "Tunnel configuration does not match tunnel name",
});
}
if (tunnelConfig.sourceHostId) {
const accessInfo = await permissionManager.canAccessHost(
userId,
tunnelConfig.sourceHostId,
"read",
);
if (!accessInfo.hasAccess) {
tunnelLogger.warn("User attempted tunnel connect without access", {
operation: "tunnel_connect_unauthorized",
userId,
hostId: tunnelConfig.sourceHostId,
tunnelName,
});
return res.status(403).json({ error: "Access denied to this host" });
}
if (accessInfo.isShared && !accessInfo.isOwner) {
tunnelConfig.requestingUserId = userId;
}
}
if (pendingTunnelOperations.has(tunnelName)) {
try {
await pendingTunnelOperations.get(tunnelName);
} catch {
tunnelLogger.warn(`Previous tunnel operation failed`, { tunnelName });
}
}
const operation = (async () => {
manualDisconnects.delete(tunnelName);
retryCounters.delete(tunnelName);
retryExhaustedTunnels.delete(tunnelName);
await cleanupTunnelResources(tunnelName);
if (tunnelConfigs.has(tunnelName)) {
const existingConfig = tunnelConfigs.get(tunnelName);
if (
existingConfig &&
(existingConfig.sourceHostId !== tunnelConfig.sourceHostId ||
existingConfig.tunnelIndex !== tunnelConfig.tunnelIndex)
) {
throw new Error(`Tunnel name collision detected: ${tunnelName}`);
}
}
if (
!isSingleHostTunnel(tunnelConfig) &&
(!tunnelConfig.endpointIP || !tunnelConfig.endpointUsername)
) {
try {
const systemCrypto = SystemCrypto.getInstance();
const internalAuthToken = await systemCrypto.getInternalAuthToken();
const allHostsResponse = await axios.get(
"http://localhost:30001/host/db/host/internal/all",
{
headers: {
"Content-Type": "application/json",
"X-Internal-Auth-Token": internalAuthToken,
},
},
);
const allHosts: SSHHost[] = allHostsResponse.data || [];
const endpointHost = findHostByTunnelEndpoint(
allHosts,
tunnelConfig.endpointHost,
);
if (!endpointHost) {
if (getTunnelMode(tunnelConfig) !== "remote") {
tunnelConfig.endpointIP =
tunnelConfig.endpointIP || tunnelConfig.endpointHost;
} else {
throw new Error(
`Endpoint host '${tunnelConfig.endpointHost}' not found in database`,
);
}
} else {
tunnelConfig.endpointIP = endpointHost.ip;
tunnelConfig.endpointSSHPort = endpointHost.port;
tunnelConfig.endpointUsername = endpointHost.username;
tunnelConfig.endpointAuthMethod = endpointHost.authType;
tunnelConfig.endpointKeyType = endpointHost.keyType;
tunnelConfig.endpointCredentialId = endpointHost.credentialId;
tunnelConfig.endpointUserId = endpointHost.userId;
// Resolve credentials server-side instead of from HTTP response
if (endpointHost.id && endpointHost.userId) {
try {
const { resolveHostById } =
await import("./host-resolver.js");
const resolved = await resolveHostById(
endpointHost.id,
endpointHost.userId,
);
if (resolved) {
tunnelConfig.endpointPassword = resolved.password;
tunnelConfig.endpointSSHKey = resolved.key;
tunnelConfig.endpointKeyPassword = resolved.keyPassword;
}
} catch (credError) {
tunnelLogger.warn(
"Failed to resolve endpoint credentials from DB",
{
operation: "tunnel_endpoint_credential_resolve",
endpointHostId: endpointHost.id,
error:
credError instanceof Error
? credError.message
: "Unknown",
},
);
}
}
}
} catch (resolveError) {
tunnelLogger.error(
"Failed to resolve endpoint host",
resolveError,
{
operation: "tunnel_connect_resolve_endpoint_failed",
tunnelName,
endpointHost: tunnelConfig.endpointHost,
},
);
throw new Error(
`Failed to resolve endpoint host: ${resolveError instanceof Error ? resolveError.message : "Unknown error"}`,
{ cause: resolveError },
);
}
}
tunnelConfigs.set(tunnelName, tunnelConfig);
await connectSSHTunnel(tunnelConfig, 0);
})();
pendingTunnelOperations.set(tunnelName, operation);
res.json({ message: "Connection request received", tunnelName });
operation
.catch((err) => {
tunnelLogger.error("Tunnel operation failed", err, {
operation: "tunnel_operation_failed",
tunnelName,
});
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.FAILED,
reason: err instanceof Error ? err.message : "Unknown error",
});
tunnelConnecting.delete(tunnelName);
})
.finally(() => {
pendingTunnelOperations.delete(tunnelName);
});
} catch (error) {
tunnelLogger.error("Failed to process tunnel connect", error, {
operation: "tunnel_connect",
tunnelName,
userId,
});
res.status(500).json({ error: "Failed to connect tunnel" });
}
},
);
/**
* @openapi
* /ssh/tunnel/disconnect:
* post:
* summary: Disconnect SSH tunnel
* description: Disconnects an active SSH tunnel.
* tags:
* - SSH Tunnels
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* tunnelName:
* type: string
* responses:
* 200:
* description: Disconnect request received.
* 400:
* description: Tunnel name required.
* 401:
* description: Authentication required.
* 403:
* description: Access denied.
* 500:
* description: Failed to disconnect tunnel.
*/
app.post(
"/ssh/tunnel/disconnect",
authenticateJWT,
async (req: AuthenticatedRequest, res: Response) => {
const { tunnelName } = req.body;
const userId = req.userId;
if (!userId) {
return res.status(401).json({ error: "Authentication required" });
}
if (!tunnelName) {
return res.status(400).json({ error: "Tunnel name required" });
}
try {
const config = tunnelConfigs.get(tunnelName);
if (config && config.sourceHostId) {
const accessInfo = await permissionManager.canAccessHost(
userId,
config.sourceHostId,
"read",
);
if (!accessInfo.hasAccess) {
return res.status(403).json({ error: "Access denied" });
}
}
tunnelLogger.info("Tunnel stop request received", {
operation: "tunnel_stop_request",
userId,
hostId: config?.sourceHostId,
tunnelName,
});
manualDisconnects.add(tunnelName);
retryCounters.delete(tunnelName);
retryExhaustedTunnels.delete(tunnelName);
if (activeRetryTimers.has(tunnelName)) {
clearTimeout(activeRetryTimers.get(tunnelName)!);
activeRetryTimers.delete(tunnelName);
}
await cleanupTunnelResources(tunnelName, true);
tunnelLogger.info("Tunnel cleanup completed", {
operation: "tunnel_cleanup_complete",
userId,
hostId: config?.sourceHostId,
tunnelName,
});
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.DISCONNECTED,
manualDisconnect: true,
});
const tunnelConfig = tunnelConfigs.get(tunnelName) || null;
handleDisconnect(tunnelName, tunnelConfig, false);
setTimeout(() => {
manualDisconnects.delete(tunnelName);
}, 5000);
res.json({ message: "Disconnect request received", tunnelName });
} catch (error) {
tunnelLogger.error("Failed to disconnect tunnel", error, {
operation: "tunnel_disconnect",
tunnelName,
userId,
});
res.status(500).json({ error: "Failed to disconnect tunnel" });
}
},
);
/**
* @openapi
* /ssh/tunnel/cancel:
* post:
* summary: Cancel tunnel retry
* description: Cancels the retry mechanism for a failed SSH tunnel connection.
* tags:
* - SSH Tunnels
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* tunnelName:
* type: string
* responses:
* 200:
* description: Cancel request received.
* 400:
* description: Tunnel name required.
* 401:
* description: Authentication required.
* 403:
* description: Access denied.
* 500:
* description: Failed to cancel tunnel retry.
*/
app.post(
"/ssh/tunnel/cancel",
authenticateJWT,
async (req: AuthenticatedRequest, res: Response) => {
const { tunnelName } = req.body;
const userId = req.userId;
if (!userId) {
return res.status(401).json({ error: "Authentication required" });
}
if (!tunnelName) {
return res.status(400).json({ error: "Tunnel name required" });
}
try {
const config = tunnelConfigs.get(tunnelName);
if (config && config.sourceHostId) {
const accessInfo = await permissionManager.canAccessHost(
userId,
config.sourceHostId,
"read",
);
if (!accessInfo.hasAccess) {
return res.status(403).json({ error: "Access denied" });
}
}
retryCounters.delete(tunnelName);
retryExhaustedTunnels.delete(tunnelName);
if (activeRetryTimers.has(tunnelName)) {
clearTimeout(activeRetryTimers.get(tunnelName)!);
activeRetryTimers.delete(tunnelName);
}
if (countdownIntervals.has(tunnelName)) {
clearInterval(countdownIntervals.get(tunnelName)!);
countdownIntervals.delete(tunnelName);
}
await cleanupTunnelResources(tunnelName, true);
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.DISCONNECTED,
manualDisconnect: true,
});
const tunnelConfig = tunnelConfigs.get(tunnelName) || null;
handleDisconnect(tunnelName, tunnelConfig, false);
setTimeout(() => {
manualDisconnects.delete(tunnelName);
}, 5000);
res.json({ message: "Cancel request received", tunnelName });
} catch (error) {
tunnelLogger.error("Failed to cancel tunnel retry", error, {
operation: "tunnel_cancel",
tunnelName,
userId,
});
res.status(500).json({ error: "Failed to cancel tunnel retry" });
}
},
);
async function initializeAutoStartTunnels(): Promise<void> {
try {
const systemCrypto = SystemCrypto.getInstance();
const internalAuthToken = await systemCrypto.getInternalAuthToken();
const autostartHosts = await fetchInternalHosts(
"internal",
internalAuthToken,
);
const allHosts = await fetchInternalHosts(
"internal/all",
internalAuthToken,
);
const autoStartTunnels: TunnelConfig[] = [];
tunnelLogger.info(
`Found ${autostartHosts.length} autostart hosts and ${allHosts.length} total hosts for endpointHost resolution`,
);
for (const host of autostartHosts) {
if (host.enableTunnel && host.tunnelConnections) {
for (const tunnelConnection of host.tunnelConnections) {
if (tunnelConnection.autoStart) {
const endpointHost = findHostByTunnelEndpoint(
allHosts,
tunnelConnection.endpointHost,
);
const mode =
tunnelConnection.mode || tunnelConnection.tunnelType || "remote";
const allowDirectTarget = mode !== "remote";
if (endpointHost || allowDirectTarget) {
const tunnelIndex =
host.tunnelConnections.indexOf(tunnelConnection);
const tunnelConfig: TunnelConfig = {
name: normalizeTunnelName(
host.id,
tunnelIndex,
host.name || `${host.username}@${host.ip}`,
tunnelConnection.sourcePort,
tunnelConnection.endpointHost,
tunnelConnection.endpointPort,
),
scope: tunnelConnection.scope || "s2s",
mode,
bindHost: tunnelConnection.bindHost,
targetHost: tunnelConnection.targetHost,
tunnelType: tunnelConnection.tunnelType || "remote",
sourceHostId: host.id,
tunnelIndex: tunnelIndex,
hostName: host.name || `${host.username}@${host.ip}`,
sourceIP: host.ip,
sourceSSHPort: host.port,
sourceUsername: host.username,
sourceAuthMethod: host.authType,
sourceKeyType: host.keyType,
sourceCredentialId: host.credentialId,
sourceUserId: host.userId,
endpointIP: endpointHost?.ip || tunnelConnection.endpointHost,
endpointSSHPort: endpointHost?.port || 22,
endpointUsername: endpointHost?.username || "",
endpointHost: tunnelConnection.endpointHost,
endpointAuthMethod:
tunnelConnection.endpointAuthType ||
endpointHost?.authType ||
"none",
endpointKeyType:
tunnelConnection.endpointKeyType || endpointHost?.keyType,
endpointCredentialId: endpointHost?.credentialId,
endpointUserId: endpointHost?.userId,
sourcePort: tunnelConnection.sourcePort,
endpointPort: tunnelConnection.endpointPort,
maxRetries: tunnelConnection.maxRetries,
retryInterval: tunnelConnection.retryInterval * 1000,
autoStart: tunnelConnection.autoStart,
isPinned: host.pin,
useSocks5: host.useSocks5,
socks5Host: host.socks5Host,
socks5Port: host.socks5Port,
socks5Username: host.socks5Username,
socks5Password: host.socks5Password,
};
autoStartTunnels.push(tunnelConfig);
} else {
tunnelLogger.error(
`Failed to find endpointHost '${tunnelConnection.endpointHost}' for tunnel from ${host.name || `${host.username}@${host.ip}`}. Available hosts: ${allHosts.map((h) => h.name || `${h.username}@${h.ip}`).join(", ")}`,
);
}
}
}
}
}
for (const tunnelConfig of autoStartTunnels) {
tunnelConfigs.set(tunnelConfig.name, tunnelConfig);
setTimeout(() => {
connectSSHTunnel(tunnelConfig, 0).catch((error) => {
tunnelLogger.error(
`Failed to connect tunnel ${tunnelConfig.name}: ${error instanceof Error ? error.message : "Unknown error"}`,
);
});
}, 1000);
}
} catch (error) {
tunnelLogger.error(
"Failed to initialize auto-start tunnels:",
error instanceof Error ? error.message : "Unknown error",
);
}
}
const PORT = 30003;
const server = createServer(app);
const c2sRelayWss = new WebSocketServer({
server,
path: "/ssh/tunnel/c2s/stream",
});
c2sRelayWss.on("connection", (ws, req) => {
let opened = false;
ws.once("message", async (raw) => {
try {
const token = extractRequestToken(req);
const payload = token ? await authManager.verifyJWTToken(token) : null;
if (!payload?.userId || payload.pendingTOTP) {
sendC2SError(ws, "Authentication required");
ws.close();
return;
}
const message = JSON.parse(raw.toString()) as C2SOpenMessage;
if (message.type !== "open" && message.type !== "test") {
throw new Error("Invalid client tunnel relay request");
}
opened = true;
if (message.type === "test") {
await handleC2SRelayTest(ws, message, payload.userId);
} else {
await handleC2SRelayOpen(ws, message, payload.userId);
}
} catch (error) {
const message = describeC2SRelayError(error);
tunnelLogger.error("Failed to open C2S relay", error, {
operation: "c2s_relay_open_failed",
});
sendC2SError(ws, message);
ws.close();
}
});
ws.on("close", () => {
if (!opened) {
tunnelLogger.info("C2S relay closed before opening", {
operation: "c2s_relay_closed_before_open",
});
}
});
});
server.listen(PORT, () => {
setTimeout(() => {
initializeAutoStartTunnels();
}, 2000);
});