release-2.4.1 (#921)

* chore(deps-dev): bump the dev-minor-updates group across 1 directory with 12 updates (#910)

Bumps the dev-minor-updates group with 12 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [@radix-ui/react-select](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/select) | `2.2.6` | `2.3.1` |
| [@radix-ui/react-slider](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/slider) | `1.3.6` | `1.4.1` |
| [@radix-ui/react-slot](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/slot) | `1.2.5` | `1.3.0` |
| [@radix-ui/react-switch](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/switch) | `1.2.6` | `1.3.1` |
| [cytoscape](https://github.com/cytoscape/cytoscape.js) | `3.33.4` | `3.34.0` |
| [electron](https://github.com/electron/electron) | `42.2.0` | `42.4.1` |
| [electron-builder](https://github.com/electron-userland/electron-builder/tree/HEAD/packages/electron-builder) | `26.8.1` | `26.15.3` |
| [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) | `1.16.0` | `1.20.0` |
| [radix-ui](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/radix-ui) | `1.4.3` | `1.6.0` |
| [react-hook-form](https://github.com/react-hook-form/react-hook-form) | `7.76.1` | `7.79.0` |
| [sharp](https://github.com/lovell/sharp) | `0.34.5` | `0.35.1` |
| [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.60.0` | `8.61.1` |



Updates `@radix-ui/react-select` from 2.2.6 to 2.3.1
- [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/select/CHANGELOG.md)
- [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/select)

Updates `@radix-ui/react-slider` from 1.3.6 to 1.4.1
- [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/slider/CHANGELOG.md)
- [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/slider)

Updates `@radix-ui/react-slot` from 1.2.5 to 1.3.0
- [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/slot/CHANGELOG.md)
- [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/slot)

Updates `@radix-ui/react-switch` from 1.2.6 to 1.3.1
- [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/switch/CHANGELOG.md)
- [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/switch)

Updates `cytoscape` from 3.33.4 to 3.34.0
- [Release notes](https://github.com/cytoscape/cytoscape.js/releases)
- [Commits](https://github.com/cytoscape/cytoscape.js/compare/v3.33.4...v3.34.0)

Updates `electron` from 42.2.0 to 42.4.1
- [Release notes](https://github.com/electron/electron/releases)
- [Commits](https://github.com/electron/electron/compare/v42.2.0...v42.4.1)

Updates `electron-builder` from 26.8.1 to 26.15.3
- [Release notes](https://github.com/electron-userland/electron-builder/releases)
- [Changelog](https://github.com/electron-userland/electron-builder/blob/master/packages/electron-builder/CHANGELOG.md)
- [Commits](https://github.com/electron-userland/electron-builder/commits/electron-builder@26.15.3/packages/electron-builder)

Updates `lucide-react` from 1.16.0 to 1.20.0
- [Release notes](https://github.com/lucide-icons/lucide/releases)
- [Commits](https://github.com/lucide-icons/lucide/commits/1.20.0/packages/lucide-react)

Updates `radix-ui` from 1.4.3 to 1.6.0
- [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/radix-ui/CHANGELOG.md)
- [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/radix-ui)

Updates `react-hook-form` from 7.76.1 to 7.79.0
- [Release notes](https://github.com/react-hook-form/react-hook-form/releases)
- [Changelog](https://github.com/react-hook-form/react-hook-form/blob/master/CHANGELOG.md)
- [Commits](https://github.com/react-hook-form/react-hook-form/compare/v7.76.1...v7.79.0)

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

Updates `typescript-eslint` from 8.60.0 to 8.61.1
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.61.1/packages/typescript-eslint)

---
updated-dependencies:
- dependency-name: "@radix-ui/react-select"
  dependency-version: 2.3.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: "@radix-ui/react-slider"
  dependency-version: 1.4.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: "@radix-ui/react-slot"
  dependency-version: 1.3.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: "@radix-ui/react-switch"
  dependency-version: 1.3.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: cytoscape
  dependency-version: 3.34.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: electron
  dependency-version: 42.4.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: electron-builder
  dependency-version: 26.15.3
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: lucide-react
  dependency-version: 1.18.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: radix-ui
  dependency-version: 1.6.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: react-hook-form
  dependency-version: 7.79.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: sharp
  dependency-version: 0.35.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: typescript-eslint
  dependency-version: 8.61.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
...

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

* chore(deps): bump node in /docker in the docker-major-updates group (#914)

Bumps the docker-major-updates group in /docker with 1 update: node.


Updates `node` from 24-slim to 26-slim

---
updated-dependencies:
- dependency-name: node
  dependency-version: 26-slim
  dependency-type: direct:production
  dependency-group: docker-major-updates
...

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

* ci(deps): bump the github-actions group with 2 updates (#915)

Bumps the github-actions group with 2 updates: [actions/checkout](https://github.com/actions/checkout) and [actions/setup-node](https://github.com/actions/setup-node).


Updates `actions/checkout` from 5 to 6
- [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/v5...v6)

Updates `actions/setup-node` from 4 to 6
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v4...v6)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
- dependency-name: actions/setup-node
  dependency-version: '6'
  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): bump the prod-minor-updates group across 1 directory with 5 updates (#916)

Bumps the prod-minor-updates group with 5 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [axios](https://github.com/axios/axios) | `1.17.0` | `1.18.0` |
| [better-sqlite3](https://github.com/WiseLibs/better-sqlite3) | `12.10.0` | `12.11.1` |
| [body-parser](https://github.com/expressjs/body-parser) | `2.2.2` | `2.3.0` |
| [multer](https://github.com/expressjs/multer) | `2.1.1` | `2.2.0` |
| [undici](https://github.com/nodejs/undici) | `8.4.0` | `8.5.0` |



Updates `axios` from 1.17.0 to 1.18.0
- [Release notes](https://github.com/axios/axios/releases)
- [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
- [Commits](https://github.com/axios/axios/compare/v1.17.0...v1.18.0)

Updates `better-sqlite3` from 12.10.0 to 12.11.1
- [Release notes](https://github.com/WiseLibs/better-sqlite3/releases)
- [Commits](https://github.com/WiseLibs/better-sqlite3/compare/v12.10.0...v12.11.1)

Updates `body-parser` from 2.2.2 to 2.3.0
- [Release notes](https://github.com/expressjs/body-parser/releases)
- [Changelog](https://github.com/expressjs/body-parser/blob/master/HISTORY.md)
- [Commits](https://github.com/expressjs/body-parser/compare/v2.2.2...v2.3.0)

Updates `multer` from 2.1.1 to 2.2.0
- [Release notes](https://github.com/expressjs/multer/releases)
- [Changelog](https://github.com/expressjs/multer/blob/main/CHANGELOG.md)
- [Commits](https://github.com/expressjs/multer/compare/v2.1.1...v2.2.0)

Updates `undici` from 8.4.0 to 8.5.0
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v8.4.0...v8.5.0)

---
updated-dependencies:
- dependency-name: axios
  dependency-version: 1.18.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: prod-minor-updates
- dependency-name: better-sqlite3
  dependency-version: 12.11.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: prod-minor-updates
- dependency-name: body-parser
  dependency-version: 2.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: prod-minor-updates
- dependency-name: multer
  dependency-version: 2.2.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: prod-minor-updates
- dependency-name: undici
  dependency-version: 8.5.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: prod-minor-updates
...

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

* feat: add unlink button for dual auth

* fix: general bug fixes

* fix: general qol/small feature additions

* fix: 100mb max upload size

* fix: terminal syntax not handling carriage returns or shell prompt lines properly

* feat: continued general improvements

* fix: terminal outputting success right after folder path

* chore: update release notes

* feat: continued fixes and improvements

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

* chore: sync Crowdin translations for 2.4.1

* fix: rebase dev branch onto main before Crowdin download

* fix: use merge instead of rebase to sync main before Crowdin

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
This commit is contained in:
Luke Gustafson
2026-06-21 15:55:41 -05:00
committed by GitHub
parent 8072b4ede9
commit d1a8dcf3c6
165 changed files with 87244 additions and 60766 deletions
+30 -3
View File
@@ -2,12 +2,18 @@ import express from "express";
import cookieParser from "cookie-parser";
import { createCorsMiddleware } from "./utils/cors-config.js";
import { getDb } from "./database/db/index.js";
import { recentActivity, hosts, hostAccess } from "./database/db/schema.js";
import { eq, and, desc, inArray } from "drizzle-orm";
import {
recentActivity,
hosts,
hostAccess,
userRoles,
} from "./database/db/schema.js";
import { eq, and, desc, inArray, or, isNull, gte, sql } from "drizzle-orm";
import { dashboardLogger } from "./utils/logger.js";
import { SimpleDBOps } from "./utils/simple-db-ops.js";
import { AuthManager } from "./utils/auth-manager.js";
import type { AuthenticatedRequest } from "../types/index.js";
import { dashboardServiceLinksRouter } from "./database/routes/dashboard-service-links-routes.js";
const app = express();
const authManager = AuthManager.getInstance();
@@ -227,11 +233,30 @@ app.post("/activity/log", async (req, res) => {
);
if (ownedHosts.length === 0) {
const userRoleIds = await getDb()
.select({ roleId: userRoles.roleId })
.from(userRoles)
.where(eq(userRoles.userId, userId));
const roleIds = userRoleIds.map((r) => r.roleId);
const now = new Date().toISOString();
const sharedHosts = await getDb()
.select()
.from(hostAccess)
.where(
and(eq(hostAccess.hostId, hostId), eq(hostAccess.userId, userId)),
and(
eq(hostAccess.hostId, hostId),
or(
eq(hostAccess.userId, userId),
roleIds.length > 0
? sql`${hostAccess.roleId} IN (${sql.join(
roleIds.map((id) => sql`${id}`),
sql`, `,
)})`
: sql`false`,
),
or(isNull(hostAccess.expiresAt), gte(hostAccess.expiresAt, now)),
),
);
if (sharedHosts.length === 0) {
@@ -349,6 +374,8 @@ app.delete("/activity/reset", async (req, res) => {
}
});
app.use("/service-links", dashboardServiceLinksRouter);
const PORT = 30006;
app.listen(PORT, async () => {
try {
+5 -1
View File
@@ -1832,7 +1832,11 @@ if (frontendDist) {
);
app.use((req, res, next) => {
if (req.method === "GET" && req.accepts("html")) {
if (
req.method === "GET" &&
req.accepts("html") &&
!req.headers.authorization
) {
res.setHeader(
"Cache-Control",
"no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0",
+31
View File
@@ -694,6 +694,7 @@ const migrateSchema = () => {
addColumnIfNotExists("user_preferences", "disable_update_check", "INTEGER");
addColumnIfNotExists("user_preferences", "confirm_tab_close", "INTEGER");
addColumnIfNotExists("user_preferences", "hidden_rail_tabs", "TEXT");
addColumnIfNotExists("user_preferences", "compact_host_view", "INTEGER");
addColumnIfNotExists("users", "is_admin", "INTEGER NOT NULL DEFAULT 0");
@@ -753,6 +754,11 @@ const migrateSchema = () => {
"enable_file_manager",
"INTEGER NOT NULL DEFAULT 1",
);
addColumnIfNotExists(
"ssh_data",
"scp_legacy",
"INTEGER NOT NULL DEFAULT 0",
);
addColumnIfNotExists("ssh_data", "default_path", "TEXT");
addColumnIfNotExists(
"ssh_data",
@@ -1197,6 +1203,14 @@ const migrateSchema = () => {
{ column: "vnc_user", sql: "ALTER TABLE ssh_data ADD COLUMN vnc_user TEXT" },
{ column: "telnet_user", sql: "ALTER TABLE ssh_data ADD COLUMN telnet_user TEXT" },
{ column: "telnet_password", sql: "ALTER TABLE ssh_data ADD COLUMN telnet_password TEXT" },
{ column: "rdp_credential_id", sql: "ALTER TABLE ssh_data ADD COLUMN rdp_credential_id INTEGER REFERENCES ssh_credentials(id) ON DELETE SET NULL" },
{ column: "vnc_credential_id", sql: "ALTER TABLE ssh_data ADD COLUMN vnc_credential_id INTEGER REFERENCES ssh_credentials(id) ON DELETE SET NULL" },
{ column: "wol_broadcast_address", sql: "ALTER TABLE ssh_data ADD COLUMN wol_broadcast_address TEXT" },
{ column: "use_warpgate", sql: "ALTER TABLE ssh_data ADD COLUMN use_warpgate INTEGER NOT NULL DEFAULT 0" },
{ column: "telnet_credential_id", sql: "ALTER TABLE ssh_data ADD COLUMN telnet_credential_id INTEGER REFERENCES ssh_credentials(id) ON DELETE SET NULL" },
{ column: "rdp_auth_type", sql: "ALTER TABLE ssh_data ADD COLUMN rdp_auth_type TEXT" },
{ column: "vnc_auth_type", sql: "ALTER TABLE ssh_data ADD COLUMN vnc_auth_type TEXT" },
{ column: "telnet_auth_type", sql: "ALTER TABLE ssh_data ADD COLUMN telnet_auth_type TEXT" },
];
for (const migration of sshDataMigrations) {
@@ -1214,6 +1228,23 @@ const migrateSchema = () => {
}
}
// Migrate legacy authType="warpgate" hosts to useWarpgate=1 with authType="none"
try {
const result = sqlite
.prepare("UPDATE ssh_data SET use_warpgate = 1, auth_type = 'none' WHERE auth_type = 'warpgate'")
.run();
if (result.changes > 0) {
databaseLogger.info(`Migrated ${result.changes} host(s) from authType='warpgate' to useWarpgate=true`, {
operation: "warpgate_auth_migration",
});
}
} catch (e) {
databaseLogger.warn("Failed to migrate legacy warpgate authType hosts", {
operation: "warpgate_auth_migration",
error: e,
});
}
// Copy unencrypted username/domain into protocol-specific columns for old guac hosts.
// Passwords are handled via the legacy field name fallback in lazy-field-encryption.ts.
const usernameDomainBackfills = [
+25
View File
@@ -94,6 +94,7 @@ export const hosts = sqliteTable("ssh_data", {
tags: text("tags"),
pin: integer("pin", { mode: "boolean" }).notNull().default(false),
authType: text("auth_type").notNull(),
useWarpgate: integer("use_warpgate", { mode: "boolean" }).notNull().default(false),
forceKeyboardInteractive: text("force_keyboard_interactive"),
password: text("password"),
@@ -127,6 +128,7 @@ export const hosts = sqliteTable("ssh_data", {
enableFileManager: integer("enable_file_manager", { mode: "boolean" })
.notNull()
.default(true),
scpLegacy: integer("scp_legacy", { mode: "boolean" }).notNull().default(false),
enableDocker: integer("enable_docker", { mode: "boolean" })
.notNull()
.default(false),
@@ -168,17 +170,24 @@ export const hosts = sqliteTable("ssh_data", {
vncPort: integer("vnc_port").default(5900),
telnetPort: integer("telnet_port").default(23),
rdpCredentialId: integer("rdp_credential_id").references(() => sshCredentials.id, { onDelete: "set null" }),
rdpUser: text("rdp_user"),
rdpPassword: text("rdp_password"),
rdpDomain: text("rdp_domain"),
rdpSecurity: text("rdp_security"),
rdpIgnoreCert: integer("rdp_ignore_cert", { mode: "boolean" }).default(false),
vncCredentialId: integer("vnc_credential_id").references(() => sshCredentials.id, { onDelete: "set null" }),
vncPassword: text("vnc_password"),
vncUser: text("vnc_user"),
telnetUser: text("telnet_user"),
telnetPassword: text("telnet_password"),
telnetCredentialId: integer("telnet_credential_id").references(() => sshCredentials.id, { onDelete: "set null" }),
rdpAuthType: text("rdp_auth_type"),
vncAuthType: text("vnc_auth_type"),
telnetAuthType: text("telnet_auth_type"),
domain: text("domain"),
security: text("security"),
@@ -193,6 +202,7 @@ export const hosts = sqliteTable("ssh_data", {
socks5ProxyChain: text("socks5_proxy_chain"),
macAddress: text("mac_address"),
wolBroadcastAddress: text("wol_broadcast_address"),
portKnockSequence: text("port_knock_sequence"),
hostKeyFingerprint: text("host_key_fingerprint"),
@@ -705,6 +715,8 @@ export const userPreferences = sqliteTable("user_preferences", {
disableUpdateCheck: integer("disable_update_check", { mode: "boolean" }),
confirmTabClose: integer("confirm_tab_close", { mode: "boolean" }),
hiddenRailTabs: text("hidden_rail_tabs"),
compactHostView: integer("compact_host_view", { mode: "boolean" }),
statusColorScheme: text("status_color_scheme"),
updatedAt: text("updated_at")
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
@@ -763,6 +775,19 @@ export const hostHealthHistory = sqliteTable("host_health_history", {
detail: text("detail"),
});
export const dashboardServiceLinks = sqliteTable("dashboard_service_links", {
id: integer("id").primaryKey({ autoIncrement: true }),
userId: text("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
label: text("label").notNull(),
url: text("url").notNull(),
order: integer("order").notNull().default(0),
createdAt: text("created_at")
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
});
// --- tmux-monitor begin ---
export const tmuxSessionTags = sqliteTable("tmux_session_tags", {
id: integer("id").primaryKey({ autoIncrement: true }),
@@ -0,0 +1,399 @@
import { execSync } from "child_process";
import { promises as fs } from "fs";
import path from "path";
import type { AuthenticatedRequest } from "../../../types/index.js";
import type { RequestHandler, Router } from "express";
import { eq } from "drizzle-orm";
import { authLogger } from "../../utils/logger.js";
import { db } from "../db/index.js";
import { users } from "../db/schema.js";
import { logAudit, getRequestMeta } from "../../utils/audit-logger.js";
const DATA_DIR = process.env.DATA_DIR || "./db/data";
const SSL_DIR = path.join(DATA_DIR, "ssl");
const ACME_WEBROOT = path.join(DATA_DIR, "acme-webroot");
const CLOUDFLARE_CREDENTIALS_FILE = path.join(
DATA_DIR,
"ssl",
"cloudflare.ini",
);
export type AcmeSettings = {
enabled: boolean;
domain: string;
email: string;
challengeType: "http-webroot" | "dns-cloudflare";
cloudflareToken: string;
lastIssuedAt: string | null;
certStatus: "none" | "valid" | "expiring" | "expired";
certExpiresAt: string | null;
};
function getCertInfo(): {
status: "none" | "valid" | "expiring" | "expired";
expiresAt: string | null;
} {
const certFile = path.join(SSL_DIR, "termix.crt");
try {
execSync(`openssl x509 -in "${certFile}" -noout 2>/dev/null`, {
stdio: "pipe",
});
} catch {
return { status: "none", expiresAt: null };
}
try {
const endDateRaw = execSync(
`openssl x509 -in "${certFile}" -noout -enddate`,
{ stdio: "pipe" },
)
.toString()
.trim()
.replace("notAfter=", "");
const expiresAt = new Date(endDateRaw).toISOString();
try {
execSync(`openssl x509 -in "${certFile}" -checkend 0 -noout`, {
stdio: "pipe",
});
} catch {
return { status: "expired", expiresAt };
}
try {
execSync(`openssl x509 -in "${certFile}" -checkend 2592000 -noout`, {
stdio: "pipe",
});
return { status: "valid", expiresAt };
} catch {
return { status: "expiring", expiresAt };
}
} catch {
return { status: "none", expiresAt: null };
}
}
function getAcmeSettingsFromDb(): AcmeSettings {
const row = db.$client
.prepare("SELECT value FROM settings WHERE key = 'acme_ssl_settings'")
.get() as { value: string } | undefined;
const { status, expiresAt } = getCertInfo();
const stored = row ? JSON.parse(row.value) : {};
return {
enabled: stored.enabled ?? false,
domain: stored.domain ?? "",
email: stored.email ?? "",
challengeType: stored.challengeType ?? "http-webroot",
cloudflareToken: stored.cloudflareToken
? `${stored.cloudflareToken.slice(0, 4)}${"*".repeat(Math.max(0, stored.cloudflareToken.length - 4))}`
: "",
lastIssuedAt: stored.lastIssuedAt ?? null,
certStatus: status,
certExpiresAt: expiresAt,
};
}
export function registerAcmeSSLRoutes(
router: Router,
authenticateJWT: RequestHandler,
): void {
/**
* @openapi
* /users/acme-ssl-settings:
* get:
* summary: Get ACME SSL settings
* description: Returns current ACME/Let's Encrypt configuration and certificate status.
* tags:
* - Users
* responses:
* 200:
* description: ACME SSL settings and certificate status.
* 500:
* description: Failed to get ACME SSL settings.
*/
router.get("/acme-ssl-settings", authenticateJWT, async (_req, res) => {
try {
res.json(getAcmeSettingsFromDb());
} catch (err) {
authLogger.error("Failed to get ACME SSL settings", err);
res.status(500).json({ error: "Failed to get ACME SSL settings" });
}
});
/**
* @openapi
* /users/acme-ssl-settings:
* patch:
* summary: Update ACME SSL settings (admin only)
* description: Saves ACME/Let's Encrypt configuration.
* tags:
* - Users
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* enabled:
* type: boolean
* domain:
* type: string
* email:
* type: string
* challengeType:
* type: string
* enum: [http-webroot, dns-cloudflare]
* cloudflareToken:
* type: string
* responses:
* 200:
* description: ACME SSL settings updated.
* 403:
* description: Not authorized.
* 500:
* description: Failed to update ACME SSL settings.
*/
router.patch("/acme-ssl-settings", authenticateJWT, async (req, res) => {
const userId = (req as AuthenticatedRequest).userId;
try {
const user = await db.select().from(users).where(eq(users.id, userId));
if (!user || user.length === 0 || !user[0].isAdmin) {
return res.status(403).json({ error: "Not authorized" });
}
const existing = db.$client
.prepare("SELECT value FROM settings WHERE key = 'acme_ssl_settings'")
.get() as { value: string } | undefined;
const current = existing ? JSON.parse(existing.value) : {};
const { enabled, domain, email, challengeType, cloudflareToken } =
req.body;
const updated = {
...current,
...(typeof enabled === "boolean" && { enabled }),
...(typeof domain === "string" && { domain }),
...(typeof email === "string" && { email }),
...(typeof challengeType === "string" && { challengeType }),
...(typeof cloudflareToken === "string" &&
cloudflareToken &&
!cloudflareToken.includes("*") && { cloudflareToken }),
};
db.$client
.prepare(
"INSERT OR REPLACE INTO settings (key, value) VALUES ('acme_ssl_settings', ?)",
)
.run(JSON.stringify(updated));
const { ipAddress, userAgent } = getRequestMeta(req);
const actorRecord = await db
.select({ username: users.username })
.from(users)
.where(eq(users.id, userId))
.limit(1);
await logAudit({
userId,
username: actorRecord[0]?.username ?? userId,
action: "update_acme_ssl_settings",
resourceType: "setting",
details: JSON.stringify({
enabled,
domain,
email,
challengeType,
hasCloudflareToken: !!updated.cloudflareToken,
}),
ipAddress,
userAgent,
success: true,
});
res.json(getAcmeSettingsFromDb());
} catch (err) {
authLogger.error("Failed to update ACME SSL settings", err);
res.status(500).json({ error: "Failed to update ACME SSL settings" });
}
});
/**
* @openapi
* /users/acme-ssl-request:
* post:
* summary: Request or renew Let's Encrypt certificate (admin only)
* description: Triggers certbot to issue or renew a certificate using the configured challenge method.
* tags:
* - Users
* responses:
* 200:
* description: Certificate issued or renewed successfully.
* 400:
* description: Invalid configuration.
* 403:
* description: Not authorized.
* 500:
* description: Certificate issuance failed.
*/
router.post("/acme-ssl-request", authenticateJWT, async (req, res) => {
const userId = (req as AuthenticatedRequest).userId;
try {
const user = await db.select().from(users).where(eq(users.id, userId));
if (!user || user.length === 0 || !user[0].isAdmin) {
return res.status(403).json({ error: "Not authorized" });
}
const row = db.$client
.prepare("SELECT value FROM settings WHERE key = 'acme_ssl_settings'")
.get() as { value: string } | undefined;
if (!row) {
return res.status(400).json({ error: "ACME settings not configured" });
}
const settings = JSON.parse(row.value);
const { domain, email, challengeType, cloudflareToken } = settings;
if (!domain || !email) {
return res.status(400).json({ error: "Domain and email are required" });
}
try {
execSync("certbot --version", { stdio: "pipe" });
} catch {
return res
.status(500)
.json({ error: "certbot is not available in this environment" });
}
await fs.mkdir(SSL_DIR, { recursive: true });
await fs.mkdir(ACME_WEBROOT, { recursive: true });
let certbotCmd: string;
if (challengeType === "dns-cloudflare") {
if (!cloudflareToken) {
return res.status(400).json({
error: "Cloudflare API token is required for DNS challenge",
});
}
await fs.mkdir(path.dirname(CLOUDFLARE_CREDENTIALS_FILE), {
recursive: true,
});
await fs.writeFile(
CLOUDFLARE_CREDENTIALS_FILE,
`dns_cloudflare_api_token = ${cloudflareToken}\n`,
{ mode: 0o600 },
);
certbotCmd = [
"certbot",
"certonly",
"--non-interactive",
"--agree-tos",
"--dns-cloudflare",
`--dns-cloudflare-credentials "${CLOUDFLARE_CREDENTIALS_FILE}"`,
"--dns-cloudflare-propagation-seconds",
"30",
"-d",
`"${domain}"`,
"--email",
`"${email}"`,
"--cert-name",
"termix",
].join(" ");
} else {
certbotCmd = [
"certbot",
"certonly",
"--non-interactive",
"--agree-tos",
"--webroot",
"-w",
`"${ACME_WEBROOT}"`,
"-d",
`"${domain}"`,
"--email",
`"${email}"`,
"--cert-name",
"termix",
].join(" ");
}
authLogger.info("Requesting Let's Encrypt certificate", {
domain,
challengeType,
operation: "acme_cert_request",
});
execSync(certbotCmd, { stdio: "pipe", timeout: 120000 });
const liveDir = `/etc/letsencrypt/live/termix`;
const fullchainSrc = path.join(liveDir, "fullchain.pem");
const privkeySrc = path.join(liveDir, "privkey.pem");
const certDest = path.join(SSL_DIR, "termix.crt");
const keyDest = path.join(SSL_DIR, "termix.key");
await fs.copyFile(fullchainSrc, certDest);
await fs.copyFile(privkeySrc, keyDest);
await fs.chmod(keyDest, 0o600);
await fs.chmod(certDest, 0o644);
const updated = { ...settings, lastIssuedAt: new Date().toISOString() };
db.$client
.prepare(
"INSERT OR REPLACE INTO settings (key, value) VALUES ('acme_ssl_settings', ?)",
)
.run(JSON.stringify(updated));
authLogger.info("Let's Encrypt certificate issued and installed", {
domain,
operation: "acme_cert_installed",
});
const { ipAddress, userAgent } = getRequestMeta(req);
const actorRecord = await db
.select({ username: users.username })
.from(users)
.where(eq(users.id, userId))
.limit(1);
await logAudit({
userId,
username: actorRecord[0]?.username ?? userId,
action: "acme_ssl_request",
resourceType: "setting",
details: JSON.stringify({ domain, challengeType, success: true }),
ipAddress,
userAgent,
success: true,
});
res.json({ success: true, ...getAcmeSettingsFromDb() });
} catch (err) {
const message = err instanceof Error ? err.message : "Unknown error";
authLogger.error("ACME certificate request failed", err);
const { ipAddress, userAgent } = getRequestMeta(req);
const actorRecord = await db
.select({ username: users.username })
.from(users)
.where(eq(users.id, userId))
.limit(1);
await logAudit({
userId,
username: actorRecord[0]?.username ?? userId,
action: "acme_ssl_request",
resourceType: "setting",
details: JSON.stringify({ error: message }),
ipAddress,
userAgent,
success: false,
});
res.status(500).json({ error: `Certificate request failed: ${message}` });
}
});
}
+7 -3
View File
@@ -154,7 +154,9 @@ router.post(
error: keyInfo.error,
});
return res.status(400).json({
error: `Invalid SSH key: ${keyInfo.error}`,
error: keyInfo.error
? `Invalid SSH key: ${keyInfo.error}`
: "Unrecognized SSH key format. Only OpenSSH and PEM formats are supported (not PuTTY .ppk).",
});
}
}
@@ -525,7 +527,9 @@ router.put(
error: keyInfo.error,
});
return res.status(400).json({
error: `Invalid SSH key: ${keyInfo.error}`,
error: keyInfo.error
? `Invalid SSH key: ${keyInfo.error}`
: "Unrecognized SSH key format. Only OpenSSH and PEM formats are supported (not PuTTY .ppk).",
});
}
updateFields.privateKey = keyInfo.privateKey;
@@ -986,7 +990,7 @@ function formatSSHHostOutput(
tunnelConnections: host.tunnelConnections
? JSON.parse(host.tunnelConnections as string)
: [],
enableFileManager: !!host.enableFileManager,
enableFileManager: host.enableFileManager !== false,
defaultPath: host.defaultPath,
createdAt: host.createdAt,
updatedAt: host.updatedAt,
@@ -0,0 +1,281 @@
import type { AuthenticatedRequest } from "../../../types/index.js";
import type { Request, Response } from "express";
import { and, asc, eq } from "drizzle-orm";
import { dashboardLogger } from "../../utils/logger.js";
import { db } from "../db/index.js";
import { dashboardServiceLinks } from "../db/schema.js";
import { isNonEmptyString } from "./host-normalizers.js";
import express from "express";
export const dashboardServiceLinksRouter = express.Router();
function isValidUrl(url: string): boolean {
try {
const parsed = new URL(url);
return parsed.protocol === "http:" || parsed.protocol === "https:";
} catch {
return false;
}
}
/**
* @openapi
* /service-links:
* get:
* summary: Get service links
* description: Returns all dashboard service links for the authenticated user.
* tags:
* - Dashboard
* responses:
* 200:
* description: List of service links.
* 500:
* description: Failed to fetch service links.
*/
dashboardServiceLinksRouter.get("/", async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
try {
const links = await db
.select()
.from(dashboardServiceLinks)
.where(eq(dashboardServiceLinks.userId, userId))
.orderBy(asc(dashboardServiceLinks.order), asc(dashboardServiceLinks.id));
res.json(links);
} catch (err) {
dashboardLogger.error("Failed to fetch service links", err);
res.status(500).json({ error: "Failed to fetch service links" });
}
});
/**
* @openapi
* /service-links:
* post:
* summary: Create service link
* description: Creates a new dashboard service link for the authenticated user.
* tags:
* - Dashboard
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - label
* - url
* properties:
* label:
* type: string
* url:
* type: string
* responses:
* 201:
* description: Service link created.
* 400:
* description: Invalid data.
* 500:
* description: Failed to create service link.
*/
dashboardServiceLinksRouter.post("/", async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
const { label, url } = req.body;
if (!isNonEmptyString(label) || !isNonEmptyString(url)) {
return res.status(400).json({ error: "label and url are required" });
}
if (!isValidUrl(url)) {
return res
.status(400)
.json({ error: "url must be a valid http or https URL" });
}
try {
const existing = await db
.select({ order: dashboardServiceLinks.order })
.from(dashboardServiceLinks)
.where(eq(dashboardServiceLinks.userId, userId))
.orderBy(asc(dashboardServiceLinks.order));
const nextOrder =
existing.length > 0 ? existing[existing.length - 1].order + 1 : 0;
const [created] = await db
.insert(dashboardServiceLinks)
.values({
userId,
label: label.trim(),
url: url.trim(),
order: nextOrder,
createdAt: new Date().toISOString(),
})
.returning();
res.status(201).json(created);
} catch (err) {
dashboardLogger.error("Failed to create service link", err);
res.status(500).json({ error: "Failed to create service link" });
}
});
/**
* @openapi
* /service-links/{id}:
* delete:
* summary: Delete service link
* description: Deletes a dashboard service link by ID.
* tags:
* - Dashboard
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Service link deleted.
* 400:
* description: Invalid id.
* 404:
* description: Not found.
* 500:
* description: Failed to delete service link.
*/
dashboardServiceLinksRouter.delete(
"/:id",
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
const idParam = Array.isArray(req.params.id)
? req.params.id[0]
: req.params.id;
const id = parseInt(idParam);
if (isNaN(id)) {
return res.status(400).json({ error: "Invalid id" });
}
try {
const existing = await db
.select()
.from(dashboardServiceLinks)
.where(
and(
eq(dashboardServiceLinks.id, id),
eq(dashboardServiceLinks.userId, userId),
),
);
if (existing.length === 0) {
return res.status(404).json({ error: "Not found" });
}
await db
.delete(dashboardServiceLinks)
.where(
and(
eq(dashboardServiceLinks.id, id),
eq(dashboardServiceLinks.userId, userId),
),
);
res.json({ message: "Service link deleted" });
} catch (err) {
dashboardLogger.error("Failed to delete service link", err);
res.status(500).json({ error: "Failed to delete service link" });
}
},
);
/**
* @openapi
* /service-links/{id}:
* put:
* summary: Update service link
* description: Updates label or url of a dashboard service link.
* tags:
* - Dashboard
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* label:
* type: string
* url:
* type: string
* responses:
* 200:
* description: Service link updated.
* 400:
* description: Invalid data.
* 404:
* description: Not found.
* 500:
* description: Failed to update service link.
*/
dashboardServiceLinksRouter.put("/:id", async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
const idParam = Array.isArray(req.params.id)
? req.params.id[0]
: req.params.id;
const id = parseInt(idParam);
const { label, url } = req.body;
if (isNaN(id)) {
return res.status(400).json({ error: "Invalid id" });
}
if (url !== undefined && !isValidUrl(url)) {
return res
.status(400)
.json({ error: "url must be a valid http or https URL" });
}
try {
const existing = await db
.select()
.from(dashboardServiceLinks)
.where(
and(
eq(dashboardServiceLinks.id, id),
eq(dashboardServiceLinks.userId, userId),
),
);
if (existing.length === 0) {
return res.status(404).json({ error: "Not found" });
}
const updates: Partial<{ label: string; url: string }> = {};
if (isNonEmptyString(label)) updates.label = label.trim();
if (isNonEmptyString(url)) updates.url = url.trim();
if (Object.keys(updates).length === 0) {
return res.status(400).json({ error: "Nothing to update" });
}
const [updated] = await db
.update(dashboardServiceLinks)
.set(updates)
.where(
and(
eq(dashboardServiceLinks.id, id),
eq(dashboardServiceLinks.userId, userId),
),
)
.returning();
res.json(updated);
} catch (err) {
dashboardLogger.error("Failed to update service link", err);
res.status(500).json({ error: "Failed to update service link" });
}
});
@@ -0,0 +1,104 @@
import { describe, it, expect } from "vitest";
import { parseSSHConfig } from "./host-bulk-routes.js";
describe("parseSSHConfig", () => {
it("parses a basic Host block", () => {
const config = `
Host myserver
HostName 192.168.1.10
User alice
Port 2222
`;
const result = parseSSHConfig(config);
expect(result).toHaveLength(1);
expect(result[0]).toMatchObject({
name: "myserver",
hostname: "192.168.1.10",
user: "alice",
port: 2222,
});
});
it("parses multiple Host blocks", () => {
const config = `
Host web
HostName web.example.com
User deploy
Host db
HostName db.example.com
User postgres
Port 5432
`;
const result = parseSSHConfig(config);
expect(result).toHaveLength(2);
expect(result[0].name).toBe("web");
expect(result[1].name).toBe("db");
expect(result[1].port).toBe(5432);
});
it("ignores comment lines", () => {
const config = `
# This is a comment
Host server
# Another comment
HostName 10.0.0.1
User root
`;
const result = parseSSHConfig(config);
expect(result).toHaveLength(1);
expect(result[0].hostname).toBe("10.0.0.1");
});
it("skips wildcard Host entries", () => {
const config = `
Host *
ServerAliveInterval 60
Host prod
HostName prod.example.com
User ubuntu
`;
const result = parseSSHConfig(config);
expect(result).toHaveLength(1);
expect(result[0].name).toBe("prod");
});
it("captures IdentityFile and ProxyJump", () => {
const config = `
Host bastion
HostName bastion.example.com
User ec2-user
IdentityFile ~/.ssh/id_rsa
ProxyJump jumphost.example.com
`;
const result = parseSSHConfig(config);
expect(result).toHaveLength(1);
expect(result[0].identityFile).toBe("~/.ssh/id_rsa");
expect(result[0].proxyJump).toBe("jumphost.example.com");
});
it("skips Host blocks without a HostName", () => {
const config = `
Host alias-only
User foo
`;
const result = parseSSHConfig(config);
expect(result).toHaveLength(0);
});
it("defaults port to undefined when not specified", () => {
const config = `
Host server
HostName 1.2.3.4
User root
`;
const result = parseSSHConfig(config);
expect(result[0].port).toBeUndefined();
});
it("returns empty array for empty input", () => {
expect(parseSSHConfig("")).toHaveLength(0);
expect(parseSSHConfig(" \n\n ")).toHaveLength(0);
});
});
@@ -11,6 +11,68 @@ import {
normalizeImportedHost,
} from "./host-normalizers.js";
type SSHConfigHost = {
name: string;
hostname?: string;
user?: string;
port?: number;
identityFile?: string;
proxyJump?: string;
};
export function parseSSHConfig(content: string): SSHConfigHost[] {
const results: SSHConfigHost[] = [];
let current: SSHConfigHost | null = null;
for (const rawLine of content.split("\n")) {
const line = rawLine.trim();
if (!line || line.startsWith("#")) continue;
const spaceIdx = line.indexOf(" ");
if (spaceIdx === -1) continue;
const key = line.slice(0, spaceIdx).toLowerCase();
const value = line.slice(spaceIdx + 1).trim();
if (key === "host") {
if (current && current.hostname) results.push(current);
// Skip wildcard patterns
if (value === "*" || value.includes("*") || value.includes("?")) {
current = null;
} else {
current = { name: value };
}
continue;
}
if (!current) continue;
switch (key) {
case "hostname":
current.hostname = value;
break;
case "user":
current.user = value;
break;
case "port": {
const p = Number.parseInt(value, 10);
if (p > 0 && p <= 65535) current.port = p;
break;
}
case "identityfile":
if (!current.identityFile) current.identityFile = value;
break;
case "proxyjump":
current.proxyJump = value;
break;
}
}
if (current && current.hostname) results.push(current);
return results;
}
export function registerHostBulkRoutes(
router: Router,
authenticateJWT: RequestHandler,
@@ -363,6 +425,12 @@ export function registerHostBulkRoutes(
if (fallback.length > 0) {
hostData.credentialId = fallback[0].id;
} else if (isNonEmptyString(hostData.key)) {
hostData.authType = "key";
hostData.credentialId = undefined;
} else if (isNonEmptyString(hostData.password)) {
hostData.authType = "password";
hostData.credentialId = undefined;
} else {
results.failed++;
results.errors.push(
@@ -519,4 +587,212 @@ export function registerHostBulkRoutes(
});
},
);
/**
* @openapi
* /host/ssh-config-import:
* post:
* summary: Import hosts from an OpenSSH config file
* description: Parses an OpenSSH ~/.ssh/config file and imports the defined hosts.
* tags:
* - SSH
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - content
* properties:
* content:
* type: string
* description: Raw text content of the SSH config file.
* overwrite:
* type: boolean
* responses:
* 200:
* description: Import completed.
* 400:
* description: Invalid request body.
*/
router.post(
"/ssh-config-import",
authenticateJWT,
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
const { content, overwrite } = req.body;
if (!isNonEmptyString(content)) {
return res.status(400).json({
error: "content is required and must be a non-empty string",
});
}
let parsed: SSHConfigHost[];
try {
parsed = parseSSHConfig(content);
} catch (err) {
return res
.status(400)
.json({ error: "Failed to parse SSH config file" });
}
if (parsed.length === 0) {
return res.status(400).json({
error: "No valid Host entries found in the SSH config file",
});
}
if (parsed.length > 100) {
return res
.status(400)
.json({ error: "Maximum 100 hosts allowed per import" });
}
const hostsToImport = parsed.map((h) => ({
name: h.name,
ip: h.hostname,
port: h.port ?? 22,
username: h.user,
authType: h.identityFile ? "key" : undefined,
connectionType: "ssh",
enableSsh: true,
...(h.proxyJump
? {
jumpHosts: [{ host: h.proxyJump, port: 22 }],
}
: {}),
}));
const results = {
success: 0,
updated: 0,
skipped: 0,
failed: 0,
errors: [] as string[],
};
let existingHostMap: Map<string, { id: number }> | undefined;
if (overwrite) {
try {
const allHosts = await SimpleDBOps.select<Record<string, unknown>>(
db.select().from(hosts).where(eq(hosts.userId, userId)),
"ssh_data",
userId,
);
existingHostMap = new Map();
for (const h of allHosts) {
const key = `${h.ip}:${h.port}:${h.username}`;
existingHostMap.set(key, { id: h.id as number });
}
} catch {
existingHostMap = undefined;
}
}
for (let i = 0; i < hostsToImport.length; i++) {
const hostData = normalizeImportedHost(
hostsToImport[i] as Record<string, unknown>,
);
try {
if (!isNonEmptyString(hostData.ip) || !isValidPort(hostData.port)) {
results.failed++;
results.errors.push(
`Host "${parsed[i].name}": Missing required fields (HostName, Port)`,
);
continue;
}
const sshDataObj: Record<string, unknown> = {
userId,
connectionType: "ssh",
name: hostData.name || hostData.ip,
folder: "Default",
tags: "",
ip: hostData.ip,
port: hostData.port,
username: hostData.username || null,
authType: hostData.authType || "none",
password: null,
key: null,
keyPassword: null,
keyType: null,
credentialId: null,
pin: false,
enableTerminal: true,
enableTunnel: true,
enableFileManager: true,
enableDocker: false,
enableProxmox: false,
enableTmuxMonitor: false,
showTerminalInSidebar: 0,
showFileManagerInSidebar: 0,
showTunnelInSidebar: 0,
showDockerInSidebar: 0,
showServerStatsInSidebar: 0,
defaultPath: "/",
sudoPassword: null,
tunnelConnections: "[]",
jumpHosts: hostData.jumpHosts
? JSON.stringify(hostData.jumpHosts)
: null,
quickActions: null,
statsConfig: null,
dockerConfig: null,
proxmoxConfig: null,
terminalConfig: null,
forceKeyboardInteractive: "false",
notes: null,
useSocks5: 0,
socks5Host: null,
socks5Port: null,
socks5Username: null,
socks5Password: null,
socks5ProxyChain: null,
portKnockSequence: null,
overrideCredentialUsername: 0,
enableSsh: true,
enableRdp: false,
enableVnc: false,
enableTelnet: false,
updatedAt: new Date().toISOString(),
};
const lookupKey = `${hostData.ip}:${hostData.port}:${hostData.username}`;
const existing = existingHostMap?.get(lookupKey);
if (existing) {
await SimpleDBOps.update(
hosts,
"ssh_data",
eq(hosts.id, existing.id),
sshDataObj,
userId,
);
results.updated++;
} else {
sshDataObj.createdAt = new Date().toISOString();
await SimpleDBOps.insert(hosts, "ssh_data", sshDataObj, userId);
results.success++;
}
} catch (error) {
results.failed++;
results.errors.push(
`Host "${parsed[i].name}": ${error instanceof Error ? error.message : "Unknown error"}`,
);
}
}
res.json({
message: `Import completed: ${results.success} created, ${results.updated} updated, ${results.failed} failed`,
success: results.success,
updated: results.updated,
skipped: results.skipped,
failed: results.failed,
errors: results.errors,
});
},
);
}
@@ -82,7 +82,7 @@ export function registerHostInternalRoutes(router: Router): void {
),
pin: !!host.pin,
enableTerminal: !!host.enableTerminal,
enableFileManager: !!host.enableFileManager,
enableFileManager: host.enableFileManager !== false,
showTerminalInSidebar: !!host.showTerminalInSidebar,
showFileManagerInSidebar: !!host.showFileManagerInSidebar,
showTunnelInSidebar: !!host.showTunnelInSidebar,
@@ -155,7 +155,7 @@ export function registerHostInternalRoutes(router: Router): void {
tunnelConnections: tunnelConnections,
pin: !!host.pin,
enableTerminal: !!host.enableTerminal,
enableFileManager: !!host.enableFileManager,
enableFileManager: host.enableFileManager !== false,
showTerminalInSidebar: !!host.showTerminalInSidebar,
showFileManagerInSidebar: !!host.showFileManagerInSidebar,
showTunnelInSidebar: !!host.showTunnelInSidebar,
@@ -101,7 +101,10 @@ export function registerHostNetworkRoutes(
try {
const host = await db
.select({ macAddress: hosts.macAddress })
.select({
macAddress: hosts.macAddress,
wolBroadcastAddress: hosts.wolBroadcastAddress,
})
.from(hosts)
.where(and(eq(hosts.id, hostId), eq(hosts.userId, userId)))
.then((rows) => rows[0]);
@@ -116,7 +119,10 @@ export function registerHostNetworkRoutes(
.json({ error: "No valid MAC address configured" });
}
await sendWakeOnLan(host.macAddress);
await sendWakeOnLan(
host.macAddress,
host.wolBroadcastAddress ?? undefined,
);
sshLogger.info("Wake-on-LAN packet sent", {
operation: "wake_on_lan",
@@ -237,7 +237,7 @@ export function transformHostResponse(
pin: !!host.pin,
enableTerminal: !!host.enableTerminal,
enableTunnel: !!host.enableTunnel,
enableFileManager: !!host.enableFileManager,
enableFileManager: host.enableFileManager !== false,
enableDocker: !!host.enableDocker,
enableProxmox: !!host.enableProxmox,
enableTmuxMonitor: !!host.enableTmuxMonitor,
@@ -293,6 +293,7 @@ export function transformHostResponse(
? JSON.parse(host.proxmoxConfig as string)
: undefined,
forceKeyboardInteractive: host.forceKeyboardInteractive === "true",
useWarpgate: !!host.useWarpgate,
socks5ProxyChain: host.socks5ProxyChain
? JSON.parse(host.socks5ProxyChain as string)
: [],
+57 -12
View File
@@ -144,6 +144,7 @@ router.post(
password,
authMethod,
authType,
useWarpgate,
credentialId,
key,
keyPassword,
@@ -153,6 +154,7 @@ router.post(
enableTerminal,
enableTunnel,
enableFileManager,
scpLegacy,
enableDocker,
enableProxmox,
enableTmuxMonitor,
@@ -184,6 +186,7 @@ router.post(
portKnockSequence,
overrideCredentialUsername,
macAddress,
wolBroadcastAddress,
enableSsh,
enableRdp,
enableVnc,
@@ -243,6 +246,7 @@ router.post(
port,
username: effectiveUsername,
authType: effectiveAuthType,
useWarpgate: useWarpgate ? 1 : 0,
credentialId: credentialId || null,
overrideCredentialUsername: overrideCredentialUsername ? 1 : 0,
pin: pin ? 1 : 0,
@@ -256,6 +260,7 @@ router.post(
? JSON.stringify(quickActions)
: null,
enableFileManager: enableFileManager ? 1 : 0,
scpLegacy: scpLegacy ? 1 : 0,
enableDocker: enableDocker ? 1 : 0,
enableProxmox: enableProxmox ? 1 : 0,
enableTmuxMonitor: enableTmuxMonitor ? 1 : 0,
@@ -301,6 +306,7 @@ router.post(
? JSON.stringify(socks5ProxyChain)
: null,
macAddress: macAddress || null,
wolBroadcastAddress: wolBroadcastAddress || null,
portKnockSequence: portKnockSequence
? JSON.stringify(portKnockSequence)
: null,
@@ -713,6 +719,7 @@ router.put(
password,
authMethod,
authType,
useWarpgate,
credentialId,
key,
keyPassword,
@@ -722,6 +729,7 @@ router.put(
enableTerminal,
enableTunnel,
enableFileManager,
scpLegacy,
enableDocker,
enableProxmox,
enableTmuxMonitor,
@@ -753,6 +761,7 @@ router.put(
portKnockSequence,
overrideCredentialUsername,
macAddress,
wolBroadcastAddress,
enableSsh,
enableRdp,
enableVnc,
@@ -809,6 +818,7 @@ router.put(
port,
username: effectiveUsername,
authType: effectiveAuthType,
useWarpgate: useWarpgate ? 1 : 0,
credentialId: credentialId || null,
overrideCredentialUsername: overrideCredentialUsername ? 1 : 0,
pin: pin ? 1 : 0,
@@ -822,6 +832,7 @@ router.put(
? JSON.stringify(quickActions)
: null,
enableFileManager: enableFileManager ? 1 : 0,
scpLegacy: scpLegacy ? 1 : 0,
enableDocker: enableDocker ? 1 : 0,
enableProxmox: enableProxmox ? 1 : 0,
enableTmuxMonitor: enableTmuxMonitor ? 1 : 0,
@@ -867,6 +878,7 @@ router.put(
? JSON.stringify(socks5ProxyChain)
: null,
macAddress: macAddress || null,
wolBroadcastAddress: wolBroadcastAddress || null,
portKnockSequence: portKnockSequence
? JSON.stringify(portKnockSequence)
: null,
@@ -952,10 +964,9 @@ router.put(
sshDataObj.keyType = null;
}
if (rdpPassword !== undefined) sshDataObj.rdpPassword = rdpPassword || null;
if (vncPassword !== undefined) sshDataObj.vncPassword = vncPassword || null;
if (telnetPassword !== undefined)
sshDataObj.telnetPassword = telnetPassword || null;
if (rdpPassword) sshDataObj.rdpPassword = rdpPassword;
if (vncPassword) sshDataObj.vncPassword = vncPassword;
if (telnetPassword) sshDataObj.telnetPassword = telnetPassword;
try {
const accessInfo = await permissionManager.canAccessHost(
@@ -988,6 +999,8 @@ router.put(
.select({
userId: hosts.userId,
credentialId: hosts.credentialId,
rdpCredentialId: hosts.rdpCredentialId,
vncCredentialId: hosts.vncCredentialId,
authType: hosts.authType,
})
.from(hosts)
@@ -1025,11 +1038,26 @@ router.put(
});
}
if (sshDataObj.credentialId !== undefined) {
if (
hostRecord[0].credentialId !== null &&
sshDataObj.credentialId === null
) {
{
const newCredId =
sshDataObj.credentialId !== undefined
? sshDataObj.credentialId
: hostRecord[0].credentialId;
const newRdpCredId =
sshDataObj.rdpCredentialId !== undefined
? sshDataObj.rdpCredentialId
: hostRecord[0].rdpCredentialId;
const newVncCredId =
sshDataObj.vncCredentialId !== undefined
? sshDataObj.vncCredentialId
: hostRecord[0].vncCredentialId;
const hadCredential =
hostRecord[0].credentialId !== null ||
hostRecord[0].rdpCredentialId !== null ||
hostRecord[0].vncCredentialId !== null;
const willHaveCredential =
newCredId !== null || newRdpCredId !== null || newVncCredId !== null;
if (hadCredential && !willHaveCredential) {
await db
.delete(hostAccess)
.where(eq(hostAccess.hostId, Number(hostId)));
@@ -1169,6 +1197,7 @@ router.get(
tunnelConnections: hosts.tunnelConnections,
jumpHosts: hosts.jumpHosts,
enableFileManager: hosts.enableFileManager,
scpLegacy: hosts.scpLegacy,
defaultPath: hosts.defaultPath,
autostartPassword: hosts.autostartPassword,
autostartKey: hosts.autostartKey,
@@ -1203,6 +1232,7 @@ router.get(
ignoreCert: hosts.ignoreCert,
guacamoleConfig: hosts.guacamoleConfig,
macAddress: hosts.macAddress,
wolBroadcastAddress: hosts.wolBroadcastAddress,
dockerConfig: hosts.dockerConfig,
proxmoxConfig: hosts.proxmoxConfig,
enableSsh: hosts.enableSsh,
@@ -1213,11 +1243,13 @@ router.get(
rdpPort: hosts.rdpPort,
vncPort: hosts.vncPort,
telnetPort: hosts.telnetPort,
rdpCredentialId: hosts.rdpCredentialId,
rdpUser: hosts.rdpUser,
rdpPassword: hosts.rdpPassword,
rdpDomain: hosts.rdpDomain,
rdpSecurity: hosts.rdpSecurity,
rdpIgnoreCert: hosts.rdpIgnoreCert,
vncCredentialId: hosts.vncCredentialId,
vncUser: hosts.vncUser,
vncPassword: hosts.vncPassword,
telnetUser: hosts.telnetUser,
@@ -1445,7 +1477,19 @@ router.get(
const host = data[0];
const resolved = (await resolveHostCredentials(host, userId)) || host;
const value = resolved[field];
let value = resolved[field];
if (!value && field === "sudoPassword" && resolved.terminalConfig) {
try {
const tc =
typeof resolved.terminalConfig === "string"
? JSON.parse(resolved.terminalConfig)
: resolved.terminalConfig;
value = tc?.sudoPassword || null;
} catch {
// malformed JSON — leave value null
}
}
if (!value) {
return res.status(404).json({ error: "No password set" });
@@ -1574,7 +1618,8 @@ router.get(
!!resolvedHost.overrideCredentialUsername,
enableTerminal: !!resolvedHost.enableTerminal,
enableTunnel: !!resolvedHost.enableTunnel,
enableFileManager: !!resolvedHost.enableFileManager,
enableFileManager: resolvedHost.enableFileManager !== false,
scpLegacy: !!resolvedHost.scpLegacy,
enableDocker: !!resolvedHost.enableDocker,
enableProxmox: !!resolvedHost.enableProxmox,
enableTmuxMonitor: !!resolvedHost.enableTmuxMonitor,
@@ -1722,7 +1767,7 @@ router.get(
!!resolvedHost.overrideCredentialUsername,
enableTerminal: !!resolvedHost.enableTerminal,
enableTunnel: !!resolvedHost.enableTunnel,
enableFileManager: !!resolvedHost.enableFileManager,
enableFileManager: resolvedHost.enableFileManager !== false,
enableDocker: !!resolvedHost.enableDocker,
enableProxmox: !!resolvedHost.enableProxmox,
enableTmuxMonitor: !!resolvedHost.enableTmuxMonitor,
@@ -2,7 +2,7 @@ import type { Router } from "express";
import type { LDAPProviderConfig } from "../../../types/index.js";
import { db } from "../db/index.js";
import { ssoProviders, users, roles, userRoles } from "../db/schema.js";
import { eq } from "drizzle-orm";
import { eq, and } from "drizzle-orm";
import { nanoid } from "nanoid";
import { authLogger } from "../../utils/logger.js";
import { AuthManager } from "../../utils/auth-manager.js";
@@ -298,14 +298,7 @@ export function registerLDAPAuthRoutes(router: Router): void {
const isFirst = (countRow?.count || 0) === 0;
if (!isFirst && !autoProvision) {
const regRow = db.$client
.prepare(
"SELECT value FROM settings WHERE key = 'allow_registration'",
)
.get() as { value: string } | undefined;
if (regRow && regRow.value !== "true") {
return res.status(403).json({ error: "Registration is disabled" });
}
return res.status(403).json({ error: "Registration is disabled" });
}
userId = nanoid();
@@ -375,6 +368,39 @@ export function registerLDAPAuthRoutes(router: Router): void {
if (config.adminGroup && !!existingUsers[0].isAdmin !== isAdmin) {
await db.update(users).set({ isAdmin }).where(eq(users.id, userId));
existingUsers[0].isAdmin = isAdmin;
try {
const newRoleName = isAdmin ? "admin" : "user";
const oldRoleName = isAdmin ? "user" : "admin";
const newRole = await db
.select({ id: roles.id })
.from(roles)
.where(eq(roles.name, newRoleName))
.limit(1);
const oldRole = await db
.select({ id: roles.id })
.from(roles)
.where(eq(roles.name, oldRoleName))
.limit(1);
if (oldRole.length > 0) {
await db
.delete(userRoles)
.where(
and(
eq(userRoles.userId, userId),
eq(userRoles.roleId, oldRole[0].id),
),
);
}
if (newRole.length > 0) {
await db.insert(userRoles).values({
userId,
roleId: newRole[0].id,
grantedBy: userId,
});
}
} catch {
/* non-fatal */
}
}
// Update display name if not dual-auth
+19 -2
View File
@@ -23,7 +23,24 @@ const authenticateJWT = authManager.createAuthMiddleware();
* 200:
* description: List of open tabs ordered by tab_order.
*/
const TAB_TTL_MS = 30 * 60 * 1000;
const DEFAULT_TAB_TTL_MINUTES = 30;
function getTabTtlMs(): number {
try {
const row = db.$client
.prepare(
"SELECT value FROM settings WHERE key = 'terminal_session_timeout_minutes'",
)
.get() as { value: string } | undefined;
if (row) {
const minutes = parseInt(row.value, 10);
if (!isNaN(minutes) && minutes > 0) return minutes * 60_000;
}
} catch {
// DB not available, use default
}
return DEFAULT_TAB_TTL_MINUTES * 60_000;
}
// Legacy tab types that were renamed. Normalize on read so previously saved
// tabs still restore to the correct (renamed) tab type.
@@ -38,7 +55,7 @@ function normalizeTabType(tabType: string): string {
router.get("/", authenticateJWT, async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
try {
const cutoff = new Date(Date.now() - TAB_TTL_MS).toISOString();
const cutoff = new Date(Date.now() - getTabTtlMs()).toISOString();
const tabs = db
.select()
.from(userOpenTabs)
+35 -8
View File
@@ -129,7 +129,12 @@ router.post(
return res.status(403).json({ error: "Not host owner" });
}
if (!host[0].credentialId && host[0].authType !== "opkssh") {
if (
!host[0].credentialId &&
!host[0].rdpCredentialId &&
!host[0].vncCredentialId &&
host[0].authType !== "opkssh"
) {
return res.status(400).json({
error:
"Only hosts using credentials or OPKSSH can be shared. Please create a credential and assign it to this host before sharing.",
@@ -204,21 +209,25 @@ router.post(
.delete(sharedCredentials)
.where(eq(sharedCredentials.hostAccessId, existing[0].id));
if (host[0].credentialId) {
const activeCredentialId =
host[0].credentialId ??
host[0].rdpCredentialId ??
host[0].vncCredentialId;
if (activeCredentialId) {
const { SharedCredentialManager } =
await import("../../utils/shared-credential-manager.js");
const sharedCredManager = SharedCredentialManager.getInstance();
if (targetType === "user") {
await sharedCredManager.createSharedCredentialForUser(
existing[0].id,
host[0].credentialId,
activeCredentialId,
targetUserId!,
userId,
);
} else {
await sharedCredManager.createSharedCredentialsForRole(
existing[0].id,
host[0].credentialId,
activeCredentialId,
targetRoleId!,
userId,
);
@@ -252,18 +261,22 @@ router.post(
await import("../../utils/shared-credential-manager.js");
const sharedCredManager = SharedCredentialManager.getInstance();
if (host[0].credentialId) {
const activeCredentialId =
host[0].credentialId ??
host[0].rdpCredentialId ??
host[0].vncCredentialId;
if (activeCredentialId) {
if (targetType === "user") {
await sharedCredManager.createSharedCredentialForUser(
result.lastInsertRowid as number,
host[0].credentialId,
activeCredentialId,
targetUserId!,
userId,
);
} else {
await sharedCredManager.createSharedCredentialsForRole(
result.lastInsertRowid as number,
host[0].credentialId,
activeCredentialId,
targetRoleId!,
userId,
);
@@ -487,6 +500,12 @@ router.get(
try {
const now = new Date().toISOString();
const userRoleIds = await db
.select({ roleId: userRoles.roleId })
.from(userRoles)
.where(eq(userRoles.userId, userId));
const roleIds = userRoleIds.map((r) => r.roleId);
const sharedHosts = await db
.select({
id: hosts.id,
@@ -506,7 +525,15 @@ router.get(
.innerJoin(users, eq(hosts.userId, users.id))
.where(
and(
eq(hostAccess.userId, userId),
or(
eq(hostAccess.userId, userId),
roleIds.length > 0
? sql`${hostAccess.roleId} IN (${sql.join(
roleIds.map((id) => sql`${id}`),
sql`, `,
)})`
: sql`false`,
),
or(isNull(hostAccess.expiresAt), gte(hostAccess.expiresAt, now)),
),
)
+262
View File
@@ -924,6 +924,268 @@ router.post(
},
);
/**
* @openapi
* /snippets/export:
* get:
* summary: Export all snippets and folders as JSON
* description: Returns all snippets and snippet folders for the authenticated user as a JSON export.
* tags:
* - Snippets
* responses:
* 200:
* description: Export object containing snippets and folders arrays.
* 400:
* description: Invalid userId.
* 500:
* description: Failed to export snippets.
*/
router.get(
"/export",
authenticateJWT,
requireDataAccess,
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
if (!isNonEmptyString(userId)) {
authLogger.warn("Invalid userId for snippet export");
return res.status(400).json({ error: "Invalid userId" });
}
try {
const allSnippets = await db
.select()
.from(snippets)
.where(eq(snippets.userId, userId))
.orderBy(asc(snippets.folder), asc(snippets.order));
const allFolders = await db
.select()
.from(snippetFolders)
.where(eq(snippetFolders.userId, userId))
.orderBy(asc(snippetFolders.name));
const exportedSnippets = allSnippets.map((s) => ({
name: s.name,
content: s.content,
description: s.description,
folder: s.folder,
order: s.order,
hostFilter: s.hostFilter,
}));
const exportedFolders = allFolders.map((f) => ({
name: f.name,
color: f.color,
icon: f.icon,
}));
authLogger.success(`Snippets exported by user ${userId}`, {
operation: "snippet_export",
userId,
snippetCount: exportedSnippets.length,
folderCount: exportedFolders.length,
});
res.json({ snippets: exportedSnippets, folders: exportedFolders });
} catch (err) {
authLogger.error("Failed to export snippets", err);
res.status(500).json({ error: "Failed to export snippets" });
}
},
);
/**
* @openapi
* /snippets/bulk-import:
* post:
* summary: Bulk import snippets and folders from JSON
* description: Imports snippets and folders. Existing folders are skipped; existing snippets (matched by name+folder) can be skipped or overwritten.
* tags:
* - Snippets
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* snippets:
* type: array
* folders:
* type: array
* overwrite:
* type: boolean
* responses:
* 200:
* description: Import results with counts.
* 400:
* description: Invalid request body.
* 500:
* description: Failed to import snippets.
*/
router.post(
"/bulk-import",
authenticateJWT,
requireDataAccess,
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
const {
snippets: snippetsToImport,
folders: foldersToImport,
overwrite,
} = req.body;
if (!isNonEmptyString(userId)) {
return res.status(400).json({ error: "Invalid userId" });
}
if (!Array.isArray(snippetsToImport) && !Array.isArray(foldersToImport)) {
return res
.status(400)
.json({ error: "snippets or folders array is required" });
}
const results = {
snippetsImported: 0,
snippetsSkipped: 0,
snippetsUpdated: 0,
foldersImported: 0,
foldersSkipped: 0,
failed: 0,
errors: [] as string[],
};
try {
if (Array.isArray(foldersToImport)) {
for (const folder of foldersToImport) {
if (!isNonEmptyString(folder.name)) {
results.failed++;
results.errors.push(`Folder missing name`);
continue;
}
const existing = await db
.select()
.from(snippetFolders)
.where(
and(
eq(snippetFolders.userId, userId),
eq(snippetFolders.name, folder.name.trim()),
),
)
.limit(1);
if (existing.length > 0) {
results.foldersSkipped++;
continue;
}
await db.insert(snippetFolders).values({
userId,
name: folder.name.trim(),
color: folder.color?.trim() || null,
icon: folder.icon?.trim() || null,
});
results.foldersImported++;
}
}
if (Array.isArray(snippetsToImport)) {
for (let i = 0; i < snippetsToImport.length; i++) {
const s = snippetsToImport[i];
if (!isNonEmptyString(s.name) || !isNonEmptyString(s.content)) {
results.failed++;
results.errors.push(
`Snippet ${i + 1}: name and content are required`,
);
continue;
}
const folderVal = s.folder?.trim() || null;
const existing = await db
.select()
.from(snippets)
.where(
and(
eq(snippets.userId, userId),
eq(snippets.name, s.name.trim()),
folderVal
? eq(snippets.folder, folderVal)
: sql`(${snippets.folder} IS NULL OR ${snippets.folder} = '')`,
),
)
.limit(1);
if (existing.length > 0) {
if (!overwrite) {
results.snippetsSkipped++;
continue;
}
await db
.update(snippets)
.set({
content: s.content.trim(),
description: s.description?.trim() || null,
folder: folderVal,
order:
typeof s.order === "number" ? s.order : existing[0].order,
hostFilter: s.hostFilter || null,
updatedAt: sql`CURRENT_TIMESTAMP`,
})
.where(
and(
eq(snippets.id, existing[0].id),
eq(snippets.userId, userId),
),
);
results.snippetsUpdated++;
continue;
}
const maxOrderResult = await db
.select({ maxOrder: sql<number>`MAX(${snippets.order})` })
.from(snippets)
.where(
and(
eq(snippets.userId, userId),
folderVal
? eq(snippets.folder, folderVal)
: sql`(${snippets.folder} IS NULL OR ${snippets.folder} = '')`,
),
);
const maxOrder = maxOrderResult[0]?.maxOrder ?? -1;
await db.insert(snippets).values({
userId,
name: s.name.trim(),
content: s.content.trim(),
description: s.description?.trim() || null,
folder: folderVal,
order: typeof s.order === "number" ? s.order : maxOrder + 1,
hostFilter: s.hostFilter || null,
});
results.snippetsImported++;
}
}
authLogger.success(`Snippets bulk-imported by user ${userId}`, {
operation: "snippet_bulk_import",
userId,
...results,
});
res.json({ success: true, ...results });
} catch (err) {
authLogger.error("Failed to bulk import snippets", err);
res.status(500).json({ error: "Failed to import snippets" });
}
},
);
/**
* @openapi
* /snippets:
@@ -9,6 +9,7 @@ import { eq, asc } from "drizzle-orm";
import { authLogger } from "../../utils/logger.js";
import { AuthManager } from "../../utils/auth-manager.js";
import type { SSOProviderType } from "../../../types/index.js";
import { getOIDCConfigFromEnv } from "./user-oidc-utils.js";
const authManager = AuthManager.getInstance();
@@ -117,6 +118,16 @@ export function registerSSOProviderRoutes(router: Router): void {
.from(ssoProviders)
.where(eq(ssoProviders.enabled, true))
.orderBy(asc(ssoProviders.displayOrder), asc(ssoProviders.id));
// If no DB providers exist, synthesize one from env vars so SSO login
// remains available when configured purely via environment variables.
if (providers.length === 0) {
const envConfig = getOIDCConfigFromEnv();
if (envConfig) {
providers.push({ id: 0, name: "SSO", type: "oidc", displayOrder: 0 });
}
}
res.json(providers);
} catch (err) {
authLogger.error("Failed to list SSO providers", err);
@@ -1,10 +1,13 @@
import type { AuthenticatedRequest } from "../../../types/index.js";
import type { RequestHandler, Router } from "express";
import { eq } from "drizzle-orm";
import { eq, and } from "drizzle-orm";
import { authLogger } from "../../utils/logger.js";
import { db } from "../db/index.js";
import { users } from "../db/schema.js";
import { users, roles, userRoles } from "../db/schema.js";
import { logAudit, getRequestMeta } from "../../utils/audit-logger.js";
import bcrypt from "bcryptjs";
import { nanoid } from "nanoid";
import { AuthManager } from "../../utils/auth-manager.js";
function isNonEmptyString(val: unknown): val is string {
return typeof val === "string" && val.trim().length > 0;
@@ -139,6 +142,50 @@ export function registerUserAdminRoutes(
: eq(users.username, resolvedUsername!),
);
try {
const targetId = targetUser[0].id;
const adminRole = await db
.select({ id: roles.id })
.from(roles)
.where(eq(roles.name, "admin"))
.limit(1);
const userRole = await db
.select({ id: roles.id })
.from(roles)
.where(eq(roles.name, "user"))
.limit(1);
if (adminRole.length > 0) {
await db
.delete(userRoles)
.where(
and(
eq(userRoles.userId, targetId),
eq(userRoles.roleId, adminRole[0].id),
),
);
await db.insert(userRoles).values({
userId: targetId,
roleId: adminRole[0].id,
grantedBy: userId,
});
}
if (userRole.length > 0) {
await db
.delete(userRoles)
.where(
and(
eq(userRoles.userId, targetId),
eq(userRoles.roleId, userRole[0].id),
),
);
}
} catch (roleError) {
authLogger.error("Failed to sync admin role on make-admin", roleError, {
operation: "make_admin_role_sync",
userId: targetUser[0].id,
});
}
try {
const { saveMemoryDatabaseToFile } = await import("../db/index.js");
await saveMemoryDatabaseToFile();
@@ -277,6 +324,54 @@ export function registerUserAdminRoutes(
: eq(users.username, resolvedUsername!),
);
try {
const targetId = targetUser[0].id;
const adminRole = await db
.select({ id: roles.id })
.from(roles)
.where(eq(roles.name, "admin"))
.limit(1);
const userRole = await db
.select({ id: roles.id })
.from(roles)
.where(eq(roles.name, "user"))
.limit(1);
if (adminRole.length > 0) {
await db
.delete(userRoles)
.where(
and(
eq(userRoles.userId, targetId),
eq(userRoles.roleId, adminRole[0].id),
),
);
}
if (userRole.length > 0) {
await db
.delete(userRoles)
.where(
and(
eq(userRoles.userId, targetId),
eq(userRoles.roleId, userRole[0].id),
),
);
await db.insert(userRoles).values({
userId: targetId,
roleId: userRole[0].id,
grantedBy: userId,
});
}
} catch (roleError) {
authLogger.error(
"Failed to sync user role on remove-admin",
roleError,
{
operation: "remove_admin_role_sync",
userId: targetUser[0].id,
},
);
}
try {
const { saveMemoryDatabaseToFile } = await import("../db/index.js");
await saveMemoryDatabaseToFile();
@@ -321,4 +416,184 @@ export function registerUserAdminRoutes(
res.status(500).json({ error: "Failed to remove admin status" });
}
});
/**
* @openapi
* /users/admin-create:
* post:
* summary: Admin create user
* description: Allows an admin to create a new user regardless of whether public registration is enabled.
* tags:
* - Users
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* username:
* type: string
* password:
* type: string
* responses:
* 200:
* description: User created successfully.
* 400:
* description: Username and password are required.
* 403:
* description: Not authorized.
* 409:
* description: Username already exists.
* 500:
* description: Failed to create user.
*/
router.post("/admin-create", authenticateJWT, async (req, res) => {
const adminId = (req as AuthenticatedRequest).userId;
try {
const adminUser = await db
.select()
.from(users)
.where(eq(users.id, adminId));
if (!adminUser || adminUser.length === 0 || !adminUser[0].isAdmin) {
return res.status(403).json({ error: "Not authorized" });
}
} catch (err) {
authLogger.error("Failed to verify admin status", err);
return res.status(500).json({ error: "Failed to verify admin status" });
}
const { username, password } = req.body;
if (!isNonEmptyString(username) || !isNonEmptyString(password)) {
return res
.status(400)
.json({ error: "Username and password are required" });
}
try {
const existing = await db
.select()
.from(users)
.where(eq(users.username, username));
if (existing && existing.length > 0) {
return res.status(409).json({ error: "Username already exists" });
}
const password_hash = await bcrypt.hash(password, 10);
const id = nanoid();
db.$client.transaction(() => {
db.$client
.prepare(
"INSERT INTO users (id, username, password_hash, is_admin, is_oidc, client_id, client_secret, issuer_url, authorization_url, token_url, identifier_path, name_path, scopes, totp_secret, totp_enabled, totp_backup_codes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
)
.run(
id,
username,
password_hash,
0,
0,
"",
"",
"",
"",
"",
"",
"",
"openid email profile",
null,
0,
null,
);
})();
try {
const userRole = await db
.select({ id: roles.id })
.from(roles)
.where(eq(roles.name, "user"))
.limit(1);
if (userRole.length > 0) {
await db.insert(userRoles).values({
userId: id,
roleId: userRole[0].id,
grantedBy: adminId,
});
}
} catch (roleError) {
authLogger.error(
"Failed to assign default role during admin create",
roleError,
{
operation: "admin_create_user_role",
userId: id,
},
);
}
const authManager = AuthManager.getInstance();
try {
await authManager.registerUser(id, password);
} catch (encryptionError) {
await db.delete(users).where(eq(users.id, id));
authLogger.error(
"Failed to setup user encryption during admin create, rolled back",
encryptionError,
{ operation: "admin_create_user_encryption_failed", userId: id },
);
return res.status(500).json({
error: "Failed to setup user security - user creation cancelled",
});
}
try {
const { saveMemoryDatabaseToFile } = await import("../db/index.js");
await saveMemoryDatabaseToFile();
} catch (saveError) {
authLogger.error(
"Failed to persist admin-created user to disk",
saveError,
{
operation: "admin_create_user_save_failed",
userId: id,
},
);
}
authLogger.success("User created by admin", {
operation: "admin_create_user_success",
adminId,
userId: id,
username,
});
const { ipAddress, userAgent } = getRequestMeta(req);
const adminRecord = await db
.select({ username: users.username })
.from(users)
.where(eq(users.id, adminId))
.limit(1);
await logAudit({
userId: adminId,
username: adminRecord[0]?.username ?? adminId,
action: "create_user",
resourceType: "user",
resourceId: id,
resourceName: username,
ipAddress,
userAgent,
success: true,
});
res.json({
message: "User created",
toast: { type: "success", message: `User created: ${username}` },
});
} catch (err) {
authLogger.error("Failed to admin-create user", err);
res.status(500).json({ error: "Failed to create user" });
}
});
}
@@ -61,6 +61,23 @@ describe("isOIDCUserAllowed", () => {
it("does not match the email against an identifier-only pattern when email differs", () => {
expect(isOIDCUserAllowed("alice", "sub-123", "alice@x.com")).toBe(false);
});
it("matches *@domain.com wildcard pattern against emails", () => {
expect(
isOIDCUserAllowed("*@company.com", "sub-1", "john@company.com"),
).toBe(true);
expect(
isOIDCUserAllowed("*@company.com", "sub-1", "jane@COMPANY.COM"),
).toBe(true);
expect(isOIDCUserAllowed("*@company.com", "sub-1", "user@other.com")).toBe(
false,
);
});
it("matches glob patterns with multiple wildcards", () => {
expect(isOIDCUserAllowed("admin*", "admin_user")).toBe(true);
expect(isOIDCUserAllowed("admin*", "user_admin")).toBe(false);
});
});
describe("getOIDCConfigFromEnv", () => {
+75 -6
View File
@@ -4,6 +4,7 @@ import { db } from "../db/index.js";
import { ssoProviders } from "../db/schema.js";
import { eq } from "drizzle-orm";
import { DataCrypto } from "../../utils/data-crypto.js";
import { Agent } from "undici";
export type OIDCConfig = {
client_id: string;
@@ -18,8 +19,14 @@ export type OIDCConfig = {
allowed_users: string;
admin_group: string;
group_claim?: string;
ca_cert?: string;
};
export function buildFetchOptions(caCert?: string): Record<string, unknown> {
if (!caCert || !caCert.trim()) return {};
return { dispatcher: new Agent({ connect: { ca: caCert } }) };
}
export function getOIDCConfigFromEnv(): OIDCConfig | null {
const client_id = process.env.OIDC_CLIENT_ID;
const client_secret = process.env.OIDC_CLIENT_SECRET;
@@ -107,6 +114,15 @@ export function isOIDCUserAllowed(
];
for (const pattern of patterns) {
if (pattern === "*") return true;
if (pattern.includes("*")) {
const escaped = pattern
.toLowerCase()
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
.replace(/\*/g, ".*");
const regex = new RegExp(`^${escaped}$`);
if (values.some((v) => v && regex.test(v.toLowerCase()))) return true;
continue;
}
for (const value of values) {
if (!value) continue;
if (pattern.toLowerCase().startsWith("@")) {
@@ -123,7 +139,9 @@ export async function verifyOIDCToken(
idToken: string,
issuerUrl: string,
clientId: string,
caCert?: string,
): Promise<Record<string, unknown>> {
const fetchOptions = buildFetchOptions(caCert);
const normalizedIssuerUrl = issuerUrl.endsWith("/")
? issuerUrl.slice(0, -1)
: issuerUrl;
@@ -142,7 +160,7 @@ export async function verifyOIDCToken(
try {
const discoveryUrl = `${normalizedIssuerUrl}/.well-known/openid-configuration`;
const discoveryResponse = await fetch(discoveryUrl);
const discoveryResponse = await fetch(discoveryUrl, fetchOptions);
if (discoveryResponse.ok) {
const discovery = (await discoveryResponse.json()) as Record<
string,
@@ -160,7 +178,7 @@ export async function verifyOIDCToken(
for (const url of jwksUrls) {
try {
const response = await fetch(url);
const response = await fetch(url, fetchOptions);
if (response.ok) {
const jwksData = (await response.json()) as Record<string, unknown>;
if (jwksData && jwksData.keys && Array.isArray(jwksData.keys)) {
@@ -214,6 +232,49 @@ export async function verifyOIDCToken(
return payload;
}
const GOOGLE_DEFAULTS = {
issuer_url: "https://accounts.google.com",
authorization_url: "https://accounts.google.com/o/oauth2/v2/auth",
token_url: "https://oauth2.googleapis.com/token",
userinfo_url: "https://openidconnect.googleapis.com/v1/userinfo",
identifier_path: "sub",
name_path: "name",
scopes: "openid email profile",
};
const GITHUB_DEFAULTS = {
issuer_url: "https://token.actions.githubusercontent.com",
authorization_url: "https://github.com/login/oauth/authorize",
token_url: "https://github.com/login/oauth/access_token",
userinfo_url: "https://api.github.com/user",
identifier_path: "id",
name_path: "name",
scopes: "read:user user:email",
};
function applyProviderDefaults(
config: OIDCConfig,
providerType: string,
): OIDCConfig {
const defaults =
providerType === "google"
? GOOGLE_DEFAULTS
: providerType === "github"
? GITHUB_DEFAULTS
: null;
if (!defaults) return config;
return {
...config,
issuer_url: config.issuer_url || defaults.issuer_url,
authorization_url: config.authorization_url || defaults.authorization_url,
token_url: config.token_url || defaults.token_url,
userinfo_url: config.userinfo_url || defaults.userinfo_url,
identifier_path: config.identifier_path || defaults.identifier_path,
name_path: config.name_path || defaults.name_path,
scopes: config.scopes || defaults.scopes,
};
}
function decryptConfigSecret(
config: Record<string, unknown>,
): Record<string, unknown> {
@@ -280,10 +341,14 @@ export async function loadProviderConfig(
} else {
parsed = decryptConfigSecret(parsed);
}
const config = parsed as unknown as OIDCConfig;
const providerType = row.type as SSOProviderType;
const config = applyProviderDefaults(
parsed as unknown as OIDCConfig,
providerType,
);
return {
config,
providerType: row.type as SSOProviderType,
providerType,
providerDbId: row.id,
};
}
@@ -318,9 +383,13 @@ export async function loadProviderConfig(
parsed = {};
}
parsed = decryptConfigSecret(parsed);
const oidcProviderType = oidcRow.type as SSOProviderType;
return {
config: parsed as unknown as OIDCConfig,
providerType: oidcRow.type as SSOProviderType,
config: applyProviderDefaults(
parsed as unknown as OIDCConfig,
oidcProviderType,
),
providerType: oidcProviderType,
providerDbId: oidcRow.id,
};
}
@@ -63,12 +63,19 @@ export function registerUserPasswordResetRoutes(
*/
router.post("/initiate-reset", async (req, res) => {
try {
const row = db.$client
.prepare(
"SELECT value FROM settings WHERE key = 'allow_password_reset'",
)
.get();
if (row && (row as { value: string }).value !== "true") {
const envVal = process.env.ALLOW_PASSWORD_RESET;
const allowed =
envVal !== undefined
? envVal.trim().toLowerCase() === "true"
: (() => {
const row = db.$client
.prepare(
"SELECT value FROM settings WHERE key = 'allow_password_reset'",
)
.get();
return row ? (row as { value: string }).value === "true" : true;
})();
if (!allowed) {
return res
.status(403)
.json({ error: "Password reset is currently disabled" });
@@ -346,8 +353,7 @@ export function registerUserPasswordResetRoutes(
}
const userId = user[0].id;
const saltRounds = parseInt(process.env.SALT || "10", 10);
const password_hash = await bcrypt.hash(newPassword, saltRounds);
const password_hash = await bcrypt.hash(newPassword, 10);
let userIdFromJwt: string | null = null;
const cookie = req.cookies?.jwt;
@@ -17,7 +17,7 @@ const pickPreferences = (row?: typeof userPreferences.$inferSelect) => ({
fontSize: row?.fontSize ?? null,
accentColor: row?.accentColor ?? null,
language: row?.language ?? null,
storageMode: row?.storageMode ?? "local",
storageMode: row?.storageMode ?? "cloud",
commandAutocomplete: row?.commandAutocomplete ?? null,
commandPaletteEnabled: row?.commandPaletteEnabled ?? null,
showHostTags: row?.showHostTags ?? null,
@@ -28,6 +28,8 @@ const pickPreferences = (row?: typeof userPreferences.$inferSelect) => ({
disableUpdateCheck: row?.disableUpdateCheck ?? null,
confirmTabClose: row?.confirmTabClose ?? null,
hiddenRailTabs: row?.hiddenRailTabs ?? null,
compactHostView: row?.compactHostView ?? null,
statusColorScheme: row?.statusColorScheme ?? null,
});
/**
@@ -92,6 +94,12 @@ const pickPreferences = (row?: typeof userPreferences.$inferSelect) => ({
* hiddenRailTabs:
* type: string
* nullable: true
* compactHostView:
* type: boolean
* nullable: true
* statusColorScheme:
* type: string
* nullable: true
*/
router.get("/", authenticateJWT, (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
@@ -158,6 +166,10 @@ router.get("/", authenticateJWT, (req: Request, res: Response) => {
* type: boolean
* hiddenRailTabs:
* type: string
* compactHostView:
* type: boolean
* statusColorScheme:
* type: string
* responses:
* 200:
* description: Preferences updated successfully.
@@ -181,6 +193,8 @@ router.put("/", authenticateJWT, (req: Request, res: Response) => {
disableUpdateCheck,
confirmTabClose,
hiddenRailTabs,
compactHostView,
statusColorScheme,
} = req.body as {
reopenTabsOnLogin?: boolean;
theme?: string | null;
@@ -198,6 +212,8 @@ router.put("/", authenticateJWT, (req: Request, res: Response) => {
disableUpdateCheck?: boolean | null;
confirmTabClose?: boolean | null;
hiddenRailTabs?: string | null;
compactHostView?: boolean | null;
statusColorScheme?: string | null;
};
const updates: Partial<typeof userPreferences.$inferInsert> = {
@@ -220,6 +236,7 @@ router.put("/", authenticateJWT, (req: Request, res: Response) => {
language,
storageMode,
hiddenRailTabs,
statusColorScheme,
})) {
if (value !== undefined && value !== null && typeof value !== "string") {
return res.status(400).json({ error: `${key} must be a string` });
@@ -236,6 +253,7 @@ router.put("/", authenticateJWT, (req: Request, res: Response) => {
confirmSnippetExecution,
disableUpdateCheck,
confirmTabClose,
compactHostView,
};
for (const [key, value] of Object.entries(boolFields)) {
if (value !== undefined && value !== null && typeof value !== "boolean") {
@@ -263,6 +281,9 @@ router.put("/", authenticateJWT, (req: Request, res: Response) => {
if (disableUpdateCheck !== undefined)
updates.disableUpdateCheck = disableUpdateCheck;
if (confirmTabClose !== undefined) updates.confirmTabClose = confirmTabClose;
if (compactHostView !== undefined) updates.compactHostView = compactHostView;
if (statusColorScheme !== undefined)
updates.statusColorScheme = statusColorScheme;
if (Object.keys(updates).length === 1) {
return res.status(400).json({ error: "No preferences provided" });
@@ -15,6 +15,24 @@ function getDefaultGuacUrl(): string {
return `${process.env.GUACD_HOST || "localhost"}:${process.env.GUACD_PORT || "4822"}`;
}
export type HostDefaults = {
useSocks5?: boolean;
socks5Host?: string;
socks5Port?: number;
socks5Username?: string;
socks5Password?: string;
credentialId?: number | null;
metricsEnabled?: boolean;
statusCheckEnabled?: boolean;
fontSize?: number;
fontFamily?: string;
theme?: string;
cursorStyle?: string;
cursorBlink?: boolean;
enableSessionLogging?: boolean;
enableCommandHistory?: boolean;
};
export function registerUserSettingsRoutes(
router: Router,
authenticateJWT: RequestHandler,
@@ -544,4 +562,91 @@ export function registerUserSettingsRoutes(
}
},
);
/**
* @openapi
* /users/host-defaults:
* get:
* summary: Get host creation defaults
* description: Returns the global default settings applied when creating a new host.
* tags:
* - Users
* responses:
* 200:
* description: Host defaults object.
* 500:
* description: Failed to get host defaults.
*/
router.get("/host-defaults", authenticateJWT, async (_req, res) => {
try {
const row = db.$client
.prepare("SELECT value FROM settings WHERE key = 'host_defaults'")
.get() as { value: string } | undefined;
const defaults: HostDefaults = row ? JSON.parse(row.value) : {};
res.json(defaults);
} catch (err) {
authLogger.error("Failed to get host defaults", err);
res.status(500).json({ error: "Failed to get host defaults" });
}
});
/**
* @openapi
* /users/host-defaults:
* patch:
* summary: Update host creation defaults (admin only)
* description: Sets global default settings applied when a new host is created.
* tags:
* - Users
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* responses:
* 200:
* description: Host defaults updated.
* 403:
* description: Not authorized.
* 500:
* description: Failed to update host defaults.
*/
router.patch("/host-defaults", authenticateJWT, async (req, res) => {
const userId = (req as AuthenticatedRequest).userId;
try {
const user = await db.select().from(users).where(eq(users.id, userId));
if (!user || user.length === 0 || !user[0].isAdmin) {
return res.status(403).json({ error: "Not authorized" });
}
const defaults: HostDefaults = req.body;
db.$client
.prepare(
"INSERT OR REPLACE INTO settings (key, value) VALUES ('host_defaults', ?)",
)
.run(JSON.stringify(defaults));
const { ipAddress, userAgent } = getRequestMeta(req);
const actorRecord = await db
.select({ username: users.username })
.from(users)
.where(eq(users.id, userId))
.limit(1);
await logAudit({
userId,
username: actorRecord[0]?.username ?? userId,
action: "update_host_defaults",
resourceType: "setting",
details: JSON.stringify(defaults),
ipAddress,
userAgent,
success: true,
});
res.json(defaults);
} catch (err) {
authLogger.error("Failed to update host defaults", err);
res.status(500).json({ error: "Failed to update host defaults" });
}
});
}
+102 -17
View File
@@ -5,6 +5,7 @@ import bcrypt from "bcryptjs";
import QRCode from "qrcode";
import speakeasy from "speakeasy";
import { AuthManager } from "../../utils/auth-manager.js";
import { FieldCrypto } from "../../utils/field-crypto.js";
import { LazyFieldEncryption } from "../../utils/lazy-field-encryption.js";
import { authLogger } from "../../utils/logger.js";
import { loginRateLimiter } from "../../utils/login-rate-limiter.js";
@@ -28,6 +29,7 @@ type TotpUserRecord = typeof users.$inferSelect;
export async function verifyTotpReauth(
userRecord: TotpUserRecord,
credential: string,
userDataKey?: Buffer | null,
): Promise<boolean> {
if (!userRecord.isOidc && userRecord.passwordHash) {
const passwordMatch = await bcrypt.compare(
@@ -40,22 +42,41 @@ export async function verifyTotpReauth(
}
if (userRecord.totpSecret) {
const totpMatch = speakeasy.totp.verify({
secret: userRecord.totpSecret,
encoding: "base32",
token: credential,
window: 2,
});
if (totpMatch) {
return true;
const totpSecret = userDataKey
? LazyFieldEncryption.safeGetFieldValue(
userRecord.totpSecret,
userDataKey,
userRecord.id,
"totpSecret",
)
: userRecord.totpSecret;
if (totpSecret) {
const totpMatch = speakeasy.totp.verify({
secret: totpSecret,
encoding: "base32",
token: credential,
window: 2,
});
if (totpMatch) {
return true;
}
}
}
const rawBackupCodes =
userDataKey && userRecord.totpBackupCodes
? LazyFieldEncryption.safeGetFieldValue(
userRecord.totpBackupCodes,
userDataKey,
userRecord.id,
"totpBackupCodes",
)
: userRecord.totpBackupCodes;
let backupCodes: unknown = [];
try {
backupCodes = userRecord.totpBackupCodes
? JSON.parse(userRecord.totpBackupCodes)
: [];
backupCodes = rawBackupCodes ? JSON.parse(rawBackupCodes) : [];
} catch {
backupCodes = [];
}
@@ -63,9 +84,18 @@ export async function verifyTotpReauth(
const backupIndex = backupCodes.indexOf(credential);
if (backupIndex !== -1) {
backupCodes.splice(backupIndex, 1);
const updatedJson = JSON.stringify(backupCodes);
const storedValue = userDataKey
? FieldCrypto.encryptField(
updatedJson,
userDataKey,
userRecord.id,
"totpBackupCodes",
)
: updatedJson;
await db
.update(users)
.set({ totpBackupCodes: JSON.stringify(backupCodes) })
.set({ totpBackupCodes: storedValue })
.where(eq(users.id, userRecord.id));
return true;
}
@@ -172,6 +202,21 @@ export function registerUserTotpRoutes(
}
try {
const passwordLoginRow = db.$client
.prepare(
"SELECT value FROM settings WHERE key = 'allow_password_login'",
)
.get() as { value: string } | undefined;
const passwordLoginAllowed = passwordLoginRow
? passwordLoginRow.value === "true"
: true;
if (!passwordLoginAllowed) {
return res.status(409).json({
error:
"Cannot enable 2FA while password login is disabled. Enable password login first.",
});
}
const user = await db.select().from(users).where(eq(users.id, userId));
if (!user || user.length === 0) {
return res.status(404).json({ error: "User not found" });
@@ -187,8 +232,18 @@ export function registerUserTotpRoutes(
return res.status(400).json({ error: "TOTP setup not initiated" });
}
const userDataKey = authManager.getUserDataKey(userId);
const totpSecret = userDataKey
? LazyFieldEncryption.safeGetFieldValue(
userRecord.totpSecret,
userDataKey,
userId,
"totpSecret",
)
: userRecord.totpSecret;
const verified = speakeasy.totp.verify({
secret: userRecord.totpSecret,
secret: totpSecret,
encoding: "base32",
token: totp_code,
window: 2,
@@ -202,11 +257,21 @@ export function registerUserTotpRoutes(
Math.random().toString(36).substring(2, 10).toUpperCase(),
);
const backupCodesJson = JSON.stringify(backupCodes);
const storedBackupCodes = userDataKey
? FieldCrypto.encryptField(
backupCodesJson,
userDataKey,
userId,
"totpBackupCodes",
)
: backupCodesJson;
await db
.update(users)
.set({
totpEnabled: true,
totpBackupCodes: JSON.stringify(backupCodes),
totpBackupCodes: storedBackupCodes,
})
.where(eq(users.id, userId));
@@ -297,7 +362,12 @@ export function registerUserTotpRoutes(
return res.status(400).json({ error: "TOTP is not enabled" });
}
const verified = await verifyTotpReauth(userRecord, credential);
const userDataKey = authManager.getUserDataKey(userId);
const verified = await verifyTotpReauth(
userRecord,
credential,
userDataKey,
);
if (!verified) {
return res
.status(401)
@@ -378,7 +448,12 @@ export function registerUserTotpRoutes(
return res.status(400).json({ error: "TOTP is not enabled" });
}
const verified = await verifyTotpReauth(userRecord, credential);
const userDataKey = authManager.getUserDataKey(userId);
const verified = await verifyTotpReauth(
userRecord,
credential,
userDataKey,
);
if (!verified) {
return res
.status(401)
@@ -389,9 +464,19 @@ export function registerUserTotpRoutes(
Math.random().toString(36).substring(2, 10).toUpperCase(),
);
const backupCodesJson = JSON.stringify(backupCodes);
const storedBackupCodes = userDataKey
? FieldCrypto.encryptField(
backupCodesJson,
userDataKey,
userId,
"totpBackupCodes",
)
: backupCodesJson;
await db
.update(users)
.set({ totpBackupCodes: JSON.stringify(backupCodes) })
.set({ totpBackupCodes: storedBackupCodes })
.where(eq(users.id, userId));
res.json({ backup_codes: backupCodes });
+224 -91
View File
@@ -2,7 +2,7 @@ import type { AuthenticatedRequest } from "../../../types/index.js";
import express from "express";
import { db } from "../db/index.js";
import { users, settings, roles, userRoles } from "../db/schema.js";
import { eq } from "drizzle-orm";
import { eq, and } from "drizzle-orm";
import bcrypt from "bcryptjs";
import { nanoid } from "nanoid";
import type { Request, Response } from "express";
@@ -22,9 +22,11 @@ import {
verifyOIDCToken,
extractOidcGroups,
loadProviderConfig,
buildFetchOptions,
} from "./user-oidc-utils.js";
import { registerUserApiKeyRoutes } from "./user-api-key-routes.js";
import { registerUserSettingsRoutes } from "./user-settings-routes.js";
import { registerAcmeSSLRoutes } from "./acme-ssl-routes.js";
import { registerUserTotpRoutes } from "./user-totp-routes.js";
import { registerUserSessionRoutes } from "./user-session-routes.js";
import { registerUserOidcAccountRoutes } from "./user-oidc-account-routes.js";
@@ -43,6 +45,45 @@ function isNonEmptyString(val: unknown): val is string {
return typeof val === "string" && val.trim().length > 0;
}
function isRegistrationAllowed(): boolean {
const envVal = process.env.ALLOW_REGISTRATION;
if (envVal !== undefined) return envVal.trim().toLowerCase() === "true";
try {
const row = db.$client
.prepare("SELECT value FROM settings WHERE key = 'allow_registration'")
.get() as { value: string } | undefined;
return row ? row.value === "true" : true;
} catch {
return true;
}
}
function isPasswordLoginAllowed(): boolean {
const envVal = process.env.ALLOW_PASSWORD_LOGIN;
if (envVal !== undefined) return envVal.trim().toLowerCase() === "true";
try {
const row = db.$client
.prepare("SELECT value FROM settings WHERE key = 'allow_password_login'")
.get() as { value: string } | undefined;
return row ? row.value === "true" : true;
} catch {
return true;
}
}
function isPasswordResetAllowed(): boolean {
const envVal = process.env.ALLOW_PASSWORD_RESET;
if (envVal !== undefined) return envVal.trim().toLowerCase() === "true";
try {
const row = db.$client
.prepare("SELECT value FROM settings WHERE key = 'allow_password_reset'")
.get() as { value: string } | undefined;
return row ? row.value === "true" : true;
} catch {
return true;
}
}
function isNativeAppRequest(req: Request): boolean {
return (
(req.get("User-Agent") || "").startsWith("Termix-Mobile/") ||
@@ -85,20 +126,10 @@ const requireAdmin = authManager.createAdminMiddleware();
* description: Failed to create user.
*/
router.post("/create", async (req, res) => {
try {
const row = db.$client
.prepare("SELECT value FROM settings WHERE key = 'allow_registration'")
.get();
if (row && (row as Record<string, unknown>).value !== "true") {
return res
.status(403)
.json({ error: "Registration is currently disabled" });
}
} catch (e) {
authLogger.warn("Failed to check registration status", {
operation: "registration_check",
error: e,
});
if (!isRegistrationAllowed()) {
return res
.status(403)
.json({ error: "Registration is currently disabled" });
}
const { username, password } = req.body;
@@ -135,8 +166,7 @@ router.post("/create", async (req, res) => {
return res.status(409).json({ error: "Username already exists" });
}
const saltRounds = parseInt(process.env.SALT || "10", 10);
const password_hash = await bcrypt.hash(password, saltRounds);
const password_hash = await bcrypt.hash(password, 10);
const id = nanoid();
const isFirstUser = db.$client.transaction(() => {
@@ -737,6 +767,9 @@ router.get("/oidc/callback", async (req, res) => {
.run(`oidc_provider_${state}`);
}
const caCert = config.ca_cert;
const fetchOptions = buildFetchOptions(caCert);
// GitHub does not issue OIDC id_tokens; handle its token exchange separately
if (callbackProviderType === "github") {
const ghTokenResponse = await fetch(config.token_url, {
@@ -752,6 +785,7 @@ router.get("/oidc/callback", async (req, res) => {
code: code,
redirect_uri: backendCallbackUri,
}),
...fetchOptions,
});
if (!ghTokenResponse.ok) {
@@ -789,6 +823,7 @@ router.get("/oidc/callback", async (req, res) => {
Accept: "application/json",
"User-Agent": "Termix",
},
...fetchOptions,
});
if (!ghUserInfoResponse.ok) {
return res
@@ -859,16 +894,9 @@ router.get("/oidc/callback", async (req, res) => {
"true";
if (!isFirstUser && !ghAutoProvision) {
const regRow = db.$client
.prepare(
"SELECT value FROM settings WHERE key = 'allow_registration'",
)
.get() as { value: string } | undefined;
if (regRow && regRow.value !== "true") {
const redirectUrl = new URL(frontendOrigin);
redirectUrl.searchParams.set("error", "registration_disabled");
return res.redirect(redirectUrl.toString());
}
const redirectUrl = new URL(frontendOrigin);
redirectUrl.searchParams.set("error", "registration_disabled");
return res.redirect(redirectUrl.toString());
}
const ghId = nanoid();
@@ -972,7 +1000,6 @@ router.get("/oidc/callback", async (req, res) => {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
Authorization: `Basic ${Buffer.from(`${encodeURIComponent(config.client_id)}:${encodeURIComponent(config.client_secret)}`).toString("base64")}`,
},
body: new URLSearchParams({
grant_type: "authorization_code",
@@ -981,6 +1008,7 @@ router.get("/oidc/callback", async (req, res) => {
code: code,
redirect_uri: backendCallbackUri,
}),
...fetchOptions,
});
if (!tokenResponse.ok) {
@@ -1023,7 +1051,7 @@ router.get("/oidc/callback", async (req, res) => {
try {
const discoveryUrl = `${normalizedIssuerUrl}/.well-known/openid-configuration`;
const discoveryResponse = await fetch(discoveryUrl);
const discoveryResponse = await fetch(discoveryUrl, fetchOptions);
if (discoveryResponse.ok) {
const discovery = (await discoveryResponse.json()) as Record<
string,
@@ -1058,6 +1086,7 @@ router.get("/oidc/callback", async (req, res) => {
tokenData.id_token as string,
config.issuer_url,
config.client_id,
caCert,
);
} catch {
try {
@@ -1081,6 +1110,7 @@ router.get("/oidc/callback", async (req, res) => {
headers: {
Authorization: `Bearer ${tokenData.access_token}`,
},
...fetchOptions,
});
if (userInfoResponse.ok) {
@@ -1190,33 +1220,17 @@ router.get("/oidc/callback", async (req, res) => {
}
if (!isFirstUser && !oidcAutoProvision) {
try {
const regRow = db.$client
.prepare(
"SELECT value FROM settings WHERE key = 'allow_registration'",
)
.get();
if (regRow && (regRow as Record<string, unknown>).value !== "true") {
authLogger.warn(
"OIDC user attempted to register when registration is disabled",
{
operation: "oidc_registration_disabled",
identifier,
name,
},
);
const redirectUrl = new URL(frontendOrigin);
redirectUrl.searchParams.set("error", "registration_disabled");
return res.redirect(redirectUrl.toString());
}
} catch (e) {
authLogger.warn("Failed to check registration status during OIDC", {
operation: "oidc_registration_check",
error: e,
});
}
authLogger.warn(
"OIDC user attempted to register but auto-provisioning is disabled",
{
operation: "oidc_registration_disabled",
identifier,
name,
},
);
const redirectUrl = new URL(frontendOrigin);
redirectUrl.searchParams.set("error", "registration_disabled");
return res.redirect(redirectUrl.toString());
}
const id = nanoid();
@@ -1367,6 +1381,39 @@ router.get("/oidc/callback", async (req, res) => {
.set({ isAdmin: shouldBeAdmin })
.where(eq(users.id, userRecord.id));
userRecord.isAdmin = shouldBeAdmin;
try {
const newRoleName = shouldBeAdmin ? "admin" : "user";
const oldRoleName = shouldBeAdmin ? "user" : "admin";
const newRole = await db
.select({ id: roles.id })
.from(roles)
.where(eq(roles.name, newRoleName))
.limit(1);
const oldRole = await db
.select({ id: roles.id })
.from(roles)
.where(eq(roles.name, oldRoleName))
.limit(1);
if (oldRole.length > 0) {
await db
.delete(userRoles)
.where(
and(
eq(userRoles.userId, userRecord.id),
eq(userRoles.roleId, oldRole[0].id),
),
);
}
if (newRole.length > 0) {
await db.insert(userRoles).values({
userId: userRecord.id,
roleId: newRole[0].id,
grantedBy: userRecord.id,
});
}
} catch {
/* non-fatal */
}
authLogger.info("OIDC admin status synced", {
operation: "oidc_admin_group_sync",
userId: userRecord.id,
@@ -1504,21 +1551,10 @@ router.post("/login", async (req, res) => {
});
}
try {
const row = db.$client
.prepare("SELECT value FROM settings WHERE key = 'allow_password_login'")
.get();
if (row && (row as { value: string }).value !== "true") {
return res
.status(403)
.json({ error: "Password authentication is currently disabled" });
}
} catch (e) {
authLogger.error("Failed to check password login status", {
operation: "login_check",
error: e,
});
return res.status(500).json({ error: "Failed to check login status" });
if (!isPasswordLoginAllowed()) {
return res
.status(403)
.json({ error: "Password authentication is currently disabled" });
}
try {
@@ -1919,12 +1955,7 @@ router.get("/db-health", requireAdmin, async (req, res) => {
*/
router.get("/registration-allowed", async (req, res) => {
try {
const row = db.$client
.prepare("SELECT value FROM settings WHERE key = 'allow_registration'")
.get();
res.json({
allowed: row ? (row as Record<string, unknown>).value === "true" : true,
});
res.json({ allowed: isRegistrationAllowed() });
} catch (err) {
authLogger.error("Failed to get registration allowed", err);
res.status(500).json({ error: "Failed to get registration allowed" });
@@ -2029,6 +2060,107 @@ router.patch("/oidc-auto-provision", authenticateJWT, async (req, res) => {
}
});
/**
* @openapi
* /users/oidc-silent-login-default:
* get:
* summary: Get OIDC silent login default setting
* description: Returns whether silent OIDC login is enabled as the default behavior.
* tags:
* - Users
* responses:
* 200:
* description: Silent login default setting.
* 500:
* description: Failed to get setting.
*/
router.get("/oidc-silent-login-default", async (_req, res) => {
try {
const row = db.$client
.prepare(
"SELECT value FROM settings WHERE key = 'oidc_silent_login_default'",
)
.get();
res.json({
enabled: row ? (row as Record<string, unknown>).value === "true" : false,
});
} catch (err) {
authLogger.error("Failed to get OIDC silent login default", err);
res.status(500).json({ error: "Failed to get OIDC silent login default" });
}
});
/**
* @openapi
* /users/oidc-silent-login-default:
* patch:
* summary: Set OIDC silent login default setting
* description: Enables or disables silent OIDC login as the default behavior on the login page.
* tags:
* - Users
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* enabled:
* type: boolean
* responses:
* 200:
* description: Setting updated.
* 400:
* description: Invalid value.
* 403:
* description: Not authorized.
* 500:
* description: Failed to update setting.
*/
router.patch(
"/oidc-silent-login-default",
authenticateJWT,
async (req, res) => {
const userId = (req as AuthenticatedRequest).userId;
try {
const user = await db.select().from(users).where(eq(users.id, userId));
if (!user || user.length === 0 || !user[0].isAdmin) {
return res.status(403).json({ error: "Not authorized" });
}
const { enabled } = req.body;
if (typeof enabled !== "boolean") {
return res.status(400).json({ error: "Invalid value for enabled" });
}
const existing = db.$client
.prepare(
"SELECT value FROM settings WHERE key = 'oidc_silent_login_default'",
)
.get();
if (existing) {
db.$client
.prepare(
"UPDATE settings SET value = ? WHERE key = 'oidc_silent_login_default'",
)
.run(enabled ? "true" : "false");
} else {
db.$client
.prepare(
"INSERT INTO settings (key, value) VALUES ('oidc_silent_login_default', ?)",
)
.run(enabled ? "true" : "false");
}
const { saveMemoryDatabaseToFile } = await import("../db/index.js");
await saveMemoryDatabaseToFile();
res.json({ enabled });
} catch (err) {
authLogger.error("Failed to set OIDC silent login default", err);
res
.status(500)
.json({ error: "Failed to set OIDC silent login default" });
}
},
);
/**
* @openapi
* /users/password-login-allowed:
@@ -2045,12 +2177,7 @@ router.patch("/oidc-auto-provision", authenticateJWT, async (req, res) => {
*/
router.get("/password-login-allowed", async (req, res) => {
try {
const row = db.$client
.prepare("SELECT value FROM settings WHERE key = 'allow_password_login'")
.get();
res.json({
allowed: row ? (row as { value: string }).value === "true" : true,
});
res.json({ allowed: isPasswordLoginAllowed() });
} catch (err) {
authLogger.error("Failed to get password login allowed", err);
res.status(500).json({ error: "Failed to get password login allowed" });
@@ -2095,6 +2222,17 @@ router.patch("/password-login-allowed", authenticateJWT, async (req, res) => {
if (typeof allowed !== "boolean") {
return res.status(400).json({ error: "Invalid value for allowed" });
}
if (!allowed) {
const totpRow = db.$client
.prepare("SELECT COUNT(*) as count FROM users WHERE totp_enabled = 1")
.get() as { count?: number };
if ((totpRow?.count || 0) > 0) {
return res.status(409).json({
error:
"Cannot disable password login while 2FA is enabled for one or more users. Disable 2FA first.",
});
}
}
db.$client
.prepare(
"INSERT OR REPLACE INTO settings (key, value) VALUES ('allow_password_login', ?)",
@@ -2125,12 +2263,7 @@ router.patch("/password-login-allowed", authenticateJWT, async (req, res) => {
*/
router.get("/password-reset-allowed", async (req, res) => {
try {
const row = db.$client
.prepare("SELECT value FROM settings WHERE key = 'allow_password_reset'")
.get();
res.json({
allowed: row ? (row as { value: string }).value === "true" : true,
});
res.json({ allowed: isPasswordResetAllowed() });
} catch (err) {
authLogger.error("Failed to get password reset allowed", err);
res.status(500).json({ error: "Failed to get password reset allowed" });
@@ -2347,8 +2480,7 @@ router.post("/change-password", authenticateJWT, async (req, res) => {
.json({ error: "Failed to update password and re-encrypt data." });
}
const saltRounds = parseInt(process.env.SALT || "10", 10);
const password_hash = await bcrypt.hash(newPassword, saltRounds);
const password_hash = await bcrypt.hash(newPassword, 10);
await db
.update(users)
.set({ passwordHash: password_hash })
@@ -2518,6 +2650,7 @@ registerUserOidcAccountRoutes(router, {
});
registerUserSettingsRoutes(router, authenticateJWT);
registerAcmeSSLRoutes(router, authenticateJWT);
registerUserApiKeyRoutes(router, requireAdmin);
+147 -3
View File
@@ -5,8 +5,8 @@ import { AuthManager } from "../utils/auth-manager.js";
import { PermissionManager } from "../utils/permission-manager.js";
import { SimpleDBOps } from "../utils/simple-db-ops.js";
import { getDb } from "../database/db/index.js";
import { hosts } from "../database/db/schema.js";
import { eq } from "drizzle-orm";
import { hosts, sshCredentials } from "../database/db/schema.js";
import { eq, and } from "drizzle-orm";
import { Client } from "ssh2";
import net from "net";
import type { AuthenticatedRequest } from "../../types/index.js";
@@ -67,9 +67,15 @@ router.use(authManager.createAuthMiddleware());
*/
router.post("/token", async (req, res) => {
try {
const { type, hostname, port, username, password, domain, ...options } =
const { type, hostname, port, username, password, domain, ...rawOptions } =
req.body;
// Strip "auto" sentinel values before forwarding to guacd
const options: Record<string, unknown> = {};
for (const [key, value] of Object.entries(rawOptions)) {
if (value !== "auto") options[key] = value;
}
if (!type || !hostname) {
return res
.status(400)
@@ -261,12 +267,138 @@ router.post(
}
}
// Strip "auto" sentinel values — these mean "use guacd default" in the UI
// but guacd doesn't recognise "auto" as a valid parameter value.
for (const key of Object.keys(guacConfig)) {
if (guacConfig[key] === "auto") {
delete guacConfig[key];
}
}
// Extract per-connection guacd proxy settings before passing the rest as connection settings
const perConnectionGuacdHost = guacConfig["guacd-hostname"] as
| string
| undefined;
const perConnectionGuacdPortRaw = guacConfig["guacd-port"];
const perConnectionGuacdPort = perConnectionGuacdPortRaw
? parseInt(String(perConnectionGuacdPortRaw), 10) || undefined
: undefined;
delete guacConfig["guacd-hostname"];
delete guacConfig["guacd-port"];
if (guacConfig.dpi != null) {
const parsed = parseInt(String(guacConfig.dpi), 10);
guacConfig.dpi =
Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
}
const hostRecord = host as Record<string, unknown>;
// Backward compat: if authType is not stored but a credentialId is, treat as credential mode
const rdpEffectiveAuthType =
(host.rdpAuthType as string) ||
(host.rdpCredentialId ? "credential" : "direct");
const vncEffectiveAuthType =
(host.vncAuthType as string) ||
(host.vncCredentialId ? "credential" : "direct");
const telnetEffectiveAuthType =
(host.telnetAuthType as string) ||
(hostRecord.telnetCredentialId ? "credential" : "direct");
if (rdpEffectiveAuthType === "credential" && host.rdpCredentialId) {
try {
const rdpCreds = await SimpleDBOps.select(
getDb()
.select()
.from(sshCredentials)
.where(
and(
eq(sshCredentials.id, host.rdpCredentialId as number),
eq(sshCredentials.userId, host.userId as string),
),
),
"ssh_credentials",
userId,
);
if (rdpCreds.length > 0) {
const cred = rdpCreds[0] as Record<string, unknown>;
if (cred.username) host.rdpUser = cred.username;
if (cred.password) host.rdpPassword = cred.password;
// domain is never sourced from credential
}
} catch (e) {
guacLogger.warn("Failed to resolve RDP credential", {
operation: "guac_rdp_credential_resolve",
hostId,
error: e instanceof Error ? e.message : "Unknown",
});
}
}
if (vncEffectiveAuthType === "credential" && host.vncCredentialId) {
try {
const vncCreds = await SimpleDBOps.select(
getDb()
.select()
.from(sshCredentials)
.where(
and(
eq(sshCredentials.id, host.vncCredentialId as number),
eq(sshCredentials.userId, host.userId as string),
),
),
"ssh_credentials",
userId,
);
if (vncCreds.length > 0) {
const cred = vncCreds[0] as Record<string, unknown>;
if (cred.password) host.vncPassword = cred.password;
if (cred.username) host.vncUser = cred.username;
}
} catch (e) {
guacLogger.warn("Failed to resolve VNC credential", {
operation: "guac_vnc_credential_resolve",
hostId,
error: e instanceof Error ? e.message : "Unknown",
});
}
}
if (
telnetEffectiveAuthType === "credential" &&
hostRecord.telnetCredentialId
) {
try {
const telnetCreds = await SimpleDBOps.select(
getDb()
.select()
.from(sshCredentials)
.where(
and(
eq(
sshCredentials.id,
hostRecord.telnetCredentialId as number,
),
eq(sshCredentials.userId, host.userId as string),
),
),
"ssh_credentials",
userId,
);
if (telnetCreds.length > 0) {
const cred = telnetCreds[0] as Record<string, unknown>;
if (cred.username) host.telnetUser = cred.username;
if (cred.password) host.telnetPassword = cred.password;
}
} catch (e) {
guacLogger.warn("Failed to resolve Telnet credential", {
operation: "guac_telnet_credential_resolve",
hostId,
error: e instanceof Error ? e.message : "Unknown",
});
}
}
let token: string;
let hostname = host.ip as string;
let port = host.port as number;
@@ -385,6 +517,15 @@ router.post(
}
}
const guacdOverrides = {
...(perConnectionGuacdHost
? { guacdHost: perConnectionGuacdHost }
: {}),
...(perConnectionGuacdPort
? { guacdPort: perConnectionGuacdPort }
: {}),
};
switch (connectionType) {
case "rdp":
if (guacConfig["enable-drive"] && !guacConfig["drive-path"]) {
@@ -405,6 +546,7 @@ router.post(
? !!host.ignoreCert
: true,
...guacConfig,
...guacdOverrides,
});
break;
case "vnc":
@@ -416,6 +558,7 @@ router.post(
port,
security: "any",
...guacConfig,
...guacdOverrides,
},
);
break;
@@ -423,6 +566,7 @@ router.post(
token = tokenService.createTelnetToken(hostname, username, password, {
port,
...guacConfig,
...guacdOverrides,
});
break;
default:
+28 -8
View File
@@ -3,6 +3,8 @@ import { guacLogger } from "../utils/logger.js";
export interface GuacamoleConnectionSettings {
type: "rdp" | "vnc" | "telnet";
guacdHost?: string;
guacdPort?: number;
settings: {
hostname: string;
port?: number;
@@ -120,18 +122,24 @@ export class GuacamoleTokenService {
hostname: string,
username: string,
password: string,
options: Partial<GuacamoleConnectionSettings["settings"]> = {},
options: Partial<GuacamoleConnectionSettings["settings"]> & {
guacdHost?: string;
guacdPort?: number;
} = {},
): string {
const { guacdHost, guacdPort, ...settingsOptions } = options;
const token: GuacamoleToken = {
connection: {
type: "rdp",
...(guacdHost ? { guacdHost } : {}),
...(guacdPort ? { guacdPort } : {}),
settings: {
hostname,
username,
password,
...(username ? { username } : {}),
...(password ? { password } : {}),
port: 3389,
"ignore-cert": true,
...options,
...settingsOptions,
},
},
};
@@ -142,17 +150,23 @@ export class GuacamoleTokenService {
hostname: string,
username?: string,
password?: string,
options: Partial<GuacamoleConnectionSettings["settings"]> = {},
options: Partial<GuacamoleConnectionSettings["settings"]> & {
guacdHost?: string;
guacdPort?: number;
} = {},
): string {
const { guacdHost, guacdPort, ...settingsOptions } = options;
const token: GuacamoleToken = {
connection: {
type: "vnc",
...(guacdHost ? { guacdHost } : {}),
...(guacdPort ? { guacdPort } : {}),
settings: {
hostname,
...(username ? { username } : {}),
password,
port: 5900,
...options,
...settingsOptions,
},
},
};
@@ -163,17 +177,23 @@ export class GuacamoleTokenService {
hostname: string,
username?: string,
password?: string,
options: Partial<GuacamoleConnectionSettings["settings"]> = {},
options: Partial<GuacamoleConnectionSettings["settings"]> & {
guacdHost?: string;
guacdPort?: number;
} = {},
): string {
const { guacdHost, guacdPort, ...settingsOptions } = options;
const token: GuacamoleToken = {
connection: {
type: "telnet",
...(guacdHost ? { guacdHost } : {}),
...(guacdPort ? { guacdPort } : {}),
settings: {
hostname,
username,
password,
port: 23,
...options,
...settingsOptions,
},
},
};
+36 -4
View File
@@ -23,6 +23,7 @@ interface HostConfig {
keyPassword?: string;
keyType?: string;
authType?: string;
useWarpgate?: boolean;
credentialId?: number;
userId?: string;
forceKeyboardInteractive?: boolean;
@@ -112,6 +113,7 @@ export class SSHAuthManager {
prompts: Array<{ prompt: string; echo: boolean }>,
finish: (responses: string[]) => void,
resolvedCredentials: ResolvedCredentials,
hostConfig?: HostConfig,
): void {
this.context.isKeyboardInteractive = true;
const promptTexts = prompts.map((p) => p.prompt);
@@ -143,7 +145,7 @@ export class SSHAuthManager {
return;
}
this.handlePasswordAuth(prompts, finish, resolvedCredentials);
this.handlePasswordAuth(prompts, finish, resolvedCredentials, hostConfig);
}
private handleWarpgateAuth(
@@ -282,7 +284,22 @@ export class SSHAuthManager {
prompts: Array<{ prompt: string; echo: boolean }>,
finish: (responses: string[]) => void,
resolvedCredentials: ResolvedCredentials,
hostConfig?: HostConfig,
): void {
// For Warpgate hosts: auto-answer password prompts silently using stored credentials.
// Warpgate sends a password prompt before its browser-verification round; we must
// not show a UI prompt here -- the WarpgateDialog handles user interaction later.
if (hostConfig?.useWarpgate) {
const responses = prompts.map((p) => {
if (/password/i.test(p.prompt) && resolvedCredentials.password) {
return resolvedCredentials.password as string;
}
return "";
});
finish(responses);
return;
}
const hasStoredPassword =
resolvedCredentials.password && resolvedCredentials.authType !== "none";
@@ -290,19 +307,34 @@ export class SSHAuthManager {
/password/i.test(p.prompt),
);
if (!hasStoredPassword && passwordPromptIndex !== -1) {
// Find the first prompt we can't auto-answer. This handles DUO/PAM challenges
// that don't say "password" (e.g. "Passcode or option (1-N):").
const firstUnansweredIndex = prompts.findIndex((p) => {
if (/password/i.test(p.prompt) && hasStoredPassword) return false;
return true;
});
if (firstUnansweredIndex !== -1) {
if (this.context.keyboardInteractiveResponded) {
return;
}
this.context.keyboardInteractiveResponded = true;
const promptIndex =
passwordPromptIndex !== -1 && !hasStoredPassword
? passwordPromptIndex
: firstUnansweredIndex;
this.context.keyboardInteractiveFinish = (userResponses: string[]) => {
const userInput = (userResponses[0] || "").trim();
const responses = prompts.map((p, index) => {
if (index === passwordPromptIndex) {
if (index === promptIndex) {
return userInput;
}
if (/password/i.test(p.prompt) && resolvedCredentials.password) {
return resolvedCredentials.password;
}
return "";
});
@@ -335,7 +367,7 @@ export class SSHAuthManager {
this.context.ws.send(
JSON.stringify({
type: "password_required",
prompt: prompts[passwordPromptIndex].prompt,
prompt: prompts[promptIndex].prompt,
}),
);
return;
+72 -2
View File
@@ -1,5 +1,8 @@
import { describe, it, expect } from "vitest";
import { pickResolvedUsername } from "./credential-username.js";
import { describe, it, expect, vi, beforeEach } from "vitest";
import {
pickResolvedUsername,
expandOidcUsername,
} from "./credential-username.js";
describe("pickResolvedUsername", () => {
it("keeps the host username when one is set, even with a credential username", () => {
@@ -26,3 +29,70 @@ describe("pickResolvedUsername", () => {
expect(pickResolvedUsername(undefined, undefined, false)).toBeUndefined();
});
});
describe("expandOidcUsername", () => {
beforeEach(() => {
vi.resetModules();
});
it("returns the username unchanged when it has no placeholder", async () => {
expect(await expandOidcUsername("alice", "user-1")).toBe("alice");
expect(await expandOidcUsername(undefined, "user-1")).toBeUndefined();
});
it("expands the placeholder with the user's OIDC identifier", async () => {
vi.doMock("../database/db/index.js", () => ({
getDb: () => ({
select: () => ({
from: () => ({
where: () => ({
limit: async () => [{ oidcIdentifier: "jdoe" }],
}),
}),
}),
}),
}));
vi.doMock("../database/db/schema.js", () => ({ users: {} }));
vi.doMock("drizzle-orm", () => ({ eq: vi.fn() }));
const { expandOidcUsername: expand } =
await import("./credential-username.js");
expect(await expand("$oidc.preferred_username", "user-1")).toBe("jdoe");
});
it("leaves the placeholder as-is when the user has no OIDC identifier", async () => {
vi.doMock("../database/db/index.js", () => ({
getDb: () => ({
select: () => ({
from: () => ({
where: () => ({
limit: async () => [{ oidcIdentifier: null }],
}),
}),
}),
}),
}));
vi.doMock("../database/db/schema.js", () => ({ users: {} }));
vi.doMock("drizzle-orm", () => ({ eq: vi.fn() }));
const { expandOidcUsername: expand } =
await import("./credential-username.js");
expect(await expand("$oidc.preferred_username", "user-1")).toBe(
"$oidc.preferred_username",
);
});
it("returns the username unchanged when the DB lookup throws", async () => {
vi.doMock("../database/db/index.js", () => ({
getDb: () => {
throw new Error("DB unavailable");
},
}));
const { expandOidcUsername: expand } =
await import("./credential-username.js");
expect(await expand("$oidc.preferred_username", "user-1")).toBe(
"$oidc.preferred_username",
);
});
});
+34
View File
@@ -21,6 +21,40 @@ export function pickResolvedUsername(
return cred;
}
/**
* Expands the `$oidc.preferred_username` placeholder in an SSH username to the
* connecting user's OIDC identifier. Returns the username unchanged if it does
* not contain the placeholder or the user has no OIDC identifier.
*/
export async function expandOidcUsername(
username: string | undefined,
userId: string,
): Promise<string | undefined> {
if (!username || !username.includes("$oidc.preferred_username")) {
return username;
}
try {
const { getDb } = await import("../database/db/index.js");
const { users } = await import("../database/db/schema.js");
const { eq } = await import("drizzle-orm");
const db = getDb();
const rows = await db
.select({ oidcIdentifier: users.oidcIdentifier })
.from(users)
.where(eq(users.id, userId))
.limit(1);
const oidcIdentifier = rows[0]?.oidcIdentifier;
if (!oidcIdentifier) return username;
return username.replace(/\$oidc\.preferred_username/g, oidcIdentifier);
} catch {
return username;
}
}
function isNonEmptyString(value: unknown): value is string {
return typeof value === "string" && value.trim() !== "";
}
+12 -3
View File
@@ -8,6 +8,7 @@ type DockerSession = {
lastActive: number;
activeOperations: number;
hostId?: number;
isWindows?: boolean;
};
type PendingDockerTotpSession = unknown;
@@ -93,7 +94,10 @@ export function registerDockerContainerRoutes(
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 formatStr = session.isWindows
? `"{\\"id\\":\\"{{.ID}}\\",\\"name\\":\\"{{.Names}}\\",\\"image\\":\\"{{.Image}}\\",\\"status\\":\\"{{.Status}}\\",\\"state\\":\\"{{.State}}\\",\\"ports\\":\\"{{.Ports}}\\",\\"created\\":\\"{{.CreatedAt}}\\"}"`
: `'{"id":"{{.ID}}","name":"{{.Names}}","image":"{{.Image}}","status":"{{.Status}}","state":"{{.State}}","ports":"{{.Ports}}","created":"{{.CreatedAt}}"}' `;
const command = `docker ps ${allFlag}--format ${formatStr}`;
const output = await executeDockerCommand(
session,
@@ -916,7 +920,7 @@ export function registerDockerContainerRoutes(
session.activeOperations++;
try {
let command = `docker logs ${containerId} 2>&1`;
let command = `docker logs ${containerId}`;
if (tail && tail > 0) {
command += ` --tail ${Math.floor(tail)}`;
@@ -934,6 +938,8 @@ export function registerDockerContainerRoutes(
command += ` --until ${until}`;
}
command += " 2>&1";
const logs = await executeDockerCommand(
session,
command,
@@ -1026,7 +1032,10 @@ export function registerDockerContainerRoutes(
session.activeOperations++;
try {
const command = `docker stats ${containerId} --no-stream --format '{"cpu":"{{.CPUPerc}}","memory":"{{.MemUsage}}","memoryPercent":"{{.MemPerc}}","netIO":"{{.NetIO}}","blockIO":"{{.BlockIO}}","pids":"{{.PIDs}}"}'`;
const statsFormatStr = session.isWindows
? `"{\\"cpu\\":\\"{{.CPUPerc}}\\",\\"memory\\":\\"{{.MemUsage}}\\",\\"memoryPercent\\":\\"{{.MemPerc}}\\",\\"netIO\\":\\"{{.NetIO}}\\",\\"blockIO\\":\\"{{.BlockIO}}\\",\\"pids\\":\\"{{.PIDs}}\\"}"`
: `'{"cpu":"{{.CPUPerc}}","memory":"{{.MemUsage}}","memoryPercent":"{{.MemPerc}}","netIO":"{{.NetIO}}","blockIO":"{{.BlockIO}}","pids":"{{.PIDs}}"}' `;
const command = `docker stats ${containerId} --no-stream --format ${statsFormatStr}`;
const output = await executeDockerCommand(
session,
+27 -4
View File
@@ -44,6 +44,7 @@ interface SSHSession {
activeOperations: number;
hostId?: number;
userId?: string;
isWindows?: boolean;
}
interface PendingTOTPSession {
@@ -852,9 +853,10 @@ app.post("/docker/ssh/connect", async (req, res) => {
if (
resolvedCredentials.authType === "none" ||
resolvedCredentials.authType === "tailscale"
resolvedCredentials.authType === "tailscale" ||
resolvedCredentials.authType === "warpgate"
) {
// Tailscale SSH and "none" auth: no credentials needed
// Tailscale SSH, "none", and Warpgate auth: no static credentials
} else if (resolvedCredentials.authType === "password") {
if (resolvedCredentials.password) {
config.password = resolvedCredentials.password;
@@ -1038,7 +1040,7 @@ app.post("/docker/ssh/connect", async (req, res) => {
),
);
sshSessions[sessionId] = {
const session: SSHSession = {
client,
isConnected: true,
lastActive: Date.now(),
@@ -1047,8 +1049,24 @@ app.post("/docker/ssh/connect", async (req, res) => {
userId,
};
sshSessions[sessionId] = session;
scheduleSessionCleanup(sessionId);
client.exec("ver", (err, stream) => {
if (!err && stream) {
let output = "";
stream.on("data", (d: Buffer) => {
output += d.toString();
});
stream.on("close", () => {
if (output.toLowerCase().includes("windows")) {
session.isWindows = true;
}
});
stream.stderr.on("data", () => {});
}
});
res.json({
success: true,
message: "SSH connection established",
@@ -1313,6 +1331,11 @@ app.post("/docker/ssh/connect", async (req, res) => {
/password/i.test(p.prompt),
);
if (resolvedCredentials.authType === "warpgate") {
finish(prompts.map(() => ""));
return;
}
if (
(resolvedCredentials.authType === "none" ||
resolvedCredentials.authType === "tailscale") &&
@@ -2144,7 +2167,7 @@ app.get("/docker/validate/:sessionId", async (req, res) => {
try {
await executeDockerCommand(
session,
"docker ps >/dev/null 2>&1",
"docker ps",
sessionId,
userId,
session.hostId,
+206 -1
View File
@@ -1,4 +1,5 @@
import type { Express } from "express";
import type { Express, Request, Response } from "express";
import Busboy from "busboy";
import type { AuthenticatedRequest } from "../../types/index.js";
import { fileLogger } from "../utils/logger.js";
import {
@@ -1302,4 +1303,208 @@ export function registerFileContentRoutes(
trySFTP();
});
/**
* @openapi
* /ssh/file_manager/ssh/uploadFileStream:
* post:
* summary: Stream-upload a file via multipart form
* description: Uploads a file to the remote host by streaming multipart form data directly into an SFTP write stream, avoiding full in-memory buffering.
* tags:
* - File Manager
* requestBody:
* required: true
* content:
* multipart/form-data:
* schema:
* type: object
* required:
* - sessionId
* - path
* - file
* properties:
* sessionId:
* type: string
* path:
* type: string
* file:
* type: string
* format: binary
* responses:
* 200:
* description: File uploaded successfully.
* 400:
* description: Missing required parameters or SSH connection not established.
* 500:
* description: Failed to upload file.
*/
app.post(
"/ssh/file_manager/ssh/uploadFileStream",
(req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
const contentType = req.headers["content-type"] || "";
if (!contentType.includes("multipart/form-data")) {
return res
.status(400)
.json({ error: "Expected multipart/form-data request" });
}
let sessionId: string | undefined;
let remotePath: string | undefined;
let fileName: string | undefined;
let uploadStartTime: number;
let resolved = false;
const bb = Busboy({ headers: req.headers });
bb.on("field", (name: string, value: string) => {
if (name === "sessionId") sessionId = value;
if (name === "path") remotePath = value;
});
bb.on(
"file",
(
fieldname: string,
fileStream: NodeJS.ReadableStream,
info: { filename: string; encoding: string; mimeType: string },
) => {
fileName = info.filename;
if (!sessionId || !remotePath || !fileName) {
fileStream.resume();
if (!resolved) {
resolved = true;
res
.status(400)
.json({ error: "Missing sessionId or path field" });
}
return;
}
const sshConn = sshSessions[sessionId];
if (!sshConn?.isConnected) {
fileStream.resume();
if (!resolved) {
resolved = true;
res.status(400).json({ error: "SSH connection not established" });
}
return;
}
if (!verifySessionOwnership(sshConn, userId)) {
fileStream.resume();
if (!resolved) {
resolved = true;
res.status(403).json({ error: "Session access denied" });
}
return;
}
sshConn.lastActive = Date.now();
uploadStartTime = Date.now();
const fullPath = remotePath.endsWith("/")
? remotePath + fileName
: remotePath + "/" + fileName;
fileLogger.info("Streaming file upload started", {
operation: "file_upload_stream_start",
sessionId,
userId,
path: fullPath,
});
getSessionSftp(sshConn)
.then((sftp) => {
const writeStream = sftp.createWriteStream(fullPath);
writeStream.on("error", (err) => {
fileLogger.error("SFTP write stream error during upload:", err);
if (!resolved) {
resolved = true;
res
.status(500)
.json({ error: `Upload failed: ${err.message}` });
}
});
writeStream.on("finish", () => {
if (resolved) return;
resolved = true;
fileLogger.success("Streaming file upload completed", {
operation: "file_upload_stream_complete",
sessionId,
userId,
path: fullPath,
duration: Date.now() - uploadStartTime,
});
res.json({
message: "File uploaded successfully",
path: fullPath,
toast: {
type: "success",
message: `File uploaded: ${fullPath}`,
},
});
});
writeStream.on("close", () => {
if (resolved) return;
resolved = true;
fileLogger.success("Streaming file upload completed", {
operation: "file_upload_stream_complete",
sessionId,
userId,
path: fullPath,
duration: Date.now() - uploadStartTime,
});
res.json({
message: "File uploaded successfully",
path: fullPath,
toast: {
type: "success",
message: `File uploaded: ${fullPath}`,
},
});
});
fileStream.on("error", (err) => {
fileLogger.error("File read stream error during upload:", err);
writeStream.destroy();
if (!resolved) {
resolved = true;
res
.status(500)
.json({ error: `Upload stream error: ${err.message}` });
}
});
(fileStream as NodeJS.ReadableStream).pipe(
writeStream as unknown as NodeJS.WritableStream,
);
})
.catch((err: Error) => {
fileStream.resume();
fileLogger.error("SFTP session error during stream upload:", err);
if (!resolved) {
resolved = true;
res.status(500).json({ error: `SFTP error: ${err.message}` });
}
});
},
);
bb.on("error", (err: Error) => {
fileLogger.error("Busboy parse error during stream upload:", err);
if (!resolved) {
resolved = true;
res.status(500).json({ error: `Upload parse error: ${err.message}` });
}
});
req.pipe(bb);
},
);
}
+140 -8
View File
@@ -2,7 +2,11 @@ import type { Express } from "express";
import type { AuthenticatedRequest } from "../../types/index.js";
import { fileLogger } from "../utils/logger.js";
import { getMimeType } from "./file-manager-utils.js";
import { getSessionSftp, type SSHSession } from "./file-manager-session.js";
import {
execChannel,
getSessionSftp,
type SSHSession,
} from "./file-manager-session.js";
type FileDownloadRoutesDeps = {
sshSessions: Record<string, SSHSession>;
@@ -10,6 +14,37 @@ type FileDownloadRoutesDeps = {
verifySessionOwnership: (session: SSHSession, userId: string) => boolean;
};
function escapeSingleQuotes(path: string): string {
return path.replace(/'/g, "'\"'\"'");
}
function downloadViaExec(
session: SSHSession,
filePath: string,
): Promise<Buffer> {
return new Promise((resolve, reject) => {
const escaped = escapeSingleQuotes(filePath);
execChannel(session, `cat '${escaped}'`, (err, stream) => {
if (err) return reject(err);
const chunks: Buffer[] = [];
let stderr = "";
stream.on("data", (chunk: Buffer) => chunks.push(chunk));
stream.stderr.on("data", (chunk: Buffer) => {
stderr += chunk.toString();
});
stream.on("close", (code: number) => {
if (code !== 0) {
return reject(
new Error(stderr.trim() || `cat exited with code ${code}`),
);
}
resolve(Buffer.concat(chunks));
});
stream.on("error", reject);
});
});
}
export function registerFileDownloadRoutes(
app: Express,
{
@@ -23,7 +58,7 @@ export function registerFileDownloadRoutes(
* /ssh/file_manager/ssh/downloadFile:
* post:
* summary: Download a file
* description: Downloads a file from the remote host.
* description: Downloads a file from the remote host. Uses SCP legacy mode (cat over exec) when the host has scpLegacy enabled, otherwise uses SFTP.
* tags:
* - File Manager
* requestBody:
@@ -88,6 +123,45 @@ export function registerFileDownloadRoutes(
sshConn.lastActive = Date.now();
scheduleSessionCleanup(sessionId);
if (sshConn.scpLegacy) {
fileLogger.info(
"Downloading file via legacy exec/cat (SCP legacy mode)",
{
operation: "file_download_legacy",
sessionId,
userId,
path: filePath,
},
);
try {
const data = await downloadViaExec(sshConn, filePath);
const fileName = filePath.split("/").pop() || "download";
fileLogger.success("File download completed (legacy mode)", {
operation: "file_download_complete",
sessionId,
userId,
hostId,
path: filePath,
bytes: data.length,
duration: Date.now() - downloadStartTime,
});
return res.json({
content: data.toString("base64"),
fileName,
size: data.length,
mimeType: getMimeType(fileName),
path: filePath,
});
} catch (err) {
fileLogger.error("Legacy exec/cat download failed:", err);
return res.status(500).json({
error: `Failed to download file: ${(err as Error).message}`,
});
}
}
fileLogger.info("Opening SFTP channel", {
operation: "file_sftp_open",
sessionId,
@@ -168,6 +242,33 @@ export function registerFileDownloadRoutes(
});
});
/**
* @openapi
* /ssh/file_manager/ssh/downloadFileStream:
* post:
* summary: Stream-download a file
* description: Downloads a file as a binary stream. Uses SCP legacy mode (cat over exec) when the host has scpLegacy enabled, otherwise uses SFTP.
* tags:
* - File Manager
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* sessionId:
* type: string
* path:
* type: string
* responses:
* 200:
* description: Binary file stream.
* 400:
* description: Missing required parameters.
* 500:
* description: Download failed.
*/
app.post("/ssh/file_manager/ssh/downloadFileStream", async (req, res) => {
const { sessionId, path: filePath } = req.body;
const userId = (req as AuthenticatedRequest).userId;
@@ -188,6 +289,43 @@ export function registerFileDownloadRoutes(
sshConn.lastActive = Date.now();
const fileName = filePath.split("/").pop() || "download";
res.setHeader("Content-Type", "application/octet-stream");
res.setHeader(
"Content-Disposition",
`attachment; filename="${encodeURIComponent(fileName)}"`,
);
if (sshConn.scpLegacy) {
fileLogger.info("Streaming file via legacy exec/cat (SCP legacy mode)", {
operation: "file_download_stream_legacy",
sessionId,
userId,
path: filePath,
});
const escaped = escapeSingleQuotes(filePath);
execChannel(sshConn, `cat '${escaped}'`, (err, stream) => {
if (err) {
if (!res.headersSent) {
res.status(500).json({ error: `Download failed: ${err.message}` });
}
return;
}
stream.on("error", (streamErr: Error) => {
if (!res.headersSent) {
res
.status(500)
.json({ error: `Download failed: ${streamErr.message}` });
} else {
res.destroy();
}
});
stream.pipe(res);
});
return;
}
try {
const sftp = await getSessionSftp(sshConn);
const stats = await new Promise<{ size: number; isFile: () => boolean }>(
@@ -200,12 +338,6 @@ export function registerFileDownloadRoutes(
return res.status(400).json({ error: "Cannot download directories" });
}
const fileName = filePath.split("/").pop() || "download";
res.setHeader("Content-Type", "application/octet-stream");
res.setHeader(
"Content-Disposition",
`attachment; filename="${encodeURIComponent(fileName)}"`,
);
res.setHeader("Content-Length", String(stats.size));
const readStream = sftp.createReadStream(filePath);
@@ -6,6 +6,7 @@ import {
execWithSudo,
type SSHSession,
} from "./file-manager-session.js";
import { isWindowsSftpPath } from "./transfer-paths.js";
type FileOperationRoutesDeps = {
sshSessions: Record<string, SSHSession>;
@@ -373,11 +374,23 @@ export function registerFileOperationRoutes(
type: isDirectory ? "directory" : "file",
});
sshConn.lastActive = Date.now();
const escapedPath = itemPath.replace(/'/g, "'\"'\"'");
const deleteCommand = isDirectory
? `rm -rf '${escapedPath}'`
: `rm -f '${escapedPath}'`;
const isWindowsPath = isWindowsSftpPath(itemPath);
let deleteCommand: string;
if (isWindowsPath) {
const winPath = itemPath
.replace(/\//g, "\\")
.replace(/^\\([A-Za-z]:\\)/, "$1");
const escapedWinPath = winPath.replace(/"/g, '""');
deleteCommand = isDirectory
? `rd /s /q "${escapedWinPath}"`
: `del /f /q "${escapedWinPath}"`;
} else {
const escapedPath = itemPath.replace(/'/g, "'\"'\"'");
deleteCommand = isDirectory
? `rm -rf '${escapedPath}'`
: `rm -f '${escapedPath}'`;
}
const executeDelete = (useSudo: boolean): Promise<void> => {
return new Promise((resolve) => {
@@ -465,10 +478,6 @@ export function registerFileOperationRoutes(
},
});
} else {
// The shell didn't echo our SUCCESS sentinel. This happens on
// non-POSIX shells (e.g. Windows PowerShell, where `rm -f` is
// not supported) and the command can exit 0 while doing nothing.
// Surface whatever the shell produced so the failure isn't silent.
const detail =
errorData.trim() ||
outputData.trim() ||
+1
View File
@@ -39,6 +39,7 @@ export interface SSHSession {
transferDedicated?: boolean;
transferId?: string;
browseSessionId?: string;
scpLegacy?: boolean;
}
export interface PendingTOTPSession {
+91 -13
View File
@@ -132,6 +132,7 @@ async function buildDedicatedTransferConnectConfig(
client: SSHClient,
): Promise<Record<string, unknown>> {
const { ip, port, username } = host;
const preloadedHostData = await SSHHostKeyVerifier.preloadHostData(host.id);
const config: Record<string, unknown> = {
host: ip?.replace(/^\[|\]$/g, "") || ip,
port,
@@ -149,6 +150,7 @@ async function buildDedicatedTransferConnectConfig(
null,
userId,
false,
preloadedHostData,
),
env: {
TERM: "xterm-256color",
@@ -726,6 +728,13 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
let resolvedPort = port;
let resolvedUsername = username;
let resolvedJumpHosts = jumpHosts;
let resolvedScpLegacy = false;
let resolvedUseSocks5 = useSocks5;
let resolvedSocks5Host = socks5Host;
let resolvedSocks5Port = socks5Port;
let resolvedSocks5Username = socks5Username;
let resolvedSocks5Password = socks5Password;
let resolvedSocks5ProxyChain = socks5ProxyChain;
if (hostId && userId && !password && !sshKey) {
try {
const { resolveHostById } = await import("./host-resolver.js");
@@ -743,6 +752,15 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
};
hostKeepaliveInterval = resolvedHost.terminalConfig?.keepaliveInterval;
hostKeepaliveCountMax = resolvedHost.terminalConfig?.keepaliveCountMax;
resolvedScpLegacy = resolvedHost.scpLegacy ?? false;
if (resolvedHost.useSocks5) {
resolvedUseSocks5 = resolvedHost.useSocks5;
resolvedSocks5Host = resolvedHost.socks5Host;
resolvedSocks5Port = resolvedHost.socks5Port;
resolvedSocks5Username = resolvedHost.socks5Username;
resolvedSocks5Password = resolvedHost.socks5Password;
resolvedSocks5ProxyChain = resolvedHost.socks5ProxyChain;
}
if (
(!resolvedJumpHosts || resolvedJumpHosts.length === 0) &&
resolvedHost.jumpHosts &&
@@ -790,6 +808,15 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
};
hostKeepaliveInterval = resolvedHost.terminalConfig?.keepaliveInterval;
hostKeepaliveCountMax = resolvedHost.terminalConfig?.keepaliveCountMax;
resolvedScpLegacy = resolvedHost.scpLegacy ?? false;
if (resolvedHost.useSocks5) {
resolvedUseSocks5 = resolvedHost.useSocks5;
resolvedSocks5Host = resolvedHost.socks5Host;
resolvedSocks5Port = resolvedHost.socks5Port;
resolvedSocks5Username = resolvedHost.socks5Username;
resolvedSocks5Password = resolvedHost.socks5Password;
resolvedSocks5ProxyChain = resolvedHost.socks5ProxyChain;
}
if (
(!resolvedJumpHosts || resolvedJumpHosts.length === 0) &&
resolvedHost.jumpHosts &&
@@ -822,6 +849,7 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
}
}
const preloadedHostData = await SSHHostKeyVerifier.preloadHostData(hostId);
const config: Record<string, unknown> = {
host: resolvedIp?.replace(/^\[|\]$/g, "") || resolvedIp,
port: resolvedPort,
@@ -829,10 +857,12 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
tryKeyboard: true,
keepaliveInterval:
typeof hostKeepaliveInterval === "number"
? hostKeepaliveInterval * 1000
? Math.max(5000, hostKeepaliveInterval * 1000)
: 60000,
keepaliveCountMax:
typeof hostKeepaliveCountMax === "number" ? hostKeepaliveCountMax : 5,
typeof hostKeepaliveCountMax === "number"
? Math.max(1, hostKeepaliveCountMax)
: 5,
readyTimeout: 60000,
tcpKeepAlive: true,
tcpKeepAliveInitialDelay: 30000,
@@ -843,6 +873,7 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
null,
userId,
false,
preloadedHostData,
),
env: {
TERM: "xterm-256color",
@@ -1015,7 +1046,8 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
}
} else if (
resolvedCredentials.authType === "none" ||
resolvedCredentials.authType === "tailscale"
resolvedCredentials.authType === "tailscale" ||
resolvedCredentials.authType === "warpgate"
) {
connectionLogs.push(
createConnectionLog(
@@ -1109,6 +1141,7 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
hostId,
username,
sudoPassword: resolvedCredentials.sudoPassword,
scpLegacy: resolvedScpLegacy,
};
scheduleSessionCleanup(sessionId);
res.json({
@@ -1266,6 +1299,14 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
}
if (
err.message.includes("Cannot parse privateKey") &&
err.message.includes("no passphrase")
) {
res.json({
status: "passphrase_required",
connectionLogs,
});
} else if (
(resolvedCredentials.authType === "none" ||
resolvedCredentials.authType === "tailscale") &&
(err.message.includes("authentication") ||
@@ -1426,12 +1467,18 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
const hasStoredPassword =
resolvedCredentials.password &&
resolvedCredentials.authType !== "none" &&
resolvedCredentials.authType !== "tailscale";
resolvedCredentials.authType !== "tailscale" &&
resolvedCredentials.authType !== "warpgate";
const passwordPromptIndex = prompts.findIndex((p) =>
/password/i.test(p.prompt),
);
if (resolvedCredentials.authType === "warpgate") {
finish(prompts.map(() => ""));
return;
}
if (
(resolvedCredentials.authType === "none" ||
resolvedCredentials.authType === "tailscale") &&
@@ -1512,16 +1559,17 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
);
const proxyConfig: SOCKS5Config | null =
useSocks5 &&
(socks5Host ||
(socks5ProxyChain && (socks5ProxyChain as ProxyNode[]).length > 0))
resolvedUseSocks5 &&
(resolvedSocks5Host ||
(resolvedSocks5ProxyChain &&
(resolvedSocks5ProxyChain as ProxyNode[]).length > 0))
? {
useSocks5,
socks5Host,
socks5Port,
socks5Username,
socks5Password,
socks5ProxyChain: socks5ProxyChain as ProxyNode[],
useSocks5: resolvedUseSocks5,
socks5Host: resolvedSocks5Host,
socks5Port: resolvedSocks5Port,
socks5Username: resolvedSocks5Username,
socks5Password: resolvedSocks5Password,
socks5ProxyChain: resolvedSocks5ProxyChain as ProxyNode[],
}
: null;
@@ -1571,7 +1619,37 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
});
}
let forwardOutDone = false;
const forwardOutTimeout = setTimeout(() => {
if (!forwardOutDone) {
forwardOutDone = true;
fileLogger.error("Timeout waiting for jump host forwardOut", {
operation: "file_jump_forward_timeout",
sessionId,
hostId,
ip,
port,
});
connectionLogs.push(
createConnectionLog(
"error",
"jump",
"Timed out waiting for jump host tunnel to target host",
),
);
jumpClient.end();
res.status(500).json({
error: "Jump host tunnel timed out",
connectionLogs,
});
}
}, 30000);
jumpClient.forwardOut("127.0.0.1", 0, ip, port, (err, stream) => {
if (forwardOutDone) return;
forwardOutDone = true;
clearTimeout(forwardOutTimeout);
if (err) {
fileLogger.error("Failed to forward through jump host", err, {
operation: "file_jump_forward",
+49 -10
View File
@@ -21,6 +21,37 @@ interface VerificationResponse {
}
export class SSHHostKeyVerifier {
/**
* Pre-fetches the host record from the database so the verifier callback
* during SSH key exchange doesn't need to do an async DB query. This keeps
* the key exchange critical path fast, avoiding LoginGraceTime expiry on
* the remote server (especially important for jump-host tunneled connections).
*/
static async preloadHostData(hostId: number | null): Promise<{
hostKeyFingerprint: string | null;
hostKeyType: string | null;
hostKeyAlgorithm: string | null;
hostKeyChangedCount: number | null;
name: string | null;
} | null> {
if (!hostId) return null;
try {
const host = await db.query.hosts.findFirst({
where: eq(hosts.id, hostId),
columns: {
hostKeyFingerprint: true,
hostKeyType: true,
hostKeyAlgorithm: true,
hostKeyChangedCount: true,
name: true,
},
});
return host ?? null;
} catch {
return null;
}
}
static async createHostVerifier(
hostId: number | null,
ip: string,
@@ -28,6 +59,9 @@ export class SSHHostKeyVerifier {
ws: WebSocket | null,
userId: string,
isJumpHost: boolean = false,
preloadedHost?: Awaited<
ReturnType<typeof SSHHostKeyVerifier.preloadHostData>
>,
): Promise<(hostkey: Buffer, verify: (valid: boolean) => void) => void> {
return (hostkey: Buffer, verify: (valid: boolean) => void): void => {
(async () => {
@@ -52,9 +86,10 @@ export class SSHHostKeyVerifier {
return;
}
const host = await db.query.hosts.findFirst({
where: eq(hosts.id, hostId),
});
const host =
preloadedHost !== undefined
? preloadedHost
: await db.query.hosts.findFirst({ where: eq(hosts.id, hostId) });
if (!host) {
sshLogger.warn(
@@ -141,13 +176,6 @@ export class SSHHostKeyVerifier {
}
if (host.hostKeyFingerprint === fingerprint) {
await db
.update(hosts)
.set({
hostKeyLastVerified: new Date().toISOString(),
})
.where(eq(hosts.id, hostId));
sshLogger.info("Host key verified successfully", {
operation: "host_key_verified",
hostId,
@@ -158,7 +186,18 @@ export class SSHHostKeyVerifier {
userId,
});
// Verify first, then update the timestamp asynchronously so the
// DB write doesn't delay the SSH key exchange critical path.
verify(true);
db.update(hosts)
.set({ hostKeyLastVerified: new Date().toISOString() })
.where(eq(hosts.id, hostId))
.catch((err) => {
sshLogger.error("Failed to update hostKeyLastVerified", err, {
operation: "host_key_update_timestamp",
hostId,
});
});
return;
}
+20 -2
View File
@@ -96,6 +96,9 @@ interface SSHHostWithCredentials {
socks5Password?: string;
socks5ProxyChain?: ProxyNode[];
connectionType?: "ssh" | "rdp" | "vnc" | "telnet";
rdpPort?: number;
vncPort?: number;
telnetPort?: number;
}
type StatusEntry = {
@@ -348,7 +351,12 @@ class PollingManager {
try {
let pingHost = refreshedHost.ip;
let pingPort = refreshedHost.port;
const ct = refreshedHost.connectionType || "ssh";
let pingPort: number;
if (ct === "rdp") pingPort = refreshedHost.rdpPort ?? 3389;
else if (ct === "vnc") pingPort = refreshedHost.vncPort ?? 5900;
else if (ct === "telnet") pingPort = refreshedHost.telnetPort ?? 23;
else pingPort = refreshedHost.port;
if (refreshedHost.jumpHosts && refreshedHost.jumpHosts.length > 0) {
const firstJump = await fetchHostById(
refreshedHost.jumpHosts[0].hostId,
@@ -792,6 +800,12 @@ async function resolveHostCredentials(
socks5ProxyChain: host.socks5ProxyChain
? JSON.parse(host.socks5ProxyChain as string)
: undefined,
connectionType:
(host.connectionType as SSHHostWithCredentials["connectionType"]) ||
"ssh",
rdpPort: (host.rdpPort as number | undefined) ?? undefined,
vncPort: (host.vncPort as number | undefined) ?? undefined,
telnetPort: (host.telnetPort as number | undefined) ?? undefined,
};
if (host.credentialId) {
@@ -1028,7 +1042,11 @@ async function buildSshConfig(
cause: keyError,
});
}
} else if (host.authType === "none" || host.authType === "tailscale") {
} else if (
host.authType === "none" ||
host.authType === "tailscale" ||
host.authType === "warpgate"
) {
// no credentials needed
} else if (host.authType === "opkssh") {
// cert auth setup happens in createSshFactory (needs client instance)
+17 -1
View File
@@ -3,7 +3,10 @@ import { hosts, sshCredentials } from "../database/db/schema.js";
import { eq, and } from "drizzle-orm";
import { SimpleDBOps } from "../utils/simple-db-ops.js";
import { logger } from "../utils/logger.js";
import { pickResolvedUsername } from "./credential-username.js";
import {
pickResolvedUsername,
expandOidcUsername,
} from "./credential-username.js";
import type { SSHHost } from "../../types/index.js";
const sshLogger = logger;
@@ -120,6 +123,10 @@ export async function resolveHostById(
: cred.password
? "password"
: "none";
host.username = await expandOidcUsername(
host.username as string | undefined,
userId,
);
return host as unknown as SSHHost;
}
}
@@ -150,6 +157,10 @@ export async function resolveHostById(
: sharedCred.password
? "password"
: "none";
host.username = await expandOidcUsername(
host.username as string | undefined,
userId,
);
return host as unknown as SSHHost;
}
} catch (e) {
@@ -203,6 +214,11 @@ export async function resolveHostById(
}
}
host.username = await expandOidcUsername(
host.username as string | undefined,
userId,
);
return host as unknown as SSHHost;
}
+131 -119
View File
@@ -5,7 +5,7 @@ import ssh2Pkg, {
type PseudoTtyOptions,
} from "ssh2";
const { Client, utils: ssh2Utils } = ssh2Pkg;
import { SSH_ALGORITHMS } from "../utils/ssh-algorithms.js";
import { buildSSHAlgorithms } from "../utils/ssh-algorithms.js";
import axios from "axios";
import { getDb } from "../database/db/index.js";
import { hosts } from "../database/db/schema.js";
@@ -30,6 +30,7 @@ import {
waitForTmuxSession,
} from "./tmux-helper.js";
import { MemoryAgent, performPortKnocking } from "./terminal-auth-helpers.js";
import { isWindowsSftpPath, sftpPathToLocalPath } from "./transfer-paths.js";
interface ConnectToHostData {
cols: number;
@@ -187,9 +188,8 @@ wss.on("connection", async (ws: WebSocket, req) => {
let isConnecting = false;
let isConnected = false;
let isCleaningUp = false;
let cwdPending = false;
let cwdBuffer = "";
let isShellInitializing = false;
let isDuplicateConnDiscarded = false;
let warpgateAuthPromptSent = false;
let warpgateAuthTimeout: NodeJS.Timeout | null = null;
let isAwaitingAuthCredentials = false;
@@ -237,7 +237,12 @@ wss.on("connection", async (ws: WebSocket, req) => {
if (currentSessionId) {
const session = sessionManager.getSession(currentSessionId);
if (session?.isConnected) {
sessionManager.detachWs(currentSessionId);
// Only detach if this WS is still the one attached to the session.
// If a refresh reconnected and reattached a new WS before this close
// event fired, we must not clobber that new attachment.
if (session.attachedWs === ws || session.attachedWs === null) {
sessionManager.detachWs(currentSessionId);
}
} else {
sessionManager.destroySession(currentSessionId);
currentSessionId = null;
@@ -446,15 +451,80 @@ wss.on("connection", async (ws: WebSocket, req) => {
break;
case "get_cwd": {
const activeStream =
sessionManager.getSession(currentSessionId)?.sshStream ?? sshStream;
if (!activeStream) {
const activeConn =
sessionManager.getSession(currentSessionId)?.sshConn ?? sshConn;
if (!activeConn) {
ws.send(JSON.stringify({ type: "cwd", path: "/" }));
break;
}
cwdPending = true;
cwdBuffer = "";
activeStream.write('\x15a=TERMIX_CWD; echo "$a:$(pwd)"\r');
activeConn.exec("pwd", (err, execStream) => {
if (err) {
ws.send(JSON.stringify({ type: "cwd", path: "/" }));
return;
}
let stdout = "";
execStream.on("data", (chunk: Buffer) => {
stdout += chunk.toString("utf-8");
});
execStream.stderr.on("data", () => {});
execStream.on("close", () => {
const cwd = stdout.trim() || "/";
const attachedWs =
sessionManager.getSession(currentSessionId)?.attachedWs ?? ws;
if (attachedWs.readyState === WebSocket.OPEN) {
attachedWs.send(JSON.stringify({ type: "cwd", path: cwd }));
}
});
});
break;
}
case "open_file_in_editor": {
const { path: requestedPath } = data as { path: string };
const activeConn =
sessionManager.getSession(currentSessionId)?.sshConn ?? sshConn;
if (!activeConn || !requestedPath) {
ws.send(
JSON.stringify({
type: "open_file_in_editor",
path: requestedPath || "/",
}),
);
break;
}
const escapedPath = requestedPath.replace(/'/g, "'\\''");
activeConn.exec(
`realpath '${escapedPath}' 2>/dev/null || echo '${escapedPath}'`,
(err, execStream) => {
if (err) {
ws.send(
JSON.stringify({
type: "open_file_in_editor",
path: requestedPath,
}),
);
return;
}
let stdout = "";
execStream.on("data", (chunk: Buffer) => {
stdout += chunk.toString("utf-8");
});
execStream.stderr.on("data", () => {});
execStream.on("close", () => {
const resolvedPath = stdout.trim() || requestedPath;
const attachedWs =
sessionManager.getSession(currentSessionId)?.attachedWs ?? ws;
if (attachedWs.readyState === WebSocket.OPEN) {
attachedWs.send(
JSON.stringify({
type: "open_file_in_editor",
path: resolvedPath,
}),
);
}
});
},
);
break;
}
@@ -990,7 +1060,7 @@ wss.on("connection", async (ws: WebSocket, req) => {
);
}
if (!hostConfig.useSocks5 && resolvedHostData.useSocks5) {
if (resolvedHostData.useSocks5) {
hostConfig.useSocks5 = resolvedHostData.useSocks5;
hostConfig.socks5Host = resolvedHostData.socks5Host;
hostConfig.socks5Port = resolvedHostData.socks5Port;
@@ -1134,27 +1204,43 @@ wss.on("connection", async (ws: WebSocket, req) => {
!existingSession.sshStream.destroyed &&
existingSession.sshConn !== sshConn
) {
const reusedSessionId = currentSessionId;
sshLogger.info(
"Reusing existing live session after duplicate connectToHost, closing new SSH conn",
{
operation: "terminal_reuse_existing_session",
sessionId: currentSessionId,
sessionId: reusedSessionId,
tabInstanceId,
userId,
},
);
// Null out currentSessionId before ending the duplicate connection so
// the sshConn "close" handler does not destroy the reused session.
// Set isDuplicateConnDiscarded so the close handler does not send a
// "disconnected" message to the new WS that is now attached to the live session.
// Null out currentSessionId before ending the duplicate connection so
// the sshConn "close" handler does not destroy the reused session.
// Set isDuplicateConnDiscarded so the close handler exits without
// sending a "disconnected" message to the new WS.
currentSessionId = null;
isDuplicateConnDiscarded = true;
clearTimeout(connectionTimeout);
try {
sshConn?.end();
} catch {
/* ignore */
}
sshConn = null;
sshStream = null;
// Point this WS handler's closure at the live session so the input
// handler can forward keystrokes via currentSessionId.
currentSessionId = reusedSessionId;
sshStream = existingSession.sshStream;
sshConn = existingSession.sshConn;
isConnecting = false;
isConnected = true;
sessionManager.attachWs(currentSessionId, userId, ws, tabInstanceId);
sessionManager.attachWs(reusedSessionId, userId, ws, tabInstanceId);
const buffered = sessionManager.getBuffer(existingSession);
if (buffered) {
@@ -1163,20 +1249,18 @@ wss.on("connection", async (ws: WebSocket, req) => {
ws.send(
JSON.stringify({
type: "sessionCreated",
sessionId: currentSessionId,
sessionId: reusedSessionId,
}),
);
ws.send(
JSON.stringify({
type: "sessionAttached",
sessionId: currentSessionId,
sessionId: reusedSessionId,
}),
);
ws.send(
JSON.stringify({ type: "connected", message: "Session reattached" }),
);
cleanupAuthState(connectionTimeout);
return;
}
@@ -1350,44 +1434,9 @@ wss.on("connection", async (ws: WebSocket, req) => {
const boundSessionId = currentSessionId;
const CWD_SENTINEL = "TERMIX_CWD:";
stream.on("data", (data: Buffer) => {
try {
let utf8String = data.toString("utf-8");
if (cwdPending) {
cwdBuffer += utf8String;
const sentinelIdx = cwdBuffer.indexOf(CWD_SENTINEL);
if (sentinelIdx !== -1) {
const afterSentinel = cwdBuffer.slice(
sentinelIdx + CWD_SENTINEL.length,
);
const newlineIdx = afterSentinel.search(/[\r\n]/);
if (newlineIdx !== -1) {
const cwd =
afterSentinel.slice(0, newlineIdx).trim() || "/";
cwdPending = false;
// Strip the sentinel line from output sent to terminal
const beforeSentinel = cwdBuffer.slice(0, sentinelIdx);
const afterNewline = afterSentinel.slice(newlineIdx);
utf8String = beforeSentinel + afterNewline;
cwdBuffer = "";
const attachedWs =
sessionManager.getSession(boundSessionId)?.attachedWs ??
ws;
if (attachedWs.readyState === WebSocket.OPEN) {
attachedWs.send(
JSON.stringify({ type: "cwd", path: cwd }),
);
}
} else {
return;
}
} else {
return;
}
}
const utf8String = data.toString("utf-8");
if (!utf8String) return;
@@ -1475,7 +1524,14 @@ wss.on("connection", async (ws: WebSocket, req) => {
const runPostShellCommands = (delay: number) => {
setTimeout(() => {
if (initialPath && initialPath.trim() !== "") {
const cdCommand = `cd "${initialPath.replace(/"/g, '\\"')}"\r`;
let cdCommand: string;
if (isWindowsSftpPath(initialPath)) {
const winPath = sftpPathToLocalPath(initialPath);
const escaped = winPath.replace(/"/g, '""');
cdCommand = `cd "${escaped}"\r`;
} else {
cdCommand = `cd "${initialPath.replace(/"/g, '\\"')}"\r`;
}
stream.write(cdCommand);
}
if (executeCommand && executeCommand.trim() !== "") {
@@ -1543,27 +1599,6 @@ wss.on("connection", async (ws: WebSocket, req) => {
}),
);
runPostShellCommands(0);
} else if (detection.sessions.length === 1) {
attachOrCreateTmuxSession(stream, detection.sessions[0].name);
const sessionName = detection.sessions[0].name;
const session = sessionManager.getSession(boundSessionId);
if (session) {
session.tmuxSessionName = sessionName;
}
sshLogger.info("Auto-attached to existing tmux session", {
operation: "tmux_auto_attach",
sessionName,
hostId: id,
});
ws.send(
JSON.stringify({
type: "tmux_session_attached",
sessionName,
}),
);
// Reattaching to existing session -- don't re-run
// initialPath/executeCommand since the session already
// has its own state
} else {
sshLogger.info(
"Multiple tmux sessions found, sending list to frontend",
@@ -1910,6 +1945,11 @@ wss.on("connection", async (ws: WebSocket, req) => {
hostId: id,
});
if (isDuplicateConnDiscarded) {
cleanupAuthState(connectionTimeout);
return;
}
if (isAwaitingAuthCredentials) {
if (currentSessionId) {
sessionManager.destroySession(currentSessionId);
@@ -1991,6 +2031,7 @@ wss.on("connection", async (ws: WebSocket, req) => {
resolvedCredentials as unknown as Parameters<
typeof sshAuthManager.handleKeyboardInteractive
>[5],
hostConfig,
);
isKeyboardInteractive = sshAuthManager.context.isKeyboardInteractive;
@@ -2008,19 +2049,24 @@ wss.on("connection", async (ws: WebSocket, req) => {
const hostKeepaliveInterval = hostConfig.terminalConfig?.keepaliveInterval;
const hostKeepaliveCountMax = hostConfig.terminalConfig?.keepaliveCountMax;
// Pre-fetch the stored host key before connect so the verifier callback
// runs synchronously during SSH key exchange, avoiding LoginGraceTime
// expiry on slow connections (especially through jump host tunnels).
const preloadedHostData = await SSHHostKeyVerifier.preloadHostData(id);
const connectConfig: Record<string, unknown> = {
host: ip,
port,
username,
tryKeyboard:
resolvedCredentials.authType !== "none" &&
resolvedCredentials.authType !== "tailscale",
tryKeyboard: resolvedCredentials.authType !== "tailscale",
keepaliveInterval:
typeof hostKeepaliveInterval === "number"
? hostKeepaliveInterval * 1000
? Math.max(5000, hostKeepaliveInterval * 1000)
: 30000,
keepaliveCountMax:
typeof hostKeepaliveCountMax === "number" ? hostKeepaliveCountMax : 3,
typeof hostKeepaliveCountMax === "number"
? Math.max(1, hostKeepaliveCountMax)
: 5,
readyTimeout: 120000,
tcpKeepAlive: true,
tcpKeepAliveInitialDelay: 30000,
@@ -2032,6 +2078,7 @@ wss.on("connection", async (ws: WebSocket, req) => {
ws,
userId,
false,
preloadedHostData,
),
env: {
TERM: "xterm-256color",
@@ -2045,51 +2092,16 @@ wss.on("connection", async (ws: WebSocket, req) => {
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-group18-sha512",
"diffie-hellman-group17-sha512",
"diffie-hellman-group16-sha512",
"diffie-hellman-group15-sha512",
"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"],
},
algorithms: buildSSHAlgorithms(
hostConfig.terminalConfig?.allowLegacyAlgorithms !== false,
),
};
if (
resolvedCredentials.authType === "none" ||
resolvedCredentials.authType === "tailscale"
) {
// Tailscale SSH and "none" auth: daemon handles authorization, no credentials needed
// Tailscale SSH and "none": no static credentials needed
} else if (resolvedCredentials.authType === "password") {
if (!resolvedCredentials.password) {
sshLogger.error(
+77 -1
View File
@@ -1,6 +1,12 @@
import crypto from "crypto";
import { createRequire } from "module";
import type { ConnectConfig, CipherAlgorithm } from "ssh2";
import type {
ConnectConfig,
CipherAlgorithm,
KexAlgorithm,
ServerHostKeyAlgorithm,
MacAlgorithm,
} from "ssh2";
const nativeRequire = createRequire(import.meta.url);
const availableCiphers = new Set(crypto.getCiphers());
@@ -47,6 +53,76 @@ function filterCiphers(list: CipherAlgorithm[]): CipherAlgorithm[] {
});
}
const LEGACY_KEX: KexAlgorithm[] = [
"diffie-hellman-group14-sha1",
"diffie-hellman-group-exchange-sha1",
"diffie-hellman-group1-sha1",
];
const LEGACY_SERVER_HOST_KEY: ServerHostKeyAlgorithm[] = ["ssh-rsa", "ssh-dss"];
const LEGACY_HMAC: MacAlgorithm[] = ["hmac-sha1", "hmac-md5"];
const LEGACY_CIPHER = filterCiphers(["3des-cbc"]);
export function buildSSHAlgorithms(
allowLegacy: boolean,
): NonNullable<ConnectConfig["algorithms"]> {
const kex: KexAlgorithm[] = [
"curve25519-sha256",
"curve25519-sha256@libssh.org",
"ecdh-sha2-nistp521",
"ecdh-sha2-nistp384",
"ecdh-sha2-nistp256",
"diffie-hellman-group-exchange-sha256",
"diffie-hellman-group18-sha512",
"diffie-hellman-group17-sha512",
"diffie-hellman-group16-sha512",
"diffie-hellman-group15-sha512",
"diffie-hellman-group14-sha256",
];
const serverHostKey: ServerHostKeyAlgorithm[] = [
"ssh-ed25519",
"ecdsa-sha2-nistp521",
"ecdsa-sha2-nistp384",
"ecdsa-sha2-nistp256",
"rsa-sha2-512",
"rsa-sha2-256",
];
const hmac: MacAlgorithm[] = [
"hmac-sha2-512-etm@openssh.com",
"hmac-sha2-256-etm@openssh.com",
"hmac-sha2-512",
"hmac-sha2-256",
];
const cipher = filterCiphers([
"chacha20-poly1305@openssh.com",
"aes256-gcm@openssh.com",
"aes128-gcm@openssh.com",
"aes256-ctr",
"aes192-ctr",
"aes128-ctr",
"aes256-cbc",
"aes192-cbc",
"aes128-cbc",
]);
if (allowLegacy) {
kex.push(...LEGACY_KEX);
serverHostKey.push(...LEGACY_SERVER_HOST_KEY);
hmac.push(...LEGACY_HMAC);
cipher.push(...LEGACY_CIPHER);
}
return {
kex,
serverHostKey,
cipher,
hmac,
compress: ["none", "zlib@openssh.com", "zlib"],
};
}
export const SSH_ALGORITHMS: NonNullable<ConnectConfig["algorithms"]> = {
kex: [
"curve25519-sha256",
+67 -2
View File
@@ -1,5 +1,18 @@
import { describe, it, expect } from "vitest";
import { isValidMac, buildMagicPacket } from "./wake-on-lan.js";
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("dgram", () => {
const socket = {
once: vi.fn(),
bind: vi.fn(),
setBroadcast: vi.fn(),
send: vi.fn(),
close: vi.fn(),
};
return { default: { createSocket: vi.fn(() => socket) } };
});
import dgram from "dgram";
import { isValidMac, buildMagicPacket, sendWakeOnLan } from "./wake-on-lan.js";
describe("isValidMac", () => {
it("accepts colon-separated MAC addresses", () => {
@@ -49,3 +62,55 @@ describe("buildMagicPacket", () => {
expect(colon.equals(hyphen)).toBe(true);
});
});
describe("sendWakeOnLan", () => {
let mockSocket: ReturnType<typeof dgram.createSocket>;
beforeEach(() => {
vi.clearAllMocks();
mockSocket = (dgram.createSocket as ReturnType<typeof vi.fn>)();
(mockSocket.bind as ReturnType<typeof vi.fn>).mockImplementation(
(cb: () => void) => cb(),
);
(mockSocket.send as ReturnType<typeof vi.fn>).mockImplementation(
(
_buf: unknown,
_off: unknown,
_len: unknown,
_port: unknown,
_addr: unknown,
cb: (err: null) => void,
) => cb(null),
);
});
it("rejects on invalid MAC address", async () => {
await expect(sendWakeOnLan("not-a-mac")).rejects.toThrow(
"Invalid MAC address",
);
});
it("sends to 255.255.255.255 by default", async () => {
await sendWakeOnLan("aa:bb:cc:dd:ee:ff");
expect(mockSocket.send).toHaveBeenCalledWith(
expect.any(Buffer),
0,
102,
9,
"255.255.255.255",
expect.any(Function),
);
});
it("sends to a custom broadcast address when provided", async () => {
await sendWakeOnLan("aa:bb:cc:dd:ee:ff", "192.168.1.255");
expect(mockSocket.send).toHaveBeenCalledWith(
expect.any(Buffer),
0,
102,
9,
"192.168.1.255",
expect.any(Function),
);
});
});
+5 -2
View File
@@ -20,7 +20,10 @@ export function isValidMac(mac: string): boolean {
return MAC_REGEX.test(mac);
}
export function sendWakeOnLan(mac: string): Promise<void> {
export function sendWakeOnLan(
mac: string,
broadcastAddress = "255.255.255.255",
): Promise<void> {
return new Promise((resolve, reject) => {
if (!isValidMac(mac)) {
return reject(new Error("Invalid MAC address"));
@@ -36,7 +39,7 @@ export function sendWakeOnLan(mac: string): Promise<void> {
socket.bind(() => {
socket.setBroadcast(true);
socket.send(packet, 0, packet.length, 9, "255.255.255.255", (err) => {
socket.send(packet, 0, packet.length, 9, broadcastAddress, (err) => {
socket.close();
if (err) reject(err);
else resolve();
+17 -2
View File
@@ -70,6 +70,7 @@ function FullscreenApp() {
const view = searchParams.get("view");
const hostId = searchParams.get("hostId");
const tmuxSession = searchParams.get("tmuxSession");
const path = searchParams.get("path");
switch (view) {
case "terminal":
@@ -80,7 +81,12 @@ function FullscreenApp() {
/>
);
case "file-manager":
return <FileManagerApp hostId={hostId || undefined} />;
return (
<FileManagerApp
hostId={hostId || undefined}
initialPath={path || undefined}
/>
);
case "tunnel":
return <TunnelApp hostId={hostId || undefined} />;
case "host-metrics":
@@ -168,6 +174,11 @@ function App() {
}, 450);
}
function handleChangeServer() {
localStorage.setItem("termix_show_server_config", "true");
handleLogout();
}
const showApp =
phase === "idle-app" || phase === "fading-in" || phase === "fading-out";
const showAuth =
@@ -211,7 +222,11 @@ function App() {
}}
>
<Suspense fallback={null}>
<AppShell username={authUsername} onLogout={handleLogout} />
<AppShell
username={authUsername}
onLogout={handleLogout}
onChangeServer={handleChangeServer}
/>
</Suspense>
</div>
)}
+25
View File
@@ -35,6 +35,7 @@ export interface OIDCProviderConfig {
allowed_users?: string;
admin_group?: string;
group_claim?: string;
ca_cert?: string;
}
export interface LDAPProviderConfig {
@@ -64,6 +65,7 @@ export type SSHAuthType =
| "none"
| "opkssh"
| "tailscale";
export type GuacamoleAuthType = "password" | "credential";
export interface ProxmoxConfig {
@@ -101,6 +103,7 @@ export interface Host {
tags: string[];
pin: boolean;
authType: "password" | "key" | "credential" | "none" | "opkssh" | "tailscale";
useWarpgate?: boolean;
password?: string;
key?: string;
keyPassword?: string;
@@ -120,6 +123,7 @@ export interface Host {
enableCommandHistory: boolean;
enableTunnel: boolean;
enableFileManager: boolean;
scpLegacy?: boolean;
enableDocker: boolean;
enableProxmox: boolean;
enableTmuxMonitor: boolean;
@@ -145,6 +149,7 @@ export interface Host {
socks5ProxyChain?: ProxyNode[];
macAddress?: string;
wolBroadcastAddress?: string;
portKnockSequence?: Array<{
port: number;
protocol?: "tcp" | "udp";
@@ -165,15 +170,21 @@ export interface Host {
rdpPort?: number;
vncPort?: number;
telnetPort?: number;
rdpCredentialId?: number | null;
rdpUser?: string;
rdpPassword?: string;
rdpDomain?: string;
rdpSecurity?: string;
rdpIgnoreCert?: boolean;
vncCredentialId?: number | null;
vncPassword?: string;
vncUser?: string;
telnetUser?: string;
telnetPassword?: string;
telnetCredentialId?: number | null;
rdpAuthType?: "direct" | "credential" | null;
vncAuthType?: "direct" | "credential" | null;
telnetAuthType?: "direct" | "credential" | null;
createdAt: string;
updatedAt: string;
@@ -211,6 +222,7 @@ export interface HostData {
tags?: string[];
pin?: boolean;
authType: "password" | "key" | "credential" | "none" | "opkssh" | "tailscale";
useWarpgate?: boolean;
password?: string;
key?: File | null;
keyPassword?: string;
@@ -223,6 +235,7 @@ export interface HostData {
enableCommandHistory?: boolean;
enableTunnel?: boolean;
enableFileManager?: boolean;
scpLegacy?: boolean;
enableDocker?: boolean;
enableProxmox?: boolean;
enableTmuxMonitor?: boolean;
@@ -249,6 +262,7 @@ export interface HostData {
socks5ProxyChain?: ProxyNode[];
macAddress?: string;
wolBroadcastAddress?: string;
portKnockSequence?: Array<{
port: number;
protocol?: "tcp" | "udp";
@@ -270,15 +284,21 @@ export interface HostData {
rdpPort?: number;
vncPort?: number;
telnetPort?: number;
rdpCredentialId?: number | null;
rdpUser?: string;
rdpPassword?: string;
rdpDomain?: string;
rdpSecurity?: string;
rdpIgnoreCert?: boolean;
vncCredentialId?: number | null;
vncPassword?: string;
vncUser?: string;
telnetUser?: string;
telnetPassword?: string;
telnetCredentialId?: number | null;
rdpAuthType?: "direct" | "credential" | null;
vncAuthType?: "direct" | "credential" | null;
telnetAuthType?: "direct" | "credential" | null;
}
export type SSHHost = Host;
@@ -597,6 +617,11 @@ export interface TerminalConfig {
urls: boolean;
numbers: boolean;
};
backgroundImage?: string;
backgroundImageOpacity?: number;
allowLegacyAlgorithms?: boolean;
linkClickBehavior?: "confirm" | "direct";
useSSHTitle?: boolean;
}
// ============================================================================
+16 -2
View File
@@ -11,6 +11,7 @@ export type Host = {
lastAccess: string;
tags?: string[];
authType: "password" | "key" | "credential" | "none" | "opkssh" | "tailscale";
useWarpgate?: boolean;
credentialId?: string;
overrideCredentialUsername?: boolean;
password?: string;
@@ -24,6 +25,7 @@ export type Host = {
keyType?: string;
notes?: string;
macAddress?: string;
wolBroadcastAddress?: string;
pin?: boolean;
enableTerminal: boolean;
@@ -53,6 +55,7 @@ export type Host = {
keepaliveCountMax?: number;
environmentVariables: { key: string; value: string }[];
startupSnippetId?: number | null;
linkClickBehavior?: "confirm" | "direct";
};
useSocks5?: boolean;
@@ -88,6 +91,7 @@ export type Host = {
}[];
enableFileManager: boolean;
scpLegacy?: boolean;
defaultPath?: string;
enableDocker: boolean;
@@ -95,6 +99,7 @@ export type Host = {
enableTmuxMonitor: boolean;
proxmoxConfig?: {
defaultCredentialId: number | null;
defaultAuthType?: string;
windowsPatterns: string;
dockerPatterns: string;
preferredPrefixes: string;
@@ -121,12 +126,14 @@ export type Host = {
vncPort: number;
telnetPort: number;
rdpCredentialId?: string;
rdpUser?: string;
rdpPassword?: string;
domain?: string;
security?: string;
ignoreCert?: boolean;
vncCredentialId?: string;
vncPassword?: string;
vncUser?: string;
@@ -201,14 +208,17 @@ export type Tab = {
instanceId: string;
type: TabType;
label: string;
customLabel?: string;
host?: Host;
openedAt: number;
restoredSessionId?: string | null;
initialFilePath?: string;
terminalRef?: import("react").RefObject<{
sendInput?: (data: string) => void;
reconnect?: () => void;
fit?: () => void;
notifyResize?: () => void;
getApplicationCursorKeysMode?: () => boolean;
} | null>;
};
@@ -236,7 +246,8 @@ export type DashboardCardId =
| "quick_actions"
| "host_status"
| "recent_activity"
| "network_graph";
| "network_graph"
| "service_links";
export type DashboardCardConfig = {
id: DashboardCardId;
@@ -275,9 +286,11 @@ export type AdminSection =
| "users"
| "sessions"
| "roles"
| "host-defaults"
| "database"
| "api-keys"
| "audit-log";
| "audit-log"
| "ssl";
export type AccentColorId = string;
export type ThemeId =
| "dark"
@@ -309,6 +322,7 @@ export type Snippet = {
content: string;
folder: string | null;
order: number;
hostIds?: number[];
};
export const FOLDER_ICONS = [
+272 -5
View File
@@ -36,6 +36,7 @@ import type {
FontSizeId,
} from "@/types/ui-types";
import { applyAccentColor, applyFontSize, PANE_COUNTS } from "@/lib/theme";
import { globalShortcutHandler } from "@/lib/global-shortcut-handler";
import { useTheme } from "@/components/theme-provider";
import {
getSSHHosts,
@@ -80,7 +81,7 @@ function sshHostToHost(h: SSHHostWithStatus): Host {
enableSsh: h.enableSsh ?? (h.connectionType === "ssh" || !h.connectionType),
enableTerminal: h.enableTerminal ?? true,
enableTunnel: h.enableTunnel ?? false,
enableFileManager: h.enableFileManager ?? false,
enableFileManager: h.enableFileManager ?? true,
enableDocker: h.enableDocker ?? false,
enableProxmox: h.enableProxmox ?? false,
enableTmuxMonitor: h.enableTmuxMonitor ?? false, // --- tmux-monitor ---
@@ -108,6 +109,9 @@ function sshHostToHost(h: SSHHostWithStatus): Host {
socks5Username: h.socks5Username,
socks5Password: h.socks5Password,
socks5ProxyChain: h.socks5ProxyChain ?? [],
statsConfig: (typeof h.statsConfig === "string"
? JSON.parse(h.statsConfig)
: h.statsConfig) as Host["statsConfig"],
};
}
@@ -161,9 +165,11 @@ export { tabIcon, renderTabContent } from "@/shell/tabUtils";
export function AppShell({
username,
onLogout,
onChangeServer,
}: {
username: string;
onLogout: () => void;
onChangeServer?: () => void;
}) {
const { t, i18n } = useTranslation();
const { setTheme } = useTheme();
@@ -193,6 +199,9 @@ export function AppShell({
JSON.parse(localStorage.getItem("termix_paneTabIds") ?? "null") ??
Array(6).fill(null),
);
useEffect(() => {
paneTabIdsRef.current = paneTabIds;
}, [paneTabIds]);
const [focusedPaneIndex, setFocusedPaneIndex] = useState<number | null>(null);
const [realHostTree, setRealHostTree] = useState<HostFolder | null>(null);
const [hostsLoading, setHostsLoading] = useState(true);
@@ -204,7 +213,6 @@ export function AppShell({
const [sidebarOpen, setSidebarOpen] = useState(true);
const [railView, setRailView] = useState<RailView>("hosts");
const [profileDropdownOpen, setProfileDropdownOpen] = useState(false);
const [sidebarWidth, setSidebarWidth] = useState(() => {
const saved = localStorage.getItem("termix_sidebarWidth");
return saved ? parseInt(saved, 10) : 291;
@@ -243,6 +251,26 @@ export function AppShell({
}, []);
const lastShiftTime = useRef(0);
const tabsRef = useRef(tabs);
const activeTabIdRef = useRef(activeTabId);
const splitModeRef = useRef(splitMode);
const focusedPaneIndexRef = useRef<number | null>(null);
const paneContentElsRef = useRef<(HTMLDivElement | null)[]>(
Array(6).fill(null),
);
const paneTabIdsRef = useRef<(string | null)[]>(Array(6).fill(null));
useEffect(() => {
tabsRef.current = tabs;
}, [tabs]);
useEffect(() => {
activeTabIdRef.current = activeTabId;
}, [activeTabId]);
useEffect(() => {
splitModeRef.current = splitMode;
}, [splitMode]);
useEffect(() => {
focusedPaneIndexRef.current = focusedPaneIndex;
}, [focusedPaneIndex]);
const [commandPaletteShortcutEnabled, setCommandPaletteShortcutEnabled] =
useState<boolean>(() => {
const v = localStorage.getItem("commandPaletteShortcutEnabled");
@@ -254,6 +282,9 @@ export function AppShell({
const [paneContentEls, setPaneContentEls] = useState<
(HTMLDivElement | null)[]
>(Array(6).fill(null));
useEffect(() => {
paneContentElsRef.current = paneContentEls;
}, [paneContentEls]);
// Stable per-tab DOM nodes — created once per tab, never destroyed while the tab lives.
// We always portal each tab's content into its own node, then move that node between
@@ -314,6 +345,174 @@ export function AppShell({
return () => window.removeEventListener("keydown", handleKeyDown);
}, [commandPaletteShortcutEnabled]);
// Split-screen and tab navigation hotkeys
// Also registered in globalShortcutHandler so xterm can invoke directly
// without going through synthetic DOM events (which are unreliable).
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
// Ctrl+Shift+\ — toggle 2-way split (side by side)
if (e.ctrlKey && e.shiftKey && !e.altKey && e.code === "Backslash") {
e.preventDefault();
if (splitModeRef.current !== "none") {
splitModeRef.current = "none";
setSplitMode("none");
setPaneTabIds(Array(6).fill(null));
} else {
const mode = "2-way";
splitModeRef.current = mode;
const currentTabs = tabsRef.current;
const currentActiveId = activeTabIdRef.current;
const count = PANE_COUNTS[mode];
const next: (string | null)[] = Array(6).fill(null);
next[0] = currentActiveId;
let slot = 1;
for (const tab of currentTabs) {
if (slot >= count) break;
if (tab.id !== currentActiveId && tab.type !== "dashboard") {
next[slot] = tab.id;
slot++;
}
}
setSplitMode(mode);
setPaneTabIds(next);
}
return;
}
// Ctrl+Shift+- — toggle 3-way-horizontal split (top/bottom)
if (e.ctrlKey && e.shiftKey && !e.altKey && e.code === "Minus") {
e.preventDefault();
if (splitModeRef.current !== "none") {
splitModeRef.current = "none";
setSplitMode("none");
setPaneTabIds(Array(6).fill(null));
} else {
const mode = "3-way-horizontal";
splitModeRef.current = mode;
const currentTabs = tabsRef.current;
const currentActiveId = activeTabIdRef.current;
const count = PANE_COUNTS[mode];
const next: (string | null)[] = Array(6).fill(null);
next[0] = currentActiveId;
let slot = 1;
for (const tab of currentTabs) {
if (slot >= count) break;
if (tab.id !== currentActiveId && tab.type !== "dashboard") {
next[slot] = tab.id;
slot++;
}
}
setSplitMode(mode);
setPaneTabIds(next);
}
return;
}
// Alt+Arrow — navigate between panes in split mode
if (e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
if (
e.code === "ArrowLeft" ||
e.code === "ArrowRight" ||
e.code === "ArrowUp" ||
e.code === "ArrowDown"
) {
if (splitModeRef.current === "none") return;
const count = PANE_COUNTS[splitModeRef.current];
if (count < 2) return;
e.preventDefault();
const current = focusedPaneIndexRef.current ?? 0;
const mode = splitModeRef.current;
const dir = e.code;
// Layout-aware navigation maps: [left, right, up, down] per pane index.
// null means no movement in that direction.
const navMap: Record<string, (number | null)[][]> = {
"2-way": [
[null, 1, null, null],
[0, null, null, null],
],
"3-way": [
[null, 1, null, null],
[0, null, null, 2],
[0, null, 1, null],
],
"3-way-horizontal": [
[null, 1, null, 2],
[0, null, null, 2],
[null, null, 0, null],
],
"4-way": [
[null, 1, null, 2],
[0, null, null, 3],
[null, 3, 0, null],
[2, null, 1, null],
],
"5-way": [
[null, 1, null, 3],
[0, 2, null, 4],
[1, null, null, 4],
[null, 4, 0, null],
[3, null, 1, null],
],
"6-way": [
[null, 1, null, 3],
[0, 2, null, 4],
[1, null, null, 5],
[null, 4, 0, null],
[3, 5, 1, null],
[4, null, 2, null],
],
};
const paneNav = navMap[mode]?.[current];
const dirIndex =
{ ArrowLeft: 0, ArrowRight: 1, ArrowUp: 2, ArrowDown: 3 }[dir] ??
-1;
const next = paneNav?.[dirIndex] ?? null;
if (next === null) return;
focusedPaneIndexRef.current = next;
setFocusedPaneIndex(next);
// Physically move DOM focus into the target pane's terminal
const tabId = paneTabIdsRef.current[next];
if (tabId) {
const termRef = terminalRefs.current.get(tabId);
(
termRef?.current as
| import("@/features/terminal/Terminal").TerminalHandle
| null
)?.focus();
}
return;
}
}
// Ctrl+Shift+] / Ctrl+Shift+[ — cycle through open tabs (] = next, [ = previous)
if (e.ctrlKey && e.shiftKey && !e.altKey && !e.metaKey) {
if (e.code === "BracketRight" || e.code === "BracketLeft") {
e.preventDefault();
const currentTabs = tabsRef.current;
if (currentTabs.length < 2) return;
const currentId = activeTabIdRef.current;
const idx = currentTabs.findIndex((t) => t.id === currentId);
const next =
e.code === "BracketRight"
? (idx + 1) % currentTabs.length
: (idx - 1 + currentTabs.length) % currentTabs.length;
setActiveTabId(currentTabs[next].id);
return;
}
}
};
globalShortcutHandler.current = handleKeyDown;
window.addEventListener("keydown", handleKeyDown);
return () => {
globalShortcutHandler.current = null;
window.removeEventListener("keydown", handleKeyDown);
};
}, []);
useEffect(() => {
const handler = () => {
const v = localStorage.getItem("commandPaletteShortcutEnabled");
@@ -623,11 +822,17 @@ export function AppShell({
const restoredSessionId =
liveSession?.sessionId ?? saved.backendSessionId ?? null;
const isCustomLabel =
host &&
saved.label !== host.name &&
!/^.+ \(\d+\)$/.test(saved.label);
restoredTabs.push({
id: tabId,
instanceId: saved.id,
type: saved.tabType as TabType,
label: saved.label,
customLabel: isCustomLabel ? saved.label : undefined,
host,
openedAt: new Date(saved.createdAt).getTime(),
restoredSessionId,
@@ -694,7 +899,12 @@ export function AppShell({
const openTab = useCallback(function openTab(
host: Host,
type: TabType,
restore?: { instanceId: string; restoredSessionId: string | null },
restore?: {
instanceId: string;
restoredSessionId: string | null;
savedLabel?: string;
initialFilePath?: string;
},
) {
const tabId = `${host.name}-${type}-${Date.now()}`;
const instanceId =
@@ -707,7 +917,34 @@ export function AppShell({
if (ref) terminalRefs.current.set(tabId, ref);
let finalLabel = host.name;
const savedLabel = restore?.savedLabel;
const initialFilePath = restore?.initialFilePath;
// A saved label that doesn't match the bare host name or the auto-numbered pattern is a custom label
const isCustomLabel =
savedLabel != null &&
savedLabel !== host.name &&
!/^.+ \(\d+\)$/.test(savedLabel);
setTabs((prev) => {
if (isCustomLabel && savedLabel) {
finalLabel = savedLabel;
return [
...prev,
{
id: tabId,
instanceId,
type,
label: finalLabel,
customLabel: finalLabel,
host,
openedAt,
terminalRef: ref,
restoredSessionId: restore?.restoredSessionId ?? null,
initialFilePath,
},
];
}
const same = prev.filter(
(t) =>
t.type === type && t.label.replace(/ \(\d+\)$/, "") === host.name,
@@ -734,6 +971,7 @@ export function AppShell({
openedAt,
terminalRef: ref,
restoredSessionId: restore?.restoredSessionId ?? null,
initialFilePath,
},
];
});
@@ -789,6 +1027,9 @@ export function AppShell({
),
0,
);
} else if (pendingEvent === "host-manager:show-credentials") {
setSidebarOpen(true);
setRailView("credentials");
} else {
setSidebarOpen(true);
setRailView("hosts");
@@ -919,6 +1160,18 @@ export function AppShell({
doCloseTab(id);
}
function renameTab(tabId: string, newLabel: string) {
setTabs((prev) =>
prev.map((t) =>
t.id === tabId ? { ...t, customLabel: newLabel, label: newLabel } : t,
),
);
const tab = tabs.find((t) => t.id === tabId);
if (tab?.instanceId) {
patchOpenTab(tab.instanceId, { label: newLabel }).catch(() => {});
}
}
function splitTabQuick(tabId: string, mode: SplitMode) {
setSplitMode(mode);
setPaneTabIds(() => {
@@ -1182,6 +1435,7 @@ export function AppShell({
openTab(host, record.tabType as TabType, {
instanceId: record.id,
restoredSessionId: effectiveSessionId,
savedLabel: record.label,
});
} else {
openSingletonTab(record.tabType as TabType);
@@ -1193,6 +1447,8 @@ export function AppShell({
prev.filter((r) => r.id !== recordId),
);
}}
onRenameTab={renameTab}
onReorderTabs={setTabs}
/>
</div>
)}
@@ -1208,6 +1464,7 @@ export function AppShell({
<UserProfilePanel
username={username}
onLogout={onLogout}
onChangeServer={onChangeServer}
userPrefs={userPrefs}
onPrefsChange={setUserPrefs}
/>
@@ -1264,8 +1521,6 @@ export function AppShell({
splitMode={splitMode}
username={username}
isAdmin={isAdmin}
profileDropdownOpen={profileDropdownOpen}
onProfileDropdownChange={setProfileDropdownOpen}
onRailClick={handleRailClick}
onOpenTab={openSingletonTab}
onLogout={onLogout}
@@ -1334,6 +1589,7 @@ export function AppShell({
onSplitTab={splitTabQuick}
onAddToSplit={addTabToSplit}
onRemoveFromSplit={removeTabFromSplit}
onRenameTab={renameTab}
/>
<div className="relative flex flex-col flex-1 min-h-0 overflow-hidden">
{/* Split view — always mounted when not mobile, hidden via CSS when inactive */}
@@ -1388,6 +1644,17 @@ export function AppShell({
openTab,
closeTab,
inPane || activeInline,
(host, filePath) =>
openTab(host, "files", {
instanceId:
typeof crypto.randomUUID === "function"
? crypto.randomUUID()
: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,
restoredSessionId: null,
initialFilePath: filePath,
}),
(host, path) => openTab(host, "files"),
renameTab,
),
tabNode,
tab.id,
+47
View File
@@ -0,0 +1,47 @@
import { authApi, handleApiError } from "@/main-axios";
export type AcmeChallengeType = "http-webroot" | "dns-cloudflare";
export type AcmeSettings = {
enabled: boolean;
domain: string;
email: string;
challengeType: AcmeChallengeType;
cloudflareToken: string;
lastIssuedAt: string | null;
certStatus: "none" | "valid" | "expiring" | "expired";
certExpiresAt: string | null;
};
export async function getAcmeSslSettings(): Promise<AcmeSettings> {
try {
const response = await authApi.get("/users/acme-ssl-settings");
return response.data;
} catch (error) {
handleApiError(error, "fetch ACME SSL settings");
}
}
export async function updateAcmeSslSettings(
settings: Partial<
Omit<AcmeSettings, "certStatus" | "certExpiresAt" | "lastIssuedAt">
>,
): Promise<AcmeSettings> {
try {
const response = await authApi.patch("/users/acme-ssl-settings", settings);
return response.data;
} catch (error) {
handleApiError(error, "update ACME SSL settings");
}
}
export async function requestAcmeCertificate(): Promise<
AcmeSettings & { success: boolean }
> {
try {
const response = await authApi.post("/users/acme-ssl-request", {});
return response.data;
} catch (error) {
handleApiError(error, "request ACME certificate");
}
}
+53
View File
@@ -81,3 +81,56 @@ export async function resetRecentActivity(): Promise<{ message: string }> {
throw handleApiError(error, "reset recent activity");
}
}
export interface ServiceLink {
id: number;
userId: string;
label: string;
url: string;
order: number;
createdAt: string;
}
export async function getServiceLinks(): Promise<ServiceLink[]> {
try {
const response = await dashboardApi.get("/service-links");
return response.data;
} catch (error) {
throw handleApiError(error, "fetch service links");
}
}
export async function createServiceLink(
label: string,
url: string,
): Promise<ServiceLink> {
try {
const response = await dashboardApi.post("/service-links", { label, url });
return response.data;
} catch (error) {
throw handleApiError(error, "create service link");
}
}
export async function deleteServiceLink(
id: number,
): Promise<{ message: string }> {
try {
const response = await dashboardApi.delete(`/service-links/${id}`);
return response.data;
} catch (error) {
throw handleApiError(error, "delete service link");
}
}
export async function updateServiceLink(
id: number,
updates: { label?: string; url?: string },
): Promise<ServiceLink> {
try {
const response = await dashboardApi.put(`/service-links/${id}`, updates);
return response.data;
} catch (error) {
throw handleApiError(error, "update service link");
}
}
+2
View File
@@ -94,6 +94,8 @@ export interface UserPreferences {
disableUpdateCheck?: boolean | null;
confirmTabClose?: boolean | null;
hiddenRailTabs?: string | null;
compactHostView?: boolean | null;
statusColorScheme?: string | null;
}
export async function getUserPreferences(): Promise<UserPreferences> {
+40
View File
@@ -146,3 +146,43 @@ export async function updateGuacamoleSettings(settings: {
}
// ============================================================================
// HOST DEFAULTS SETTINGS
// ============================================================================
export type HostDefaults = {
useSocks5?: boolean;
socks5Host?: string;
socks5Port?: number;
socks5Username?: string;
socks5Password?: string;
credentialId?: number | null;
metricsEnabled?: boolean;
statusCheckEnabled?: boolean;
fontSize?: number;
fontFamily?: string;
theme?: string;
cursorStyle?: string;
cursorBlink?: boolean;
enableSessionLogging?: boolean;
enableCommandHistory?: boolean;
};
export async function getHostDefaults(): Promise<HostDefaults> {
try {
const response = await authApi.get("/users/host-defaults");
return response.data;
} catch (error) {
handleApiError(error, "fetch host defaults");
}
}
export async function updateHostDefaults(
defaults: HostDefaults,
): Promise<HostDefaults> {
try {
const response = await authApi.patch("/users/host-defaults", defaults);
return response.data;
} catch (error) {
handleApiError(error, "update host defaults");
}
}
+49
View File
@@ -181,3 +181,52 @@ export async function reorderSnippets(
throw handleApiError(error, "reorder snippets");
}
}
export interface SnippetExportData {
snippets: Array<{
name: string;
content: string;
description?: string | null;
folder?: string | null;
order?: number;
hostFilter?: string | null;
}>;
folders: Array<{
name: string;
color?: string | null;
icon?: string | null;
}>;
}
export async function exportSnippets(): Promise<SnippetExportData> {
try {
const response = await authApi.get("/snippets/export");
return response.data;
} catch (error) {
throw handleApiError(error, "export snippets");
}
}
export async function importSnippets(
data: SnippetExportData,
overwrite: boolean,
): Promise<{
success: boolean;
snippetsImported: number;
snippetsSkipped: number;
snippetsUpdated: number;
foldersImported: number;
foldersSkipped: number;
failed: number;
errors: string[];
}> {
try {
const response = await authApi.post("/snippets/bulk-import", {
...data,
overwrite,
});
return response.data;
} catch (error) {
throw handleApiError(error, "import snippets");
}
}
+26 -19
View File
@@ -51,10 +51,11 @@ export async function connectSSH(
},
): Promise<Record<string, unknown>> {
try {
const response = await fileManagerApi.post("/ssh/connect", {
sessionId,
...config,
});
const response = await fileManagerApi.post(
"/ssh/connect",
{ sessionId, ...config },
{ timeout: 120000 },
);
return response.data;
} catch (error: unknown) {
if (
@@ -344,18 +345,20 @@ export async function uploadSSHFile(
sessionId: string,
path: string,
fileName: string,
content: string,
file: File,
hostId?: number,
userId?: string,
): Promise<Record<string, unknown>> {
try {
const response = await fileManagerApi.post("/ssh/uploadFile", {
sessionId,
path,
fileName,
content,
hostId,
userId,
const form = new FormData();
form.append("sessionId", sessionId);
form.append("path", path);
if (hostId !== undefined) form.append("hostId", String(hostId));
if (userId !== undefined) form.append("userId", userId);
form.append("file", file, fileName);
const response = await fileManagerApi.post("/ssh/uploadFileStream", form, {
timeout: 0,
});
return response.data;
} catch (error) {
@@ -370,12 +373,16 @@ export async function downloadSSHFile(
userId?: string,
): Promise<Record<string, unknown>> {
try {
const response = await fileManagerApi.post("/ssh/downloadFile", {
sessionId,
path: filePath,
hostId,
userId,
});
const response = await fileManagerApi.post(
"/ssh/downloadFile",
{
sessionId,
path: filePath,
hostId,
userId,
},
{ timeout: 0 },
);
return response.data;
} catch (error) {
handleApiError(error, "download SSH file");
@@ -389,7 +396,7 @@ export async function downloadSSHFileStream(
const response = await fileManagerApi.post(
"/ssh/downloadFileStream",
{ sessionId, path: filePath },
{ responseType: "blob" },
{ responseType: "blob", timeout: 0 },
);
const blob = response.data as Blob;
const fileName = filePath.split("/").pop() || "download";
+22
View File
@@ -107,6 +107,28 @@ export async function bulkImportSSHHosts(
}
}
export async function importSSHConfigHosts(
content: string,
overwrite = false,
): Promise<{
message: string;
success: number;
updated: number;
skipped: number;
failed: number;
errors: string[];
}> {
try {
const response = await sshHostApi.post("/ssh-config-import", {
content,
overwrite,
});
return response.data;
} catch (error) {
handleApiError(error, "import SSH config hosts");
}
}
export async function discoverProxmoxGuests(
hostId: number,
): Promise<ProxmoxDiscoverResult> {
+24
View File
@@ -196,6 +196,30 @@ export async function updateOidcAutoProvision(
}
}
export async function getOidcSilentLoginDefault(): Promise<{
enabled: boolean;
}> {
try {
const response = await authApi.get("/users/oidc-silent-login-default");
return response.data;
} catch (error) {
handleApiError(error, "get OIDC silent login default");
}
}
export async function updateOidcSilentLoginDefault(
enabled: boolean,
): Promise<{ enabled: boolean }> {
try {
const response = await authApi.patch("/users/oidc-silent-login-default", {
enabled,
});
return response.data;
} catch (error) {
handleApiError(error, "update OIDC silent login default");
}
}
export async function updatePasswordLoginAllowed(
allowed: boolean,
): Promise<{ allowed: boolean }> {
+66 -9
View File
@@ -34,6 +34,7 @@ import {
isElectron,
getEmbeddedServerStatus,
getCurrentToken,
getOidcSilentLoginDefault,
} from "@/main-axios";
import { getSSOProviders, ldapLogin } from "@/api/sso-provider-api";
import type { SSOProviderPublic } from "@/types/index";
@@ -256,6 +257,9 @@ export function Auth({ onLogin }: AuthProps) {
const [ldapUsername, setLdapUsername] = useState("");
const [ldapPassword, setLdapPassword] = useState("");
const silentSigninHandledRef = useRef(false);
const [oidcSilentLoginDefault, setOidcSilentLoginDefault] = useState(false);
const [oidcSilentLoginDefaultLoaded, setOidcSilentLoginDefaultLoaded] =
useState(false);
const [firstUser, setFirstUser] = useState(false);
const [dbConnectionFailed, setDbConnectionFailed] = useState(false);
const [dbHealthChecking, setDbHealthChecking] = useState(true);
@@ -288,6 +292,10 @@ export function Auth({ onLogin }: AuthProps) {
.then((providers) => setSsoProviders(providers || []))
.catch(() => setSsoProviders([]))
.finally(() => setSsoProvidersLoaded(true));
getOidcSilentLoginDefault()
.then((res) => setOidcSilentLoginDefault(res.enabled))
.catch(() => {})
.finally(() => setOidcSilentLoginDefaultLoaded(true));
}, []);
useEffect(() => {
@@ -312,6 +320,18 @@ export function Auth({ onLogin }: AuthProps) {
return;
}
if (isElectron()) {
const forceShow = localStorage.getItem("termix_show_server_config");
if (forceShow === "true") {
localStorage.removeItem("termix_show_server_config");
try {
const config = await getServerConfig();
setCurrentServerUrl(config?.serverUrl || "");
} catch {
// ignore
}
setShowServerConfig(true);
return;
}
try {
const [config, status] = await Promise.all([
getServerConfig(),
@@ -732,6 +752,29 @@ export function Auth({ onLogin }: AuthProps) {
const loadingKey = providerId ?? -1;
setProviderLoading((prev) => ({ ...prev, [loadingKey]: true }));
try {
if (isInElectronWebView()) {
// Inside the Electron iframe: delegate OIDC to the parent window so
// the system browser opens instead of navigating the iframe (which
// would break captcha stages like Cloudflare Turnstile).
const callbackPort = 17832 + Math.floor(Math.random() * 100);
const authResponse = await getOIDCAuthorizeUrl(
rememberMe,
callbackPort,
providerId,
);
const { auth_url: authUrl } = authResponse;
if (!authUrl) throw new Error(t("errors.invalidAuthUrl"));
window.parent.postMessage(
{
type: "OIDC_SYSTEM_BROWSER_AUTH",
source: "oidc_request",
authUrl,
callbackPort,
},
"*",
);
return;
}
if (isElectron()) {
const electronAPI = (
window as unknown as {
@@ -834,14 +877,19 @@ export function Auth({ onLogin }: AuthProps) {
useEffect(() => {
if (!ssoProvidersLoaded || silentSigninHandledRef.current) return;
if (!shouldTriggerSilentSignin(window.location.search)) return;
if (!oidcSilentLoginDefaultLoaded) return;
const nextSearch = removeSilentSigninFromSearch(window.location.search);
window.history.replaceState(
{},
document.title,
`${window.location.pathname}${nextSearch}${window.location.hash}`,
);
const urlTriggered = shouldTriggerSilentSignin(window.location.search);
if (!urlTriggered && !oidcSilentLoginDefault) return;
if (urlTriggered) {
const nextSearch = removeSilentSigninFromSearch(window.location.search);
window.history.replaceState(
{},
document.title,
`${window.location.pathname}${nextSearch}${window.location.hash}`,
);
}
silentSigninHandledRef.current = true;
@@ -853,8 +901,17 @@ export function Auth({ onLogin }: AuthProps) {
return;
}
toast.info(t("errors.silentSigninOidcUnavailable"));
}, [handleOIDCLogin, ssoProvidersLoaded, ssoProviders, t]);
if (urlTriggered) {
toast.info(t("errors.silentSigninOidcUnavailable"));
}
}, [
handleOIDCLogin,
ssoProvidersLoaded,
ssoProviders,
t,
oidcSilentLoginDefault,
oidcSilentLoginDefaultLoaded,
]);
// Electron server config / webview auth success screens
if (isElectron() && !isInElectronWebView()) {
+31 -1
View File
@@ -63,13 +63,43 @@ export function ElectronLoginForm({
try {
if (event.source !== iframeRef.current?.contentWindow) return;
if (!event.data || typeof event.data !== "object") return;
const { type, platform, source, token } = event.data;
const { type, platform, source, token, authUrl, callbackPort } =
event.data;
if (
type === "AUTH_SUCCESS" &&
platform === "desktop" &&
AUTH_MESSAGE_SOURCES.has(source)
) {
await handleAuthSuccess(token ?? null);
return;
}
// OIDC login requested from inside the iframe — open the system browser
// so captcha stages (e.g. Cloudflare Turnstile) render correctly.
if (type === "OIDC_SYSTEM_BROWSER_AUTH" && authUrl && callbackPort) {
const electronAPI = (
window as unknown as {
electronAPI?: {
oidcSystemBrowserAuth?: (
url: string,
port: number,
) => Promise<{
success: boolean;
token?: string;
error?: string;
}>;
};
}
).electronAPI;
if (!electronAPI?.oidcSystemBrowserAuth) return;
const result = await electronAPI.oidcSystemBrowserAuth(
authUrl,
callbackPort,
);
if (result.success && result.token) {
await handleAuthSuccess(result.token);
}
}
} catch {
// ignore
+114 -10
View File
@@ -1,4 +1,4 @@
import React, { useState, useEffect } from "react";
import React, { useState, useEffect, useRef } from "react";
import { Button } from "@/components/button.tsx";
import { Input } from "@/components/input.tsx";
import { Label } from "@/components/label.tsx";
@@ -12,7 +12,34 @@ import {
setEmbeddedMode,
type ServerConfig,
} from "@/main-axios.ts";
import { Server, Monitor, Loader2 } from "lucide-react";
import { Server, Monitor, Loader2, ChevronDown, X } from "lucide-react";
const SAVED_URLS_KEY = "termix_saved_server_urls";
const MAX_SAVED_URLS = 5;
function getSavedUrls(): string[] {
try {
const raw = localStorage.getItem(SAVED_URLS_KEY);
if (!raw) return [];
return JSON.parse(raw);
} catch {
return [];
}
}
function addSavedUrl(url: string) {
const urls = getSavedUrls().filter((u) => u !== url);
urls.unshift(url);
localStorage.setItem(
SAVED_URLS_KEY,
JSON.stringify(urls.slice(0, MAX_SAVED_URLS)),
);
}
function removeSavedUrl(url: string) {
const urls = getSavedUrls().filter((u) => u !== url);
localStorage.setItem(SAVED_URLS_KEY, JSON.stringify(urls));
}
interface ServerConfigProps {
onServerConfigured: (serverUrl: string) => void;
@@ -36,12 +63,31 @@ export function ElectronServerConfig({
const [embeddedAvailable, setEmbeddedAvailable] = useState<boolean | null>(
null,
);
const [savedUrls, setSavedUrls] = useState<string[]>([]);
const [dropdownOpen, setDropdownOpen] = useState(false);
const dropdownRef = useRef<HTMLDivElement>(null);
useEffect(() => {
loadServerConfig();
checkEmbeddedBackend();
setSavedUrls(getSavedUrls());
}, []);
useEffect(() => {
function handleClickOutside(e: MouseEvent) {
if (
dropdownRef.current &&
!dropdownRef.current.contains(e.target as Node)
) {
setDropdownOpen(false);
}
}
if (dropdownOpen) {
document.addEventListener("mousedown", handleClickOutside);
}
return () => document.removeEventListener("mousedown", handleClickOutside);
}, [dropdownOpen]);
const loadServerConfig = async () => {
try {
const config = await getServerConfig();
@@ -151,6 +197,8 @@ export function ElectronServerConfig({
const success = await saveServerConfig(config);
if (success) {
addSavedUrl(normalizedUrl);
setSavedUrls(getSavedUrls());
onServerConfigured(normalizedUrl);
} else {
setError(t("serverConfig.saveFailed"));
@@ -220,14 +268,70 @@ export function ElectronServerConfig({
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-1.5">
<Label htmlFor="server-url">{t("serverConfig.serverUrl")}</Label>
<Input
id="server-url"
type="text"
placeholder="https://your-server.com"
value={serverUrl}
onChange={(e) => handleUrlChange(e.target.value)}
disabled={loading || embeddedLoading}
/>
<div className="relative" ref={dropdownRef}>
<Input
id="server-url"
type="text"
placeholder="https://your-server.com"
value={serverUrl}
onChange={(e) => handleUrlChange(e.target.value)}
disabled={loading || embeddedLoading}
className={savedUrls.length > 0 ? "pr-9" : ""}
onFocus={() => {
if (savedUrls.length > 0) setDropdownOpen(true);
}}
/>
{savedUrls.length > 0 && (
<button
type="button"
tabIndex={-1}
onClick={() => setDropdownOpen((o) => !o)}
disabled={loading || embeddedLoading}
className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
aria-label={t("serverConfig.savedServers")}
>
<ChevronDown className="size-4" />
</button>
)}
{dropdownOpen && savedUrls.length > 0 && (
<div className="absolute z-50 w-full top-full mt-1 border border-border bg-card shadow-md">
<p className="px-2.5 py-1.5 text-[10px] font-bold uppercase tracking-widest text-muted-foreground border-b border-border">
{t("serverConfig.savedServers")}
</p>
{savedUrls.map((url) => (
<div
key={url}
className="flex items-center justify-between group hover:bg-muted transition-colors"
>
<button
type="button"
className="flex-1 text-left px-2.5 py-2 text-sm font-mono truncate"
onClick={() => {
handleUrlChange(url);
setDropdownOpen(false);
}}
>
{url}
</button>
<button
type="button"
className="px-2 py-2 text-muted-foreground hover:text-destructive transition-colors shrink-0"
title={t("serverConfig.removeServer")}
onClick={(e) => {
e.stopPropagation();
removeSavedUrl(url);
const updated = getSavedUrls();
setSavedUrls(updated);
if (updated.length === 0) setDropdownOpen(false);
}}
>
<X className="size-3.5" />
</button>
</div>
))}
</div>
)}
</div>
</div>
{serverUrl.trim().startsWith("https://") && (
+174 -107
View File
@@ -29,6 +29,7 @@ import {
isElectron,
getEmbeddedServerStatus,
getCurrentToken,
getOidcSilentLoginDefault,
} from "@/main-axios";
import { getSSOProviders, ldapLogin } from "@/api/sso-provider-api";
import type { SSOProviderPublic } from "@/types/index";
@@ -129,6 +130,9 @@ export function Auth({
const [ldapPassword, setLdapPassword] = useState("");
const [ldapLoading, setLdapLoading] = useState(false);
const silentSigninHandledRef = useRef(false);
const [oidcSilentLoginDefault, setOidcSilentLoginDefault] = useState(false);
const [oidcSilentLoginDefaultLoaded, setOidcSilentLoginDefaultLoaded] =
useState(false);
const [resetStep, setResetStep] = useState<
"initiate" | "verify" | "newPassword"
@@ -258,6 +262,17 @@ export function Auth({
});
}, []);
useEffect(() => {
getOidcSilentLoginDefault()
.then((res) => {
setOidcSilentLoginDefault(res.enabled);
})
.catch(() => {})
.finally(() => {
setOidcSilentLoginDefaultLoaded(true);
});
}, []);
useEffect(() => {
if (showServerConfig) {
return;
@@ -683,8 +698,19 @@ export function Auth({
setLdapLoading(true);
try {
await ldapLogin(providerId, ldapUsername, ldapPassword, rememberMe);
const userInfo = await getUserInfo();
onLogin(userInfo);
const meRes = await getUserInfo();
setInternalLoggedIn(true);
setLoggedIn(true);
setIsAdmin(!!meRes.is_admin);
setUsername(meRes.username || null);
setUserId(meRes.userId || null);
setDbError(null);
onAuthSuccess({
isAdmin: !!meRes.is_admin,
username: meRes.username || null,
userId: meRes.userId || null,
});
toast.success(t("messages.loginSuccess"));
} catch (err: unknown) {
const error = err as {
response?: { data?: { error?: string } };
@@ -699,19 +725,35 @@ export function Auth({
setLdapLoading(false);
}
},
[ldapUsername, ldapPassword, rememberMe, onLogin, t],
[
ldapUsername,
ldapPassword,
rememberMe,
onAuthSuccess,
setLoggedIn,
setIsAdmin,
setUsername,
setUserId,
setDbError,
t,
],
);
useEffect(() => {
if (!ssoProvidersLoaded || silentSigninHandledRef.current) return;
if (!shouldTriggerSilentSignin(window.location.search)) return;
if (!oidcSilentLoginDefaultLoaded) return;
const nextSearch = removeSilentSigninFromSearch(window.location.search);
window.history.replaceState(
{},
document.title,
`${window.location.pathname}${nextSearch}${window.location.hash}`,
);
const urlTriggered = shouldTriggerSilentSignin(window.location.search);
if (!urlTriggered && !oidcSilentLoginDefault) return;
if (urlTriggered) {
const nextSearch = removeSilentSigninFromSearch(window.location.search);
window.history.replaceState(
{},
document.title,
`${window.location.pathname}${nextSearch}${window.location.hash}`,
);
}
silentSigninHandledRef.current = true;
const oidcProvider = ssoProviders.find(
@@ -728,8 +770,17 @@ export function Auth({
return;
}
toast.info(t("errors.silentSigninOidcUnavailable"));
}, [handleOIDCLogin, ssoProvidersLoaded, ssoProviders, t]);
if (urlTriggered) {
toast.info(t("errors.silentSigninOidcUnavailable"));
}
}, [
handleOIDCLogin,
ssoProvidersLoaded,
ssoProviders,
t,
oidcSilentLoginDefault,
oidcSilentLoginDefaultLoaded,
]);
useEffect(() => {
const urlParams = new URLSearchParams(window.location.search);
@@ -1515,106 +1566,122 @@ export function Auth({
className="flex flex-col gap-5"
onSubmit={handleSubmit}
>
<div className="flex flex-col gap-2">
<Label htmlFor="username">
{t("common.username")}
</Label>
<Input
id="username"
type="text"
required
className="h-11 text-base"
value={localUsername}
onChange={(e) =>
setLocalUsername(e.target.value)
}
disabled={loading || loggedIn}
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="password">
{t("common.password")}
</Label>
<PasswordInput
id="password"
required
className="h-11 text-base"
value={password}
onChange={(e) => setPassword(e.target.value)}
disabled={loading || loggedIn}
/>
</div>
{tab === "login" && (
<div className="flex items-center gap-2">
<Checkbox
id="rememberMe"
checked={rememberMe}
onCheckedChange={(checked) =>
setRememberMe(checked === true)
}
disabled={loading || loggedIn}
/>
<Label
htmlFor="rememberMe"
className="text-sm font-normal cursor-pointer"
{!passwordLoginAllowed &&
!firstUser &&
tab === "login" ? (
<p className="text-center text-muted-foreground text-sm">
{t("auth.passwordLoginDisabledDesc")}
</p>
) : (
<>
<div className="flex flex-col gap-2">
<Label htmlFor="username">
{t("common.username")}
</Label>
<Input
id="username"
type="text"
required
className="h-11 text-base"
value={localUsername}
onChange={(e) =>
setLocalUsername(e.target.value)
}
disabled={loading || loggedIn}
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="password">
{t("common.password")}
</Label>
<PasswordInput
id="password"
required
className="h-11 text-base"
value={password}
onChange={(e) =>
setPassword(e.target.value)
}
disabled={loading || loggedIn}
/>
</div>
{tab === "login" && (
<div className="flex items-center gap-2">
<Checkbox
id="rememberMe"
checked={rememberMe}
onCheckedChange={(checked) =>
setRememberMe(checked === true)
}
disabled={loading || loggedIn}
/>
<Label
htmlFor="rememberMe"
className="text-sm font-normal cursor-pointer"
>
{t("auth.rememberMe")}
</Label>
</div>
)}
{tab === "signup" && (
<div className="flex flex-col gap-2">
<Label htmlFor="signup-confirm-password">
{t("common.confirmPassword")}
</Label>
<PasswordInput
id="signup-confirm-password"
required
className="h-11 text-base"
value={signupConfirmPassword}
onChange={(e) =>
setSignupConfirmPassword(e.target.value)
}
disabled={loading || loggedIn}
/>
</div>
)}
<Button
type="submit"
className="w-full h-11 mt-2 text-base font-semibold"
disabled={loading || internalLoggedIn}
>
{t("auth.rememberMe")}
</Label>
</div>
)}
{tab === "signup" && (
<div className="flex flex-col gap-2">
<Label htmlFor="signup-confirm-password">
{t("common.confirmPassword")}
</Label>
<PasswordInput
id="signup-confirm-password"
required
className="h-11 text-base"
value={signupConfirmPassword}
onChange={(e) =>
setSignupConfirmPassword(e.target.value)
}
disabled={loading || loggedIn}
/>
</div>
)}
<Button
type="submit"
className="w-full h-11 mt-2 text-base font-semibold"
disabled={loading || internalLoggedIn}
>
{loading
? Spinner
: tab === "login"
? t("common.login")
: t("auth.signUp")}
</Button>
{tab === "login" && (
<Button
type="button"
variant="outline"
className="w-full h-11 text-base font-semibold"
disabled={loading || loggedIn}
onClick={() => {
setTab("reset");
resetPasswordState();
clearFormFields();
}}
>
{t("auth.resetPasswordButton")}
</Button>
{loading
? Spinner
: tab === "login"
? t("common.login")
: t("auth.signUp")}
</Button>
{tab === "login" && (
<Button
type="button"
variant="outline"
className="w-full h-11 text-base font-semibold"
disabled={loading || loggedIn}
onClick={() => {
setTab("reset");
resetPasswordState();
clearFormFields();
}}
>
{t("auth.resetPasswordButton")}
</Button>
)}
</>
)}
{ssoProviders.length > 0 && !isElectron() && (
<div className="flex flex-col gap-3 pt-2">
<div className="flex items-center gap-3">
<div className="flex-1 border-t border-border" />
<span className="text-xs text-muted-foreground px-1 whitespace-nowrap">
{t("auth.orContinueWith")}
</span>
<div className="flex-1 border-t border-border" />
</div>
{(passwordLoginAllowed ||
firstUser ||
tab === "signup") && (
<div className="flex items-center gap-3">
<div className="flex-1 border-t border-border" />
<span className="text-xs text-muted-foreground px-1 whitespace-nowrap">
{t("auth.orContinueWith")}
</span>
<div className="flex-1 border-t border-border" />
</div>
)}
{ssoProviders.map((provider) => {
if (provider.type === "ldap") {
const isExpanded =
@@ -34,6 +34,8 @@ interface ProxmoxDiscoverDialogProps {
preselectedHostId?: number;
/** Credential to use for imported hosts */
defaultCredentialId?: number | null;
/** Auth type to use for imported hosts */
defaultAuthType?: string;
/** Username from the default credential */
defaultUsername?: string;
}
@@ -45,6 +47,7 @@ export function ProxmoxDiscoverDialog({
onHostsChanged,
preselectedHostId,
defaultCredentialId,
defaultAuthType,
defaultUsername,
}: ProxmoxDiscoverDialogProps) {
const { t } = useTranslation();
@@ -115,6 +118,8 @@ export function ProxmoxDiscoverDialog({
try {
// Prefer explicitly configured credential, then fall back to the host's own credential
const credId = defaultCredentialId ?? discoveredCredentialId;
const resolvedAuthType =
defaultAuthType ?? (credId != null ? "credential" : "password");
const toImport = guests
.filter((g) => selected.has(g.vmid))
@@ -124,13 +129,13 @@ export function ProxmoxDiscoverDialog({
port: g.connectionType === "rdp" ? 3389 : 22,
username: defaultUsername ?? "root",
folder: importFolder,
...(credId != null
authType: resolvedAuthType,
...(resolvedAuthType === "credential" && credId != null
? {
authType: "credential" as const,
credentialId: credId,
overrideCredentialUsername: true,
}
: { authType: "password" as const }),
: {}),
enableTerminal: g.connectionType !== "rdp",
enableFileManager: g.connectionType !== "rdp",
enableTunnel: g.connectionType !== "rdp",
+275 -53
View File
@@ -6,10 +6,12 @@ import { Separator } from "@/components/separator";
import {
Activity,
Database,
ExternalLink,
GripHorizontal,
GripVertical,
KeyRound,
LayoutDashboard,
Link,
MessagesSquare,
Network,
Plus,
@@ -37,10 +39,21 @@ import {
registerMetricsViewer,
sendMetricsHeartbeat,
getUserInfo,
getServiceLinks,
createServiceLink,
deleteServiceLink,
} from "@/main-axios";
import type {
RecentActivityItem,
SSHHostWithStatus,
ServiceLink,
} from "@/main-axios";
import type { RecentActivityItem, SSHHostWithStatus } from "@/main-axios";
import { useTranslation } from "react-i18next";
import { NetworkGraphCard } from "@/dashboard/cards/NetworkGraphCard";
import {
useStatusColorScheme,
getStatusClasses,
} from "@/hooks/use-status-color-scheme";
function sshHostToHost(h: SSHHostWithStatus): Host {
return {
@@ -66,7 +79,7 @@ function sshHostToHost(h: SSHHostWithStatus): Host {
macAddress: h.macAddress,
enableTerminal: h.enableTerminal ?? true,
enableTunnel: h.enableTunnel ?? false,
enableFileManager: h.enableFileManager ?? false,
enableFileManager: h.enableFileManager ?? true,
enableDocker: h.enableDocker ?? false,
enableSsh: h.connectionType === "ssh" || !h.connectionType,
enableRdp: h.connectionType === "rdp",
@@ -205,35 +218,48 @@ function CountersBarCard({
hosts,
credentialCount,
activeTunnelCount,
onOpenSingletonTab,
}: {
hosts: Host[];
credentialCount: number;
activeTunnelCount: number;
onOpenSingletonTab: (type: TabType, pendingEvent?: string) => void;
}) {
const { t } = useTranslation();
return (
<Card className="grid grid-cols-3 divide-x divide-border overflow-hidden w-full h-full py-0 gap-0">
<div className="flex items-center gap-2.5 px-4 py-2.5">
<button
onClick={() => onOpenSingletonTab("host-manager")}
className="flex items-center gap-2.5 px-4 py-2.5 hover:bg-muted transition-colors cursor-pointer text-left"
>
<Server className="size-3.5 text-muted-foreground shrink-0" />
<span className="text-base font-bold">{hosts.length}</span>
<span className="text-[10px] text-muted-foreground uppercase tracking-widest font-semibold">
{t("dashboard.totalHosts")}
</span>
</div>
<div className="flex items-center gap-2.5 px-4 py-2.5">
</button>
<button
onClick={() =>
onOpenSingletonTab("host-manager", "host-manager:show-credentials")
}
className="flex items-center gap-2.5 px-4 py-2.5 hover:bg-muted transition-colors cursor-pointer text-left"
>
<KeyRound className="size-3.5 text-muted-foreground shrink-0" />
<span className="text-base font-bold">{credentialCount}</span>
<span className="text-[10px] text-muted-foreground uppercase tracking-widest font-semibold">
{t("dashboard.totalCredentials")}
</span>
</div>
<div className="flex items-center gap-2.5 px-4 py-2.5">
</button>
<button
onClick={() => onOpenSingletonTab("tunnel")}
className="flex items-center gap-2.5 px-4 py-2.5 hover:bg-muted transition-colors cursor-pointer text-left"
>
<Network className="size-3.5 text-muted-foreground shrink-0" />
<span className="text-base font-bold">{activeTunnelCount}</span>
<span className="text-[10px] text-muted-foreground uppercase tracking-widest font-semibold">
{t("dashboardTab.activeTunnels")}
</span>
</div>
</button>
</Card>
);
}
@@ -365,16 +391,48 @@ function QuickActionsCard({
);
}
function MetricBar({ label, value }: { label: string; value: number }) {
const color =
value >= 90
? "bg-red-500"
: value >= 70
? "bg-yellow-500"
: "bg-accent-brand";
const textColor =
value >= 90
? "text-red-400"
: value >= 70
? "text-yellow-400"
: "text-accent-brand";
return (
<div className="flex flex-col gap-0.5 w-16">
<div className="flex items-center justify-between">
<span className="text-[10px] text-muted-foreground">{label}</span>
<span className={`text-[10px] font-bold ${textColor}`}>
{value.toFixed(0)}%
</span>
</div>
<div className="h-0.5 bg-muted w-full">
<div className={`h-full ${color}`} style={{ width: `${value}%` }} />
</div>
</div>
);
}
function HostStatusCard({
hosts,
hostMetrics,
onOpenTab,
}: {
hosts: Host[];
hostMetrics: Map<string, { cpu: number | null; ram: number | null }>;
hostMetrics: Map<
string,
{ cpu: number | null; ram: number | null; disk: number | null }
>;
onOpenTab: (host: Host, type: TabType) => void;
}) {
const { t } = useTranslation();
const statusScheme = useStatusColorScheme();
const online = hosts.filter((h) => h.online).length;
return (
<Card className="flex flex-col overflow-hidden w-full h-full py-0 gap-0">
@@ -399,19 +457,23 @@ function HostStatusCard({
const metrics = hostMetrics.get(host.id);
const cpu = metrics?.cpu ?? null;
const ram = metrics?.ram ?? null;
const hasMetrics = cpu !== null || ram !== null;
const disk = metrics?.disk ?? null;
const hasMetrics = cpu !== null || ram !== null || disk !== null;
return (
<div
key={i}
onClick={() => onOpenTab(host, "host-metrics")}
className="flex items-center justify-between px-4 py-2.5 border-b border-border last:border-0 hover:bg-muted/50 cursor-pointer"
className="flex items-center justify-between px-4 py-2.5 border-b border-border last:border-0 hover:bg-muted/50 cursor-pointer group/row"
>
<div className="flex items-center gap-2.5">
<span
className={`size-1.5 rounded-full shrink-0 ${host.online ? "bg-accent-brand" : "bg-muted-foreground/40"}`}
className={`size-1.5 rounded-full shrink-0 ${getStatusClasses(host.online, statusScheme, "dot")}`}
/>
<div className="flex flex-col">
<span className="text-xs font-semibold">{host.name}</span>
<div className="flex items-center gap-1">
<span className="text-xs font-semibold">{host.name}</span>
<ExternalLink className="size-2.5 text-muted-foreground/0 group-hover/row:text-muted-foreground/60 transition-colors shrink-0" />
</div>
<span className="text-[10px] text-muted-foreground font-mono">
{host.ip}
</span>
@@ -421,40 +483,13 @@ function HostStatusCard({
{host.online && hasMetrics ? (
<div className="flex items-center gap-3">
{cpu !== null && (
<div className="flex flex-col gap-0.5 w-16">
<div className="flex items-center justify-between">
<span className="text-[10px] text-muted-foreground">
{t("dashboard.cpu")}
</span>
<span className="text-[10px] font-bold text-accent-brand">
{cpu.toFixed(0)}%
</span>
</div>
<div className="h-0.5 bg-muted w-full">
<div
className="h-full bg-accent-brand"
style={{ width: `${cpu}%` }}
/>
</div>
</div>
<MetricBar label={t("dashboard.cpu")} value={cpu} />
)}
{ram !== null && (
<div className="flex flex-col gap-0.5 w-16">
<div className="flex items-center justify-between">
<span className="text-[10px] text-muted-foreground">
{t("dashboard.ram")}
</span>
<span className="text-[10px] font-bold text-accent-brand">
{ram.toFixed(0)}%
</span>
</div>
<div className="h-0.5 bg-muted w-full">
<div
className="h-full bg-accent-brand"
style={{ width: `${ram}%` }}
/>
</div>
</div>
<MetricBar label={t("dashboard.ram")} value={ram} />
)}
{disk !== null && (
<MetricBar label={t("dashboardTab.disk")} value={disk} />
)}
</div>
) : (
@@ -465,10 +500,13 @@ function HostStatusCard({
<span className="text-[10px] text-muted-foreground w-16 text-center">
</span>
<span className="text-[10px] text-muted-foreground w-16 text-center">
</span>
</div>
)}
<span
className={`text-[10px] px-2 py-0.5 font-semibold border ${host.online ? "border-accent-brand/40 text-accent-brand bg-accent-brand/10" : "border-border text-muted-foreground"}`}
className={`text-[10px] px-2 py-0.5 font-semibold border ${getStatusClasses(host.online, statusScheme, "badge")}`}
>
{host.online
? t("dashboardTab.online")
@@ -495,6 +533,7 @@ function RecentActivityCard({
onClear: () => void;
}) {
const { t } = useTranslation();
const statusScheme = useStatusColorScheme();
const typeIcon: Record<RecentActivityItem["type"], React.ReactNode> = {
terminal: <Terminal className="size-2.5" />,
file_manager: <Server className="size-2.5" />,
@@ -570,7 +609,7 @@ function RecentActivityCard({
>
<div className="flex items-center gap-2">
<span
className={`size-1.5 rounded-full shrink-0 ${host?.online ? "bg-accent-brand" : "bg-muted-foreground/40"}`}
className={`size-1.5 rounded-full shrink-0 ${getStatusClasses(host?.online ?? false, statusScheme, "dot")}`}
/>
<div className="flex flex-col">
<span className="text-xs font-semibold truncate max-w-24">
@@ -593,6 +632,124 @@ function RecentActivityCard({
);
}
function ServiceLinksCard({
links,
onAdd,
onDelete,
}: {
links: ServiceLink[];
onAdd: (label: string, url: string) => Promise<void>;
onDelete: (id: number) => Promise<void>;
}) {
const { t } = useTranslation();
const [label, setLabel] = useState("");
const [url, setUrl] = useState("");
const [urlError, setUrlError] = useState(false);
const [adding, setAdding] = useState(false);
const handleAdd = async () => {
let valid = true;
try {
const parsed = new URL(url);
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
valid = false;
}
} catch {
valid = false;
}
if (!valid) {
setUrlError(true);
return;
}
setUrlError(false);
setAdding(true);
try {
await onAdd(label.trim(), url.trim());
setLabel("");
setUrl("");
} finally {
setAdding(false);
}
};
return (
<Card className="flex flex-col overflow-hidden w-full h-full py-0 gap-0">
<div className="flex items-center gap-2 px-4 py-2.5 border-b border-border shrink-0">
<Link className="size-3.5 text-muted-foreground" />
<span className="text-xs text-muted-foreground uppercase tracking-widest font-semibold">
{t("dashboardTab.serviceLinksTitle")}
</span>
</div>
<div className="flex flex-col overflow-auto flex-1">
{links.length === 0 && (
<div className="flex-1 flex items-center justify-center text-xs text-muted-foreground/40 py-4">
{t("dashboardTab.serviceLinksEmpty")}
</div>
)}
{links.map((link) => (
<div
key={link.id}
className="flex items-center justify-between px-4 py-2 border-b border-border last:border-0 group/link"
>
<a
href={link.url}
target="_blank"
rel="noreferrer noopener"
className="flex items-center gap-2 min-w-0 flex-1 hover:text-accent-brand transition-colors"
>
<ExternalLink className="size-3 text-muted-foreground shrink-0" />
<span className="text-xs font-semibold truncate">
{link.label}
</span>
<span className="text-[10px] text-muted-foreground truncate">
{link.url}
</span>
</a>
<button
onClick={() => onDelete(link.id)}
className="ml-2 opacity-0 group-hover/link:opacity-100 transition-opacity size-5 flex items-center justify-center hover:text-destructive"
>
<Trash2 className="size-3" />
</button>
</div>
))}
</div>
<div className="flex items-center gap-2 px-4 py-2 border-t border-border shrink-0">
<input
type="text"
value={label}
onChange={(e) => setLabel(e.target.value)}
placeholder={t("dashboardTab.serviceLinksLabelPlaceholder")}
className="flex-1 min-w-0 text-xs bg-transparent border border-border px-2 py-1 focus:outline-none focus:border-accent-brand/60"
/>
<input
type="text"
value={url}
onChange={(e) => {
setUrl(e.target.value);
setUrlError(false);
}}
placeholder={t("dashboardTab.serviceLinksUrlPlaceholder")}
className={`flex-[2] min-w-0 text-xs bg-transparent border px-2 py-1 focus:outline-none ${urlError ? "border-destructive" : "border-border focus:border-accent-brand/60"}`}
/>
<Button
size="sm"
className="text-xs bg-accent-brand hover:bg-accent-brand/90 text-white h-6 px-2 shrink-0"
onClick={handleAdd}
disabled={!label.trim() || !url.trim() || adding}
>
{t("dashboardTab.serviceLinksAdd")}
</Button>
</div>
{urlError && (
<div className="px-4 pb-2 text-[10px] text-destructive shrink-0">
{t("dashboardTab.serviceLinksInvalidUrl")}
</div>
)}
</Card>
);
}
// ─── CardItem ─────────────────────────────────────────────────────────────────
function CardItem({
@@ -617,6 +774,9 @@ function CardItem({
activity,
onClearActivity,
isAdmin,
serviceLinks,
onAddServiceLink,
onDeleteServiceLink,
}: {
slot: CardSlot;
editMode: boolean;
@@ -629,7 +789,10 @@ function CardItem({
onOpenSingletonTab: (type: TabType, pendingEvent?: string) => void;
onOpenTab: (host: Host, type: TabType) => void;
hosts: Host[];
hostMetrics: Map<string, { cpu: number | null; ram: number | null }>;
hostMetrics: Map<
string,
{ cpu: number | null; ram: number | null; disk: number | null }
>;
uptimeFormatted: string;
versionText: string;
versionStatus: "up_to_date" | "requires_update" | "beta";
@@ -639,6 +802,9 @@ function CardItem({
activity: RecentActivityItem[];
onClearActivity: () => void;
isAdmin: boolean;
serviceLinks: ServiceLink[];
onAddServiceLink: (label: string, url: string) => Promise<void>;
onDeleteServiceLink: (id: number) => Promise<void>;
}) {
const cardRef = useRef<HTMLDivElement | null>(null);
@@ -704,6 +870,7 @@ function CardItem({
hosts={hosts}
credentialCount={credentialCount}
activeTunnelCount={activeTunnelCount}
onOpenSingletonTab={onOpenSingletonTab}
/>
)}
{slot.id === "quick_actions" && (
@@ -735,6 +902,13 @@ function CardItem({
onOpenInNewTab={() => onOpenSingletonTab("network_graph")}
/>
)}
{slot.id === "service_links" && (
<ServiceLinksCard
links={serviceLinks}
onAdd={onAddServiceLink}
onDelete={onDeleteServiceLink}
/>
)}
</div>
{editMode && !isFlex && (
<div
@@ -831,7 +1005,10 @@ type PanelColumnProps = {
onOpenSingletonTab: (type: TabType, pendingEvent?: string) => void;
onOpenTab: (host: Host, type: TabType) => void;
hosts: Host[];
hostMetrics: Map<string, { cpu: number | null; ram: number | null }>;
hostMetrics: Map<
string,
{ cpu: number | null; ram: number | null; disk: number | null }
>;
uptimeFormatted: string;
versionText: string;
versionStatus: "up_to_date" | "requires_update" | "beta";
@@ -842,6 +1019,9 @@ type PanelColumnProps = {
onClearActivity: () => void;
cardLabels: Record<DashboardCardId, string>;
isAdmin: boolean;
serviceLinks: ServiceLink[];
onAddServiceLink: (label: string, url: string) => Promise<void>;
onDeleteServiceLink: (id: number) => Promise<void>;
};
function PanelColumn({
@@ -869,6 +1049,9 @@ function PanelColumn({
onClearActivity,
cardLabels,
isAdmin,
serviceLinks,
onAddServiceLink,
onDeleteServiceLink,
}: PanelColumnProps) {
const { t } = useTranslation();
const sorted = [...slots].sort((a, b) => a.order - b.order);
@@ -921,6 +1104,9 @@ function PanelColumn({
activity={activity}
onClearActivity={onClearActivity}
isAdmin={isAdmin}
serviceLinks={serviceLinks}
onAddServiceLink={onAddServiceLink}
onDeleteServiceLink={onDeleteServiceLink}
/>
</div>
))}
@@ -1028,7 +1214,7 @@ export function DashboardTab({
const [activeTunnelCount, setActiveTunnelCount] = useState(0);
const [activity, setActivity] = useState<RecentActivityItem[]>([]);
const [hostMetrics, setHostMetrics] = useState<
Map<string, { cpu: number | null; ram: number | null }>
Map<string, { cpu: number | null; ram: number | null; disk: number | null }>
>(new Map());
const viewerSessionsRef = useRef<Map<number, string>>(new Map());
@@ -1066,6 +1252,7 @@ export function DashboardTab({
id: host.id,
cpu: metrics.cpu?.percent ?? null,
ram: metrics.memory?.percent ?? null,
disk: metrics.disk?.percent ?? null,
};
} catch {
return null;
@@ -1074,9 +1261,12 @@ export function DashboardTab({
);
viewerSessionsRef.current = newSessions;
const map = new Map<string, { cpu: number | null; ram: number | null }>();
const map = new Map<
string,
{ cpu: number | null; ram: number | null; disk: number | null }
>();
for (const r of results) {
if (r) map.set(r.id, { cpu: r.cpu, ram: r.ram });
if (r) map.set(r.id, { cpu: r.cpu, ram: r.ram, disk: r.disk });
}
setHostMetrics(map);
}, []);
@@ -1169,6 +1359,24 @@ export function DashboardTab({
}
};
const [serviceLinks, setServiceLinks] = useState<ServiceLink[]>([]);
useEffect(() => {
getServiceLinks()
.then(setServiceLinks)
.catch(() => {});
}, []);
const handleAddServiceLink = async (label: string, url: string) => {
const created = await createServiceLink(label, url);
setServiceLinks((prev) => [...prev, created]);
};
const handleDeleteServiceLink = async (id: number) => {
await deleteServiceLink(id);
setServiceLinks((prev) => prev.filter((l) => l.id !== id));
};
const todayLabel = new Date().toLocaleDateString(i18n.language, {
weekday: "long",
month: "long",
@@ -1192,6 +1400,7 @@ export function DashboardTab({
host_status: t("dashboardTab.hostStatus"),
recent_activity: t("dashboard.recentActivity"),
network_graph: t("dashboard.networkGraph"),
service_links: t("dashboard.serviceLinks"),
};
const onColumnDividerMouseDown = useCallback(
@@ -1264,7 +1473,9 @@ export function DashboardTab({
? 350
: id === "host_status" || id === "recent_activity"
? null
: 150;
: id === "service_links"
? 200
: 150;
return [...prev, { id, panel, order: maxOrder, height: defaultHeight }];
});
};
@@ -1299,6 +1510,9 @@ export function DashboardTab({
onOpenTab,
cardLabels,
isAdmin,
serviceLinks,
onAddServiceLink: handleAddServiceLink,
onDeleteServiceLink: handleDeleteServiceLink,
};
const isMobile = useIsMobile();
@@ -1393,6 +1607,7 @@ export function DashboardTab({
hosts={hosts}
credentialCount={credentialCount}
activeTunnelCount={activeTunnelCount}
onOpenSingletonTab={onOpenSingletonTab}
/>
)}
{slot.id === "quick_actions" && (
@@ -1424,6 +1639,13 @@ export function DashboardTab({
onOpenInNewTab={() => onOpenSingletonTab("network_graph")}
/>
)}
{slot.id === "service_links" && (
<ServiceLinksCard
links={serviceLinks}
onAdd={handleAddServiceLink}
onDelete={handleDeleteServiceLink}
/>
)}
</div>
))}
</div>
+11 -5
View File
@@ -128,11 +128,17 @@ function buildNodeSvg(
): string {
const isOnline = status === "online";
const isOffline = status === "offline";
const statusColor = isOnline
? "rgb(16,185,129)"
: isOffline
? "rgb(239,68,68)"
: "rgb(100,116,139)";
const useRealColors = localStorage.getItem("statusColorScheme") === "status";
let statusColor: string;
if (isOnline) {
statusColor = useRealColors
? "rgb(16,185,129)"
: resolveCssVar("--accent-brand", "rgb(16,185,129)");
} else if (isOffline) {
statusColor = useRealColors ? "rgb(239,68,68)" : "rgba(16,185,129,0.2)";
} else {
statusColor = "rgb(100,116,139)";
}
const bg = resolveCssVar("--card", "#1e1e20");
const border = resolveCssVar("--border", "#2a2a2c");
@@ -204,7 +204,7 @@ export function LogViewer({
</div>
</div>
<div className="flex-1 bg-[#111210] border border-border p-3 overflow-auto font-mono text-xs leading-relaxed scrollbar-thin min-h-0">
<div className="flex-1 bg-muted border border-border p-3 overflow-auto font-mono text-xs leading-relaxed scrollbar-thin min-h-0">
{filteredLogs.length > 0 ? (
filteredLogs.map((line, i) => {
const tsEnd = line.indexOf(" ", 1);
+196 -35
View File
@@ -24,6 +24,7 @@ import { useConfirmation } from "@/hooks/use-confirmation.ts";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { FileManagerDialogs } from "./FileManagerDialogs.tsx";
import { PassphraseDialog } from "@/ssh/dialogs/PassphraseDialog.tsx";
import { FileManagerToolbar } from "./FileManagerToolbar.tsx";
import { TransferToHostDialog } from "./components/TransferToHostDialog.tsx";
import { TerminalWindow } from "./components/TerminalWindow.tsx";
@@ -78,7 +79,12 @@ import type {
} from "./file-manager-types.ts";
import { formatFileSize } from "./file-manager-utils.ts";
function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
function FileManagerContent({
initialHost,
initialFilePath,
initialPath,
onClose,
}: FileManagerProps) {
const { openWindow } = useWindowManager();
const { t } = useTranslation();
const formatTransferMetrics = useMemo(
@@ -94,10 +100,10 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
const [currentHost] = useState<SSHHost | null>(initialHost || null);
const [currentPath, setCurrentPath] = useState(
initialHost?.defaultPath || "/",
initialPath || initialHost?.defaultPath || "/",
);
const [navHistory, setNavHistory] = useState<string[]>([
initialHost?.defaultPath || "/",
initialPath || initialHost?.defaultPath || "/",
]);
const [navIndex, setNavIndex] = useState(0);
const [files, setFiles] = useState<FileItem[]>([]);
@@ -133,6 +139,7 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
const [authDialogReason, setAuthDialogReason] = useState<
"no_keyboard" | "auth_failed" | "timeout"
>("no_keyboard");
const [showPassphraseDialog, setShowPassphraseDialog] = useState(false);
const [pinnedFiles, setPinnedFiles] = useState<Set<string>>(new Set());
const [sidebarRefreshTrigger, setSidebarRefreshTrigger] = useState(0);
const [hasConnectionError, setHasConnectionError] = useState<boolean>(false);
@@ -267,6 +274,60 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
};
}, [sshSessionId, startKeepalive, stopKeepalive]);
const initialFileOpenedRef = useRef(false);
useEffect(() => {
if (!sshSessionId || !initialFilePath || initialFileOpenedRef.current)
return;
initialFileOpenedRef.current = true;
const fileName = initialFilePath.split("/").pop() || initialFilePath;
const fileDir =
initialFilePath.lastIndexOf("/") > 0
? initialFilePath.substring(0, initialFilePath.lastIndexOf("/"))
: "/";
setCurrentPath(fileDir);
const file: FileItem = {
name: fileName,
path: initialFilePath,
type: "file",
};
const windowCount = Date.now() % 10;
const offsetX = Math.min(
120 + windowCount * 30,
Math.max(0, window.innerWidth - 820),
);
const offsetY = Math.min(
120 + windowCount * 30,
Math.max(0, window.innerHeight - 620),
);
const createWindowComponent = (windowId: string) => (
<FileWindow
windowId={windowId}
file={file}
sshSessionId={sshSessionId}
sshHost={currentHost}
initialX={offsetX}
initialY={offsetY}
onFileNotFound={handleFileNotFound}
/>
);
openWindow({
title: fileName,
x: offsetX,
y: offsetY,
width: 800,
height: 600,
isMaximized: false,
isMinimized: false,
component: createWindowComponent,
});
}, [sshSessionId, initialFilePath]);
const initialLoadDoneRef = useRef(false);
const lastPathChangeRef = useRef<string>("");
const pathChangeTimerRef = useRef<NodeJS.Timeout | null>(null);
@@ -416,6 +477,12 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
return;
}
if (result?.status === "passphrase_required") {
setShowPassphraseDialog(true);
setIsLoading(false);
return;
}
setSshSessionId(sessionId);
try {
@@ -839,24 +906,11 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
"/"
: currentPath;
const fileContent = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onerror = () => reject(reader.error);
reader.onload = () => {
if (typeof reader.result === "string") {
resolve(reader.result.split(",")[1] || "");
} else {
reject(new Error("Failed to read file"));
}
};
reader.readAsDataURL(file);
});
await uploadSSHFile(
sshSessionId,
uploadPath,
file.name,
fileContent,
file,
currentHost?.id,
);
}
@@ -896,26 +950,11 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
try {
await ensureSSHConnection();
const fileContent = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onerror = () => reject(reader.error);
reader.onload = () => {
if (typeof reader.result === "string") {
const base64 = reader.result.split(",")[1] || "";
resolve(base64);
} else {
reject(new Error("Failed to read file"));
}
};
reader.readAsDataURL(file);
});
await uploadSSHFile(
sshSessionId,
currentPath,
file.name,
fileContent,
file,
currentHost?.id,
undefined,
);
@@ -1357,6 +1396,23 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
});
}
function handleCopyFolderLink(path: string) {
if (!currentHost?.id) return;
const params = new URLSearchParams({
view: "file-manager",
hostId: String(currentHost.id),
path,
});
const url = `${window.location.origin}?${params.toString()}`;
copyToClipboard(url).then((ok) => {
if (ok) {
toast.success(t("fileManager.folderLinkCopied"));
} else {
toast.error(t("fileManager.failedToCopyFolderLink"));
}
});
}
async function handlePasteFiles() {
if (!clipboard || !sshSessionId) return;
@@ -2120,6 +2176,85 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
if (onClose) onClose();
}
async function handlePassphraseSubmit(passphrase: string) {
if (!currentHost) return;
try {
setIsLoading(true);
setShowPassphraseDialog(false);
const sessionId = currentHost.id.toString();
const result = await connectSSH(sessionId, {
hostId: currentHost.id,
ip: currentHost.ip,
port: currentHost.port,
username: currentHost.username,
sshKey: currentHost.key,
keyPassword: passphrase,
authType: "key",
credentialId: currentHost.credentialId,
userId: currentHost.userId,
jumpHosts: currentHost.jumpHosts,
useSocks5: currentHost.useSocks5,
socks5Host: currentHost.socks5Host,
socks5Port: currentHost.socks5Port,
socks5Username: currentHost.socks5Username,
socks5Password: currentHost.socks5Password,
socks5ProxyChain: currentHost.socks5ProxyChain,
});
if (result?.status === "passphrase_required") {
setShowPassphraseDialog(true);
setIsLoading(false);
toast.error(t("fileManager.incorrectPassphrase"));
return;
}
if (result?.requires_totp) {
setTotpRequired(true);
setTotpSessionId(sessionId);
setTotpPrompt(result.prompt || t("fileManager.verificationCodePrompt"));
setIsLoading(false);
return;
}
if (result?.status === "auth_required") {
setAuthDialogReason(result.reason || "auth_failed");
setShowAuthDialog(true);
setIsLoading(false);
return;
}
setSshSessionId(sessionId);
try {
const response = await listSSHFiles(sessionId, currentPath);
const files = Array.isArray(response)
? response
: response?.files || [];
setFiles(files);
clearSelection();
initialLoadDoneRef.current = true;
toast.success(t("fileManager.connectedSuccessfully"));
logFileManagerActivity();
} catch (dirError: unknown) {
console.error("Failed to load initial directory:", dirError);
}
} catch (error: unknown) {
console.error("SSH connection with passphrase failed:", error);
setShowPassphraseDialog(true);
toast.error(t("fileManager.incorrectPassphrase"));
} finally {
setIsLoading(false);
}
}
function handlePassphraseCancel() {
setShowPassphraseDialog(false);
if (onClose) onClose();
}
function generateUniqueName(
baseName: string,
type: "file" | "directory",
@@ -2749,6 +2884,7 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
onExtractArchive={handleExtractArchive}
onCompress={handleOpenCompressDialog}
onCopyPath={handleCopyPath}
onCopyFolderLink={handleCopyFolderLink}
onTransferToHost={handleOpenTransferDialog}
/>
</div>
@@ -2768,6 +2904,21 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
/>
)}
{currentHost && (
<PassphraseDialog
isOpen={showPassphraseDialog}
onSubmit={handlePassphraseSubmit}
onCancel={handlePassphraseCancel}
hostInfo={{
ip: currentHost.ip,
port: currentHost.port,
username: currentHost.username,
name: currentHost.name,
}}
backgroundColor="var(--bg-canvas)"
/>
)}
<FileManagerDialogs
compressDialogFiles={compressDialogFiles}
setCompressDialogFiles={setCompressDialogFiles}
@@ -2805,10 +2956,20 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
);
}
function FileManagerInner({ initialHost, onClose }: FileManagerProps) {
function FileManagerInner({
initialHost,
initialFilePath,
initialPath,
onClose,
}: FileManagerProps) {
return (
<WindowManager>
<FileManagerContent initialHost={initialHost} onClose={onClose} />
<FileManagerContent
initialHost={initialHost}
initialFilePath={initialFilePath}
initialPath={initialPath}
onClose={onClose}
/>
</WindowManager>
);
}
@@ -5,9 +5,13 @@ import { FullScreenAppWrapper } from "@/features/FullScreenAppWrapper.tsx";
interface FileManagerAppProps {
hostId?: string;
initialPath?: string;
}
const FileManagerApp: React.FC<FileManagerAppProps> = ({ hostId }) => {
const FileManagerApp: React.FC<FileManagerAppProps> = ({
hostId,
initialPath,
}) => {
const { t } = useTranslation();
return (
<FullScreenAppWrapper hostId={hostId}>
@@ -39,6 +43,7 @@ const FileManagerApp: React.FC<FileManagerAppProps> = ({ hostId }) => {
<FileManager
embedded={true}
initialHost={hostConfig}
initialPath={initialPath}
onClose={() => {}}
/>
);
@@ -19,6 +19,7 @@ import {
Bookmark,
FileArchive,
ArrowRightLeft,
Link,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import { Kbd, KbdKey, KbdSeparator } from "@/components/kbd.tsx";
@@ -67,6 +68,7 @@ interface ContextMenuProps {
onExtractArchive?: (file: FileItem) => void;
onCompress?: (files: FileItem[]) => void;
onCopyPath?: (files: FileItem[]) => void;
onCopyFolderLink?: (path: string) => void;
onTransferToHost?: (files: FileItem[], move: boolean) => void;
}
@@ -110,6 +112,7 @@ export function FileManagerContextMenu({
onExtractArchive,
onCompress,
onCopyPath,
onCopyFolderLink,
onTransferToHost,
}: ContextMenuProps) {
const { t } = useTranslation();
@@ -350,12 +353,22 @@ export function FileManagerContextMenu({
});
}
if (isSingleFile && files[0].type === "directory" && onCopyFolderLink) {
menuItems.push({
icon: <Link className="size-3.5" />,
label: t("fileManager.copyFolderLink"),
action: () => onCopyFolderLink(files[0].path),
});
}
if (
(hasFiles && (onPreview || onDragToDesktop)) ||
(isSingleFile &&
files[0].type === "file" &&
(onPinFile || onUnpinFile)) ||
(isSingleFile && files[0].type === "directory" && onAddShortcut)
(isSingleFile &&
files[0].type === "directory" &&
(onAddShortcut || onCopyFolderLink))
) {
menuItems.push({ separator: true } as MenuItem);
}
@@ -491,6 +504,15 @@ export function FileManagerContextMenu({
shortcut: "Ctrl+V",
});
}
if (onCopyFolderLink && currentPath) {
menuItems.push({ separator: true } as MenuItem);
menuItems.push({
icon: <Link className="size-3.5" />,
label: t("fileManager.copyCurrentFolderLink"),
action: () => onCopyFolderLink(currentPath),
});
}
}
const filteredMenuItems = menuItems.filter((item, index) => {
@@ -173,9 +173,11 @@ export function FileManagerSidebar({
try {
const response = await listSSHFiles(sshSessionId, "/");
const rootFiles = (response.files || []) as DirectoryItemData[];
const rootFolders = rootFiles.filter(
(item: DirectoryItemData) => item.type === "directory",
);
const rootFolders = rootFiles
.filter((item: DirectoryItemData) => item.type === "directory")
.sort((a, b) =>
a.name.localeCompare(b.name, undefined, { sensitivity: "base" }),
);
const rootTreeItems = rootFolders.map((folder: DirectoryItemData) => ({
id: `folder-${folder.name}`,
@@ -232,9 +234,11 @@ export function FileManagerSidebar({
try {
const subResponse = await listSSHFiles(sshSessionId, folderPath);
const subFiles = (subResponse.files || []) as DirectoryItemData[];
const subFolders = subFiles.filter(
(item: DirectoryItemData) => item.type === "directory",
);
const subFolders = subFiles
.filter((item: DirectoryItemData) => item.type === "directory")
.sort((a, b) =>
a.name.localeCompare(b.name, undefined, { sensitivity: "base" }),
);
const subTreeItems = subFolders.map((folder: DirectoryItemData) => ({
id: `folder-${folder.path.replace(/\//g, "-")}`,
@@ -23,6 +23,7 @@ interface CodeEditorProps {
onChange: (value: string) => void;
onFocus: () => void;
onBlur: () => void;
fontSize?: number;
}
function getLanguageExtension(filename: string) {
@@ -73,7 +74,7 @@ function getLanguageExtension(filename: string) {
export const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(
function CodeEditor(
{ fileName, value, placeholder, onChange, onFocus, onBlur },
{ fileName, value, placeholder, onChange, onFocus, onBlur, fontSize = 14 },
ref,
) {
const editorRef = useRef<{ view?: EditorView } | null>(null);
@@ -105,6 +106,7 @@ export const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(
EditorView.theme({
"&": {
height: "100%",
fontSize: `${fontSize}px`,
},
".cm-scroller": {
overflow: "auto",
@@ -116,7 +118,7 @@ export const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(
},
}),
];
}, [fileName]);
}, [fileName, fontSize]);
useImperativeHandle(
ref,
@@ -17,6 +17,8 @@ import {
RotateCcw,
Keyboard,
Search,
ZoomIn,
ZoomOut,
} from "lucide-react";
import {
SiJavascript,
@@ -85,6 +87,7 @@ interface FileViewerProps {
savedContent?: string;
isLoading?: boolean;
isEditable?: boolean;
resetKey?: number;
onContentChange?: (content: string) => void;
onSave?: (content: string) => void;
onRevert?: () => void;
@@ -265,6 +268,7 @@ export function FileViewer({
savedContent = "",
isLoading = false,
isEditable = false,
resetKey,
onContentChange,
onSave,
onRevert,
@@ -280,8 +284,31 @@ export function FileViewer({
const [showKeyboardShortcuts, setShowKeyboardShortcuts] = useState(false);
const [editorFocused, setEditorFocused] = useState(false);
const [markdownEditMode, setMarkdownEditMode] = useState(false);
const [editorFontSize, setEditorFontSize] = useState<number>(() => {
const stored = localStorage.getItem("fileManagerEditorFontSize");
return stored ? parseInt(stored, 10) : 14;
});
const editorRef = useRef<CodeEditorHandle | null>(null);
const MIN_FONT_SIZE = 8;
const MAX_FONT_SIZE = 32;
const decreaseFontSize = () => {
setEditorFontSize((prev) => {
const next = Math.max(MIN_FONT_SIZE, prev - 1);
localStorage.setItem("fileManagerEditorFontSize", String(next));
return next;
});
};
const increaseFontSize = () => {
setEditorFontSize((prev) => {
const next = Math.min(MAX_FONT_SIZE, prev + 1);
localStorage.setItem("fileManagerEditorFontSize", String(next));
return next;
});
};
const fileTypeInfo = getFileType(file.name);
const WARNING_SIZE = 50 * 1024 * 1024;
@@ -301,6 +328,9 @@ export function FileViewer({
if (savedContent) {
setOriginalContent(savedContent);
}
}, [file.name, file.path, resetKey]);
useEffect(() => {
setHasChanges(content !== savedContent);
if (fileTypeInfo.type === "unknown" && isLargeFile && !forceShowAsText) {
@@ -308,14 +338,7 @@ export function FileViewer({
} else {
setShowLargeFileWarning(false);
}
}, [
content,
savedContent,
fileTypeInfo.type,
isLargeFile,
forceShowAsText,
file.name,
]);
}, [content, savedContent, fileTypeInfo.type, isLargeFile, forceShowAsText]);
const handleContentChange = (newContent: string) => {
setEditedContent(newContent);
@@ -417,6 +440,33 @@ export function FileViewer({
<Search className="w-4 h-4" />
</Button>
)}
{isEditable && (
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
onClick={decreaseFontSize}
disabled={editorFontSize <= MIN_FONT_SIZE}
title={t("fileManager.decreaseFontSize")}
className="w-7 h-7 p-0"
>
<ZoomOut className="w-4 h-4" />
</Button>
<span className="text-xs text-muted-foreground w-8 text-center select-none">
{editorFontSize}px
</span>
<Button
variant="ghost"
size="sm"
onClick={increaseFontSize}
disabled={editorFontSize >= MAX_FONT_SIZE}
title={t("fileManager.increaseFontSize")}
className="w-7 h-7 p-0"
>
<ZoomIn className="w-4 h-4" />
</Button>
</div>
)}
{isEditable && (
<Button
variant="ghost"
@@ -684,6 +734,7 @@ export function FileViewer({
onFocus={() => setEditorFocused(true)}
onBlur={() => setEditorFocused(false)}
placeholder={t("fileManager.startTyping")}
fontSize={editorFontSize}
/>
</Suspense>
) : (
@@ -56,7 +56,8 @@ function isDisplayableText(str: string): boolean {
(code >= 32 && code <= 126) ||
code === 9 ||
code === 10 ||
code === 13
code === 13 ||
code >= 128
) {
printable++;
}
@@ -82,6 +83,7 @@ export function FileWindow({
const [isLoading, setIsLoading] = useState(false);
const [isEditable, setIsEditable] = useState(false);
const [pendingContent, setPendingContent] = useState<string>("");
const [resetKey, setResetKey] = useState(0);
const [mediaDimensions, setMediaDimensions] = useState<
{ width: number; height: number } | undefined
>();
@@ -141,6 +143,7 @@ export function FileWindow({
setContent(fileContent);
setPendingContent(fileContent);
setResetKey((k) => k + 1);
if (!file.size) {
const contentSize = new Blob([fileContent]).size;
@@ -268,6 +271,7 @@ export function FileWindow({
const fileContent = response.content || "";
setContent(fileContent);
setPendingContent("");
setResetKey((k) => k + 1);
if (!file.size) {
const contentSize = new Blob([fileContent]).size;
@@ -444,6 +448,7 @@ export function FileWindow({
content={pendingContent || content}
savedContent={content}
isLoading={isLoading}
resetKey={resetKey}
onRevert={handleRevert}
isEditable={isEditable}
onContentChange={handleContentChange}
@@ -3,6 +3,8 @@ import type { LogEntry } from "@/types/connection-log.ts";
export interface FileManagerProps {
initialHost?: SSHHost | null;
initialFilePath?: string;
initialPath?: string;
onClose?: () => void;
}
+11 -1
View File
@@ -7,6 +7,7 @@ import {
getGuacamoleTokenFromHost,
getGuacdStatus,
getSSHHosts,
logActivity,
} from "@/main-axios.ts";
import { useTranslation } from "react-i18next";
import { AlertCircle, RefreshCw } from "lucide-react";
@@ -76,6 +77,7 @@ const GuacamoleApp: React.FC<GuacamoleAppProps> = ({
<GuacamoleAppInner
hostId={parseInt(hostId, 10)}
hostConfig={hostConfig}
hostName={hostConfig.name || hostConfig.ip || String(hostId)}
tabId={tabId}
protocol={protocol}
/>
@@ -85,6 +87,7 @@ const GuacamoleApp: React.FC<GuacamoleAppProps> = ({
interface GuacamoleAppInnerProps {
hostId: number;
hostConfig: Pick<SSHHost, "connectionType">;
hostName: string;
tabId?: string;
protocol?: "rdp" | "vnc" | "telnet";
}
@@ -92,6 +95,7 @@ interface GuacamoleAppInnerProps {
const GuacamoleAppInner: React.FC<GuacamoleAppInnerProps> = ({
hostId,
hostConfig,
hostName,
tabId,
protocol,
}) => {
@@ -114,7 +118,13 @@ const GuacamoleAppInner: React.FC<GuacamoleAppInnerProps> = ({
return getGuacamoleTokenFromHost(hostId, protocol);
})
.then((result) => {
if (result) setToken(result.token);
if (result) {
setToken(result.token);
const resolvedProtocol = (protocol ??
hostConfig.connectionType ??
"rdp") as "rdp" | "vnc" | "telnet";
logActivity(resolvedProtocol, hostId, hostName).catch(() => {});
}
})
.catch((err) => setError(err?.message || t("guacamole.failedToConnect")));
}, [hostId, protocol, retryCount, t]);
@@ -541,6 +541,7 @@ export const GuacamoleDisplay = forwardRef<
const h = Math.round(rect.height);
if (w > 0 && h > 0) {
clientRef.current.sendSize(w, h);
rescaleDisplay(true);
}
}
}, 150);
@@ -0,0 +1,499 @@
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import {
ChevronUp,
ChevronDown,
ChevronLeft,
ChevronRight,
Pencil,
X,
Plus,
RotateCcw,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/button";
import { Input } from "@/components/input";
import {
Sheet,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetTitle,
} from "@/components/sheet";
import type { TerminalHandle } from "./terminal-types";
interface MobileTerminalKeyboardProps {
terminalRef: React.RefObject<TerminalHandle | null>;
}
const CTRL_MAP: Record<string, string> = {
a: "\x01",
c: "\x03",
d: "\x04",
k: "\x0B",
l: "\x0C",
r: "\x12",
u: "\x15",
w: "\x17",
z: "\x1A",
};
const DEFAULT_QUICK_KEYS = [
"/",
"|",
"~",
"-",
"_",
"#",
"\\",
'"',
"'",
";",
":",
"!",
"&",
];
const LS_KEY = "termix:mobileQuickKeys";
function loadQuickKeys(): string[] {
try {
const raw = localStorage.getItem(LS_KEY);
if (raw) {
const parsed = JSON.parse(raw);
if (Array.isArray(parsed) && parsed.every((v) => typeof v === "string"))
return parsed;
}
} catch {
/* ignore */
}
return DEFAULT_QUICK_KEYS;
}
function saveQuickKeys(keys: string[]) {
try {
localStorage.setItem(LS_KEY, JSON.stringify(keys));
} catch {
/* ignore */
}
}
// Shared button styles
const KEY_BASE =
"flex items-center justify-center rounded border transition-colors select-none touch-none active:scale-95 shrink-0";
const KEY_NORMAL = "border-border bg-muted/50 text-foreground hover:bg-muted";
const KEY_ACTIVE =
"border-accent-brand bg-accent-brand/20 text-accent-brand shadow-[0_0_0_1px_color-mix(in_oklab,var(--accent-brand)_30%,transparent)]";
const KEY_MD = "h-9 px-3 min-w-[2.75rem] text-xs font-medium";
const KEY_SM = "h-9 w-9";
const SEP = "w-px h-5 bg-border mx-0.5 shrink-0";
// --- QuickKeysSheet ---
interface QuickKeysSheetProps {
open: boolean;
onOpenChange: (open: boolean) => void;
quickKeys: string[];
onUpdateKeys: (keys: string[]) => void;
}
function QuickKeysSheet({
open,
onOpenChange,
quickKeys,
onUpdateKeys,
}: QuickKeysSheetProps) {
const { t } = useTranslation();
const [newSymbol, setNewSymbol] = useState("");
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (!open) setNewSymbol("");
}, [open]);
function addKey() {
const sym = newSymbol.trim();
if (!sym || quickKeys.includes(sym) || sym.length > 8) {
setNewSymbol("");
return;
}
onUpdateKeys([...quickKeys, sym]);
setNewSymbol("");
inputRef.current?.focus();
}
function removeKey(index: number) {
onUpdateKeys(quickKeys.filter((_, i) => i !== index));
}
function resetDefaults() {
onUpdateKeys(DEFAULT_QUICK_KEYS);
}
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent
side="bottom"
className="max-h-[70vh] flex flex-col border-border"
>
<SheetHeader className="flex-row items-start justify-between pr-8">
<div>
<SheetTitle>{t("mobileKeyboard.quickKeysTitle")}</SheetTitle>
<SheetDescription>
{t("mobileKeyboard.quickKeysDesc")}
</SheetDescription>
</div>
<Button
variant="ghost"
size="sm"
className="text-xs"
onClick={resetDefaults}
>
<RotateCcw className="size-3 mr-1" />
{t("mobileKeyboard.resetDefaults")}
</Button>
</SheetHeader>
<div className="flex-1 overflow-y-auto px-4 py-2">
<div className="flex flex-wrap gap-2">
{quickKeys.map((sym, i) => (
<div
key={i}
className="flex items-center gap-1 h-8 pl-3 pr-1 rounded border border-border bg-muted/50 text-xs font-medium text-foreground"
>
<span className="font-mono">{sym}</span>
<button
className="size-5 flex items-center justify-center rounded hover:bg-destructive hover:text-destructive-foreground transition-colors"
onClick={() => removeKey(i)}
title={t("mobileKeyboard.removeQuickKey")}
>
<X className="size-3" />
</button>
</div>
))}
</div>
</div>
<div className="flex gap-2 px-4 py-2 border-t border-border">
<Input
ref={inputRef}
value={newSymbol}
onChange={(e) => setNewSymbol(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") addKey();
}}
maxLength={8}
placeholder={t("mobileKeyboard.quickKeyPlaceholder")}
className="h-9 text-xs font-mono"
/>
<Button
variant="outline"
size="sm"
className="h-9 shrink-0"
onClick={addKey}
disabled={!newSymbol.trim() || quickKeys.includes(newSymbol.trim())}
>
<Plus className="size-3.5 mr-1" />
{t("mobileKeyboard.addQuickKey")}
</Button>
</div>
<SheetFooter className="pt-0">
<Button className="w-full" onClick={() => onOpenChange(false)}>
{t("mobileKeyboard.done")}
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
);
}
// --- CtrlPanel ---
interface CtrlPanelProps {
onSend: (letter: string) => void;
}
function CtrlPanel({ onSend }: CtrlPanelProps) {
const CTRL_KEYS = ["c", "d", "l", "u", "z", "a", "r", "w", "k"];
return (
<div className="flex items-center gap-1 px-2 py-1 bg-muted/30 border-t border-border overflow-x-auto">
{CTRL_KEYS.map((k) => (
<button
key={k}
className={cn(KEY_BASE, KEY_NORMAL, KEY_MD, "font-mono")}
onPointerDown={(e) => {
e.preventDefault();
onSend(k);
}}
title={`Ctrl+${k.toUpperCase()}`}
>
^{k.toUpperCase()}
</button>
))}
</div>
);
}
// --- MobileTerminalKeyboard ---
export function MobileTerminalKeyboard({
terminalRef,
}: MobileTerminalKeyboardProps) {
const { t } = useTranslation();
const [ctrlActive, setCtrlActive] = useState(false);
const [shiftActive, setShiftActive] = useState(false);
const [quickKeys, setQuickKeys] = useState<string[]>(loadQuickKeys);
const [sheetOpen, setSheetOpen] = useState(false);
function send(seq: string) {
terminalRef.current?.sendInput?.(seq);
}
function toggleCtrl() {
setCtrlActive((v) => !v);
setShiftActive(false);
}
function toggleShift() {
setShiftActive((v) => !v);
setCtrlActive(false);
}
function sendArrow(normalSeq: string, appSeq: string, shiftSeq: string) {
if (shiftActive) {
send(shiftSeq);
setShiftActive(false);
return;
}
const appMode =
terminalRef.current?.getApplicationCursorKeysMode?.() ?? false;
send(appMode ? appSeq : normalSeq);
}
function handleTab() {
send(shiftActive ? "\x1b[Z" : "\t");
setShiftActive(false);
}
function handleCtrlKey(letter: string) {
const seq = CTRL_MAP[letter];
if (seq) send(seq);
setCtrlActive(false);
}
function updateQuickKeys(next: string[]) {
setQuickKeys(next);
saveQuickKeys(next);
}
return (
<div className="md:hidden flex flex-col bg-sidebar border-t border-border shrink-0">
{/* Row 1 — special keys */}
<div className="flex items-center gap-1 px-2 py-1.5 overflow-x-auto">
{/* ESC */}
<button
className={cn(KEY_BASE, KEY_NORMAL, KEY_MD)}
onPointerDown={(e) => {
e.preventDefault();
send("\x1b");
}}
title={t("mobileKeyboard.esc")}
>
{t("mobileKeyboard.esc")}
</button>
{/* Tab / back-tab */}
<button
className={cn(
KEY_BASE,
KEY_NORMAL,
KEY_MD,
shiftActive && "ring-1 ring-accent-brand/50",
)}
onPointerDown={(e) => {
e.preventDefault();
handleTab();
}}
title={shiftActive ? "Shift+Tab" : t("mobileKeyboard.tab")}
>
{shiftActive ? t("mobileKeyboard.backTab") : t("mobileKeyboard.tab")}
</button>
<div className={SEP} />
{/* Ctrl */}
<button
className={cn(KEY_BASE, KEY_MD, ctrlActive ? KEY_ACTIVE : KEY_NORMAL)}
onPointerDown={(e) => {
e.preventDefault();
toggleCtrl();
}}
title={t("mobileKeyboard.ctrl")}
>
{t("mobileKeyboard.ctrl")}
</button>
{/* Shift */}
<button
className={cn(
KEY_BASE,
KEY_MD,
shiftActive ? KEY_ACTIVE : KEY_NORMAL,
)}
onPointerDown={(e) => {
e.preventDefault();
toggleShift();
}}
title={t("mobileKeyboard.shift")}
>
{t("mobileKeyboard.shift")}
</button>
<div className={SEP} />
{/* Arrow keys */}
<button
className={cn(KEY_BASE, KEY_NORMAL, KEY_SM)}
onPointerDown={(e) => {
e.preventDefault();
sendArrow("\x1b[A", "\x1bOA", "\x1b[1;2A");
}}
title={t("mobileKeyboard.arrowUp")}
>
<ChevronUp className="size-4" />
</button>
<button
className={cn(KEY_BASE, KEY_NORMAL, KEY_SM)}
onPointerDown={(e) => {
e.preventDefault();
sendArrow("\x1b[B", "\x1bOB", "\x1b[1;2B");
}}
title={t("mobileKeyboard.arrowDown")}
>
<ChevronDown className="size-4" />
</button>
<button
className={cn(KEY_BASE, KEY_NORMAL, KEY_SM)}
onPointerDown={(e) => {
e.preventDefault();
sendArrow("\x1b[D", "\x1bOD", "\x1b[1;2D");
}}
title={t("mobileKeyboard.arrowLeft")}
>
<ChevronLeft className="size-4" />
</button>
<button
className={cn(KEY_BASE, KEY_NORMAL, KEY_SM)}
onPointerDown={(e) => {
e.preventDefault();
sendArrow("\x1b[C", "\x1bOC", "\x1b[1;2C");
}}
title={t("mobileKeyboard.arrowRight")}
>
<ChevronRight className="size-4" />
</button>
<div className={SEP} />
{/* Home / End */}
<button
className={cn(KEY_BASE, KEY_NORMAL, KEY_MD)}
onPointerDown={(e) => {
e.preventDefault();
send("\x1b[H");
}}
title={t("mobileKeyboard.home")}
>
{t("mobileKeyboard.home")}
</button>
<button
className={cn(KEY_BASE, KEY_NORMAL, KEY_MD)}
onPointerDown={(e) => {
e.preventDefault();
send("\x1b[F");
}}
title={t("mobileKeyboard.end")}
>
{t("mobileKeyboard.end")}
</button>
<div className={SEP} />
{/* PgUp / PgDn / Del */}
<button
className={cn(KEY_BASE, KEY_NORMAL, KEY_MD)}
onPointerDown={(e) => {
e.preventDefault();
send("\x1b[5~");
}}
title={t("mobileKeyboard.pageUp")}
>
{t("mobileKeyboard.pageUp")}
</button>
<button
className={cn(KEY_BASE, KEY_NORMAL, KEY_MD)}
onPointerDown={(e) => {
e.preventDefault();
send("\x1b[6~");
}}
title={t("mobileKeyboard.pageDown")}
>
{t("mobileKeyboard.pageDown")}
</button>
<button
className={cn(KEY_BASE, KEY_NORMAL, KEY_MD)}
onPointerDown={(e) => {
e.preventDefault();
send("\x1b[3~");
}}
title={t("mobileKeyboard.delete")}
>
{t("mobileKeyboard.delete")}
</button>
</div>
{/* Ctrl combos panel */}
{ctrlActive && <CtrlPanel onSend={handleCtrlKey} />}
{/* Row 2 — quick keys */}
<div className="flex items-center gap-1 px-2 pb-1.5 overflow-x-auto">
{quickKeys.map((sym, i) => (
<button
key={i}
className={cn(KEY_BASE, KEY_NORMAL, KEY_MD, "font-mono")}
onPointerDown={(e) => {
e.preventDefault();
send(sym);
}}
title={sym}
>
{sym}
</button>
))}
<div className="ml-auto shrink-0">
<button
className={cn(KEY_BASE, KEY_NORMAL, KEY_SM)}
onPointerDown={(e) => {
e.preventDefault();
setSheetOpen(true);
}}
title={t("mobileKeyboard.editQuickKeys")}
>
<Pencil className="size-3.5" />
</button>
</div>
</div>
<QuickKeysSheet
open={sheetOpen}
onOpenChange={setSheetOpen}
quickKeys={quickKeys}
onUpdateKeys={updateQuickKeys}
/>
</div>
);
}
+222 -9
View File
@@ -40,6 +40,7 @@ import {
} from "@/lib/terminal-themes.ts";
import "./terminal-global-styles.ts";
import { useTheme } from "@/components/theme-provider.tsx";
import { globalShortcutHandler } from "@/lib/global-shortcut-handler";
import { useCommandTracker } from "@/features/terminal/command-history/useCommandTracker.ts";
import { highlightTerminalOutput } from "@/lib/terminal-syntax-highlighter.ts";
import { useCommandHistory } from "@/features/terminal/command-history/CommandHistoryContext.tsx";
@@ -75,6 +76,7 @@ interface SSHTerminalProps {
/** Attach to this tmux session right after connecting (tmux monitor). */
tmuxAttachSession?: string;
onOpenFileManager?: (path?: string) => void;
onOpenFileInEditor?: (filePath: string) => void;
previewTheme?: string | null;
}
@@ -85,10 +87,12 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
isVisible,
splitScreen = false,
onClose,
onTitleChange,
initialPath,
executeCommand,
tmuxAttachSession,
onOpenFileManager,
onOpenFileInEditor,
previewTheme,
},
ref,
@@ -114,7 +118,11 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
const activeTheme = previewTheme || config.theme;
const themeColors = resolveTermixThemeColors(activeTheme, appTheme);
const backgroundColor = themeColors.background;
const backgroundImage = config.backgroundImage || "";
const backgroundImageOpacity = config.backgroundImageOpacity ?? 0.15;
const backgroundColor = backgroundImage
? "transparent"
: themeColors.background;
const fitAddonRef = useRef<FitAddon | null>(null);
const webSocketRef = useRef<WebSocket | null>(null);
const resizeTimeout = useRef<NodeJS.Timeout | null>(null);
@@ -176,6 +184,10 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
const pendingRestoredSessionIdRef = useRef<string | null>(
hostConfig.restoredSessionId ?? null,
);
const [linkClickDialog, setLinkClickDialog] = useState<{
url: string;
} | null>(null);
const [tmuxSessionPicker, setTmuxSessionPicker] = useState<{
sessions: Array<{
name: string;
@@ -655,6 +667,7 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
isFittingRef.current = false;
}
},
focus: () => terminal?.focus(),
sendInput: (data: string) => {
if (webSocketRef.current?.readyState === 1) {
webSocketRef.current.send(JSON.stringify({ type: "input", data }));
@@ -673,6 +686,8 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
}
},
refresh: () => hardRefresh(),
getApplicationCursorKeysMode: () =>
terminal?.modes?.applicationCursorKeysMode ?? false,
openFileManager: () => {
if (webSocketRef.current?.readyState === WebSocket.OPEN) {
webSocketRef.current.send(JSON.stringify({ type: "get_cwd" }));
@@ -941,6 +956,24 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
);
}
terminal.onData((data) => {
if (data === "\r" || data === "\n") {
const currentCmd = getCurrentCommand().trim();
const termixMatch = currentCmd.match(/^termix\s+(.+)$/);
if (termixMatch && onOpenFileInEditor) {
const filePath = termixMatch[1].trim();
trackInput(data);
terminal.write("\r\n");
if (ws.readyState === WebSocket.OPEN) {
ws.send(
JSON.stringify({
type: "open_file_in_editor",
path: filePath,
}),
);
}
return;
}
}
trackInput(data);
ws.send(JSON.stringify({ type: "input", data }));
});
@@ -970,6 +1003,13 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
}
if (msg.type === "data") {
if (typeof msg.data === "string") {
if (showAutocompleteRef.current) {
showAutocompleteRef.current = false;
setShowAutocomplete(false);
setAutocompleteSuggestions([]);
currentAutocompleteCommand.current = "";
}
const syntaxHighlightingEnabled =
hostConfig.terminalConfig?.syntaxHighlighting !== false;
@@ -982,7 +1022,13 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
terminal.write(outputData);
const sudoPasswordPattern =
/(?:\[sudo\][^\n]*:\s*$|sudo:[^\n]*password[^\n]*required|password for [^\n]*:\s*$|Password:\s*$)/i;
/(?:\[sudo\][^\n\r]*:\s*$|sudo:[^\n\r]*password[^\n\r]*required|password for [^\n\r]*:\s*$|Password:\s*$)/im;
// Strip ANSI escape codes before testing — newer sudo versions (Ubuntu 26.04+)
// emit colored prompts with embedded escape sequences that break the regex.
const strippedData = msg.data.replace(
/\x1b(?:[@-Z\\-_]|\[[0-9;?>=!]*[@-~])/g,
"",
);
const hasSudoPw =
hostConfig.terminalConfig?.sudoPassword ||
hostConfig.password ||
@@ -990,7 +1036,7 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
hostConfig.hasPassword;
if (
config.sudoPasswordAutoFill &&
sudoPasswordPattern.test(msg.data) &&
sudoPasswordPattern.test(strippedData) &&
hasSudoPw &&
!sudoPromptShownRef.current
) {
@@ -1386,6 +1432,8 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
}
} else if (msg.type === "cwd") {
onOpenFileManager?.(msg.path as string);
} else if (msg.type === "open_file_in_editor") {
onOpenFileInEditor?.(msg.path as string);
} else if (msg.type === "passphrase_required") {
setShowPassphraseDialog(true);
setIsConnecting(false);
@@ -1792,7 +1840,9 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
| "both";
terminal.options.theme = {
background: themeColors.background,
background: config.backgroundImage
? "transparent"
: themeColors.background,
foreground: themeColors.foreground,
cursor: themeColors.cursor,
cursorAccent: themeColors.cursorAccent,
@@ -1850,7 +1900,7 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
fontFamily,
allowTransparency: true, // MUST be set before open()
convertEol: false,
macOptionIsMeta: false,
macOptionIsMeta: true,
macOptionClickForcesSelection: false,
rightClickSelectsWord: config.rightClickSelectsWord,
fastScrollSensitivity: config.fastScrollSensitivity,
@@ -1860,7 +1910,9 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
lineHeight: config.lineHeight,
bellStyle: config.bellStyle as "none" | "sound" | "visual" | "both",
theme: {
background: themeColors.background,
background: config.backgroundImage
? "transparent"
: themeColors.background,
foreground: themeColors.foreground,
cursor: themeColors.cursor,
cursorAccent: themeColors.cursorAccent,
@@ -1894,7 +1946,17 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
uri.startsWith("http://") || uri.startsWith("https://")
? uri
: `https://${uri}`;
window.open(url, "_blank");
const hostBehavior = hostConfig.terminalConfig?.linkClickBehavior;
const globalBehavior =
localStorage.getItem("terminalLinkClickBehavior") ?? "confirm";
const behavior = hostBehavior ?? globalBehavior;
if (behavior === "direct") {
window.open(url, "_blank");
} else {
setLinkClickDialog({ url });
}
});
fitAddonRef.current = fitAddon;
@@ -1906,6 +1968,9 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
terminal.unicode.activeVersion = "11";
terminal.open(xtermRef.current);
terminal.onTitleChange((title) => {
if (title) onTitleChange?.(title);
});
document.fonts.ready.then(() => {
terminal.refresh(0, terminal.rows - 1);
fitAddon.fit();
@@ -2017,7 +2082,18 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
return false;
};
// On macOS Electron, Tab key events can be swallowed by Chromium's focus
// traversal system before xterm.js sees them. Calling preventDefault() in
// the capture phase blocks that traversal while still allowing the event to
// reach xterm.js's internal handler (which fires our attachCustomKeyEventHandler).
const handleTabCapture = (e: KeyboardEvent) => {
if (e.key === "Tab") {
e.preventDefault();
}
};
element?.addEventListener("keydown", handleBackspaceMode, true);
element?.addEventListener("keydown", handleTabCapture, true);
const resizeObserver = new ResizeObserver(() => {
if (resizeTimeout.current) clearTimeout(resizeTimeout.current);
@@ -2041,6 +2117,7 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
element?.removeEventListener("mousemove", handleTmuxDragMove);
element?.removeEventListener("mouseup", handleTmuxDragEnd);
element?.removeEventListener("keydown", handleBackspaceMode, true);
element?.removeEventListener("keydown", handleTabCapture, true);
if (notifyTimerRef.current) clearTimeout(notifyTimerRef.current);
if (resizeTimeout.current) clearTimeout(resizeTimeout.current);
};
@@ -2096,6 +2173,37 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
return true;
}
// Forward global app shortcuts to AppShell directly — xterm swallows
// all keydown events and synthetic re-dispatch is unreliable.
// stopPropagation prevents the same event from also firing the window listener.
if (e.ctrlKey && e.shiftKey && !e.altKey && !e.metaKey) {
const globalCodes = [
"BracketRight",
"BracketLeft",
"Backslash",
"Minus",
];
if (globalCodes.includes(e.code)) {
e.stopPropagation();
globalShortcutHandler.current?.(e);
return false;
}
}
if (e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
const arrowCodes = [
"ArrowLeft",
"ArrowRight",
"ArrowUp",
"ArrowDown",
];
if (arrowCodes.includes(e.code)) {
e.stopPropagation();
globalShortcutHandler.current?.(e);
return false;
}
}
if (
e.ctrlKey &&
!e.shiftKey &&
@@ -2132,6 +2240,38 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
}
}
if (
e.ctrlKey &&
e.shiftKey &&
!e.altKey &&
!e.metaKey &&
e.key.toLowerCase() === "c"
) {
const selection = terminal.getSelection();
if (selection) {
e.preventDefault();
e.stopPropagation();
writeTextToClipboard(selection);
terminal.clearSelection();
return false;
}
}
if (
e.ctrlKey &&
e.shiftKey &&
!e.altKey &&
!e.metaKey &&
e.key.toLowerCase() === "v"
) {
e.preventDefault();
e.stopPropagation();
readTextFromClipboard().then((text) => {
if (text) terminal.paste(text);
});
return false;
}
if (
e.ctrlKey &&
!e.shiftKey &&
@@ -2426,10 +2566,30 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
const hasConnectionError = !!connectionError;
return (
<div className="h-full w-full relative" style={{ backgroundColor }}>
<div
className="h-full w-full relative"
style={{
backgroundColor: backgroundImage ? "transparent" : backgroundColor,
...(backgroundImage && {
backgroundImage: `url(${backgroundImage})`,
backgroundSize: "cover",
backgroundPosition: "center",
backgroundRepeat: "no-repeat",
}),
}}
>
{backgroundImage && (
<div
className="absolute inset-0 pointer-events-none"
style={{
backgroundColor: themeColors.background,
opacity: 1 - backgroundImageOpacity,
}}
/>
)}
<div
ref={xtermRef}
className="h-full w-full"
className="h-full w-full relative"
style={{
pointerEvents: isVisible ? "auto" : "none",
visibility:
@@ -2656,6 +2816,7 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
}),
);
}
setTimeout(() => terminal?.focus(), 50);
}}
onCreateNew={() => {
setTmuxSessionPicker(null);
@@ -2667,6 +2828,7 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
}),
);
}
setTimeout(() => terminal?.focus(), 50);
}}
onCancel={() => setTmuxSessionPicker(null)}
backgroundColor={backgroundColor}
@@ -2680,6 +2842,57 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
position={autocompletePosition}
onSelect={handleAutocompleteSelect}
/>
{linkClickDialog && (
<div
className="absolute inset-0 flex items-center justify-center z-[150]"
style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
>
<div
className="flex flex-col gap-3 p-4 rounded shadow-lg max-w-sm w-full mx-4"
style={{ backgroundColor }}
>
<p className="text-xs font-bold uppercase tracking-widest text-muted-foreground">
{t("terminal.linkDialogTitle")}
</p>
<p className="text-sm break-all text-foreground select-all">
{linkClickDialog.url}
</p>
<div className="flex gap-2 justify-end">
<Button
variant="outline"
size="sm"
onClick={() => {
writeTextToClipboard(linkClickDialog.url);
setLinkClickDialog(null);
}}
>
{t("terminal.linkDialogCopy")}
</Button>
<Button
size="sm"
onClick={() => {
window.open(
linkClickDialog.url,
"_blank",
"noopener,noreferrer",
);
setLinkClickDialog(null);
}}
>
{t("terminal.linkDialogOpen")}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setLinkClickDialog(null)}
>
{t("common.cancel")}
</Button>
</div>
</div>
</div>
)}
</div>
);
},
@@ -1,9 +1,5 @@
const style = document.createElement("style");
style.innerHTML = `
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:ital,wght@0,400;0,700;1,400;1,700&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;700&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Source+Code+Pro:ital,wght@0,400;0,700;1,400;1,700&display=swap');
@font-face {
font-family: 'Caskaydia Cove Nerd Font Mono';
src: url('./fonts/CaskaydiaCoveNerdFontMono-Regular.ttf') format('truetype');
@@ -21,7 +21,9 @@ export interface TerminalHandle {
disconnect: () => void;
reconnect: () => void;
fit: () => void;
focus: () => void;
sendInput: (data: string) => void;
notifyResize: () => void;
refresh: () => void;
getApplicationCursorKeysMode: () => boolean;
}
+51
View File
@@ -0,0 +1,51 @@
import { useState, useEffect } from "react";
export type StatusColorScheme = "accent" | "status";
export function useStatusColorScheme(): StatusColorScheme {
const [scheme, setScheme] = useState<StatusColorScheme>(
() =>
(localStorage.getItem("statusColorScheme") as StatusColorScheme) ??
"accent",
);
useEffect(() => {
const handler = () => {
setScheme(
(localStorage.getItem("statusColorScheme") as StatusColorScheme) ??
"accent",
);
};
window.addEventListener("statusColorSchemeChanged", handler);
return () =>
window.removeEventListener("statusColorSchemeChanged", handler);
}, []);
return scheme;
}
/** Returns Tailwind class names for a status dot/stripe. */
export function getStatusClasses(
online: boolean,
scheme: StatusColorScheme,
variant: "dot" | "stripe" | "badge",
): string {
if (scheme === "status") {
if (variant === "dot") return online ? "bg-emerald-500" : "bg-red-500";
if (variant === "stripe")
return online ? "bg-emerald-500" : "bg-red-500/40";
// badge
return online
? "border-emerald-500/40 text-emerald-500 bg-emerald-500/10"
: "border-red-500/40 text-red-500 bg-red-500/10";
}
// accent scheme
if (variant === "dot")
return online ? "bg-accent-brand" : "bg-muted-foreground/25";
if (variant === "stripe")
return online ? "bg-accent-brand" : "bg-transparent";
// badge
return online
? "border-accent-brand/40 text-accent-brand bg-accent-brand/10"
: "border-border/50 text-muted-foreground/60 bg-muted/30";
}
+21 -11
View File
@@ -1,6 +1,16 @@
@import "tailwindcss";
@import "tw-animate-css";
@import "@fontsource-variable/jetbrains-mono";
@import "@fontsource/jetbrains-mono/400.css";
@import "@fontsource/jetbrains-mono/400-italic.css";
@import "@fontsource/jetbrains-mono/700.css";
@import "@fontsource/jetbrains-mono/700-italic.css";
@import "@fontsource/fira-code/400.css";
@import "@fontsource/fira-code/700.css";
@import "@fontsource/source-code-pro/400.css";
@import "@fontsource/source-code-pro/400-italic.css";
@import "@fontsource/source-code-pro/700.css";
@import "@fontsource/source-code-pro/700-italic.css";
@font-face {
font-family: "Caskaydia Cove Nerd Font Mono";
@@ -242,38 +252,38 @@
.nord {
--background: #2e3440;
--foreground: #eceff4;
--card: #272c36;
--card: #303642;
--card-foreground: #eceff4;
--popover: #272c36;
--popover: #303642;
--popover-foreground: #eceff4;
--primary: #eceff4;
--primary-foreground: #2e3440;
--secondary: #3b4252;
--secondary-foreground: #eceff4;
--surface: #272c36;
--surface-dim: #22262e;
--surface: #303642;
--surface-dim: #262b35;
--muted: #3b4252;
--muted-foreground: #4c566a;
--muted-foreground: #8899b0;
--accent: #3b4252;
--accent-foreground: #eceff4;
--destructive: #bf616a;
--border: rgba(76, 86, 106, 0.35);
--input: rgba(76, 86, 106, 0.3);
--ring: #4c566a;
--border: rgba(136, 192, 208, 0.2);
--input: rgba(136, 192, 208, 0.15);
--ring: #88c0d0;
--chart-1: #bf616a;
--chart-2: #88c0d0;
--chart-3: #a3be8c;
--chart-4: #ebcb8b;
--chart-5: #b48ead;
--radius: 0.625rem;
--sidebar: #272c36;
--sidebar: #282d39;
--sidebar-foreground: #eceff4;
--sidebar-primary: #88c0d0;
--sidebar-primary-foreground: #2e3440;
--sidebar-accent: #3b4252;
--sidebar-accent-foreground: #eceff4;
--sidebar-border: rgba(76, 86, 106, 0.35);
--sidebar-ring: #4c566a;
--sidebar-border: rgba(136, 192, 208, 0.2);
--sidebar-ring: #88c0d0;
}
/* ── Solarized Dark ─────────────────────────────────────────── */
+11 -3
View File
@@ -18,9 +18,13 @@ export class RobustClipboardProvider implements IClipboardProvider {
});
return;
}
navigator.clipboard.writeText(text).catch(() => {
if (navigator.clipboard?.writeText) {
navigator.clipboard.writeText(text).catch(() => {
this.pendingWrite = text;
});
} else {
this.pendingWrite = text;
});
}
}
};
window.addEventListener("focus", this.focusHandler);
@@ -47,7 +51,11 @@ export class RobustClipboardProvider implements IClipboardProvider {
await window.electronClipboard.writeText(text);
return;
}
await navigator.clipboard.writeText(text);
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text);
} else {
this.pendingWrite = text;
}
} catch {
this.pendingWrite = text;
}
+5
View File
@@ -0,0 +1,5 @@
// Module-level ref so xterm's key handler can invoke app-level shortcuts
// without going through synthetic DOM events.
export const globalShortcutHandler = {
current: null as ((e: KeyboardEvent) => void) | null,
};
+88 -1
View File
@@ -154,7 +154,7 @@ describe("highlightTerminalOutput", () => {
});
it("processes multi-line text line by line", () => {
const text = "some output\nERROR: failed";
const text = "some output\nERROR: failed\n";
const out = highlightTerminalOutput(text);
expect(out).toContain(ESC + "[91m");
});
@@ -198,4 +198,91 @@ describe("highlightTerminalOutput", () => {
});
expect(out).not.toContain(ESC + "[96m");
});
it("skips highlighting when chunk contains a mid-line carriage return", () => {
// Progress bars and shell prompt redraws use \r to overwrite the current line
const chunk = "downloading...\rdownloading [====] 100%";
expect(highlightTerminalOutput(chunk)).toBe(chunk);
});
it("still processes CRLF line endings (\\r\\n is fine)", () => {
const out = highlightTerminalOutput("ERROR occurred\r\n");
expect(out).toContain(ESC + "[91m");
});
it("does not highlight shell prompt lines (user@host:path$)", () => {
const prompt = `${ESC}[01;32mpi@raspberrypi${ESC}[00m:${ESC}[01;34m/home/pi${ESC}[00m$ `;
const out = highlightTerminalOutput(prompt);
expect(out).toBe(prompt);
});
it("does not highlight plain-text shell prompt line", () => {
const prompt = "pi@raspberrypi:/home/pi$ ";
const out = highlightTerminalOutput(prompt);
expect(out).toBe(prompt);
});
it("does not highlight 'success' when immediately followed by a path (cd output)", () => {
// Some shells print "success~/new/dir" or "success/path" after a cd command
const out = highlightTerminalOutput("success~/home/user/projects");
expect(out).not.toContain(ESC + "[92m");
});
it("still highlights 'success' when not followed by a path separator", () => {
const out = highlightTerminalOutput("Build success: all tests passed");
expect(out).toContain(ESC + "[92m");
});
it("highlights output lines but not the prompt in a mixed chunk", () => {
const chunk = `ERROR: disk full\npi@raspberrypi:~$ `;
const out = highlightTerminalOutput(chunk);
// The error line should be highlighted
expect(out).toContain(ESC + "[91m");
// The prompt line should be unchanged
expect(out).toContain("pi@raspberrypi:~$ ");
const promptLine = out.split("\n")[1];
expect(promptLine).toBe("pi@raspberrypi:~$ ");
});
it("does not highlight paths inside a command-echo line (prompt + command)", () => {
// When the shell echoes the user's command, it prefixes the prompt.
// The path in the prompt portion (/home/user) must not be highlighted —
// the shell already colored it, and re-coloring it causes the doubled-path bug.
const echo = "user@host:/home/user$ cd /opt/app/bin/files";
const out = highlightTerminalOutput(echo);
expect(out).toBe(echo);
});
it("does not highlight paths in colored command-echo lines (root prompt)", () => {
const echo = `${ESC}[01;32mroot@host${ESC}[00m:${ESC}[01;34m/home/user${ESC}[00m# cd /opt/app/bin/files`;
const out = highlightTerminalOutput(echo);
expect(out).toBe(echo);
});
it("does not highlight the last line of a multi-line chunk with no trailing newline", () => {
// In a multi-line chunk, the trailing fragment without \n could be a live
// readline input line. Injecting ANSI bytes there breaks bash's cursor
// arithmetic (causes cursor jump / text shift when using arrow keys).
const chunk = "ERROR: disk full\nuser@host:/path$ cd /var/log";
const out = highlightTerminalOutput(chunk);
// First line (terminated by \n) gets highlighted
expect(out.split("\n")[0]).toContain(ESC + "[91m");
// Last unterminated fragment is left verbatim
expect(out.split("\n")[1]).toBe("user@host:/path$ cd /var/log");
});
it("still highlights a single-line chunk with no trailing newline", () => {
// A single-line chunk with no \n is plain command output, not a readline
// input fragment — highlight it normally.
const out = highlightTerminalOutput("ERROR: something failed");
expect(out).toContain(ESC + "[91m");
});
it("highlights all lines when the chunk ends with a newline", () => {
// When a chunk ends with \n every line is complete output — highlight them all.
const chunk = "ERROR: disk full\nconnect to /var/run/app.sock\n";
const out = highlightTerminalOutput(chunk);
expect(out.split("\n")[0]).toContain(ESC + "[91m");
expect(out.split("\n")[1]).toContain(ESC + "[36m");
});
});
+48 -5
View File
@@ -56,6 +56,28 @@ const MAX_LINE_LENGTH = 2000;
// If a chunk contains these, we skip highlighting entirely.
const TUI_SEQUENCE = /\x1b\[[\d;]*[ABCDEFGHJKST]/;
// A bare \r (not immediately followed by \n) means the terminal is overwriting
// the current line (shell prompts, progress bars). Highlighting mid-rewrite
// chunks corrupts the cursor state, so we skip the whole chunk.
const MID_LINE_CR = /\r(?!\n)/;
// Detects shell prompt lines (user@host:/path$ or similar) after stripping ANSI.
// These should not be highlighted — the server already colored them, and injecting
// additional ANSI codes into the prompt fragments causes display corruption.
const STRIP_ANSI_RE = /\x1b(?:[@-Z\\-_]|\[[0-9;?>=!]*[@-~])/g;
function isShellPromptLine(bare: string): boolean {
const plain = bare.replace(STRIP_ANSI_RE, "");
// Matches a trailing prompt: "user@host:~$ ", "root@pi:/home/pi# ", "[user@host dir]$ "
if (/(?:[\w.-]+@[\w.-]+|[\w.-]+).*?[$#%>]\s*$/.test(plain)) return true;
// Matches a leading prompt followed by a command: "user@host:/path$ cmd arg"
// This is the echoed command line — the shell colors the prompt prefix itself,
// so injecting extra ANSI codes into it causes visual corruption / doubled paths.
if (/^(?:\[?[\w.-]+@[\w.-]+[\w./ ~-]*\]?|[\w.-]+).*?[$#%>]\s+\S/.test(plain))
return true;
return false;
}
// Matches any complete ANSI escape sequence
const ANSI_REGEX = /\x1b(?:[@-Z\\-_]|\[[0-9;?>=!]*[@-~])/g;
@@ -114,10 +136,13 @@ const ALL_PATTERNS: HighlightPattern[] = [
category: "logLevels",
},
// Success keywords — kept conservative to avoid noise
// Success keywords — kept conservative to avoid noise.
// Negative lookahead prevents matching when directly followed by a path separator
// (e.g. shell `cd` output that prints "success~/new/dir").
{
name: "log-success",
regex: /\b(?:success(?:ful(?:ly)?)?|pass(?:ed)?|complete(?:d)?|ok\b)\b/gi,
regex:
/\b(?:success(?:ful(?:ly)?)?|pass(?:ed)?|complete(?:d)?|ok\b)\b(?![\\/~])/gi,
ansiCode: ANSI.brightGreen,
priority: 8,
category: "logLevels",
@@ -313,6 +338,7 @@ function highlightLine(
const bare = cr ? line.slice(0, -1) : line;
if (!bare.trim()) return line;
if (isShellPromptLine(bare)) return line;
const segments = parseAnsiSegments(bare);
const result = segments
@@ -334,12 +360,29 @@ export function highlightTerminalOutput(
if (hasIncompleteAnsiSequence(text)) return text;
if (TUI_SEQUENCE.test(text)) return text;
if (MID_LINE_CR.test(text)) return text;
const activePatterns = buildActivePatterns(options);
if (activePatterns.length === 0) return text;
return text
.split("\n")
.map((line) => highlightLine(line, activePatterns))
const lines = text.split("\n");
const endsWithNewline = text.endsWith("\n");
const hasMultipleLines = lines.length > 1;
// When a multi-line chunk has a trailing fragment without \n, that fragment
// could be a live readline input line that bash will redraw with \r +
// cursor-positioning sequences. Injecting ANSI bytes into it adds invisible
// chars that bash doesn't count, so bash's cursor arithmetic diverges from
// xterm's actual column position — causing the cursor to jump and text to
// shift when the user types or navigates with arrow keys.
// Only skip the last fragment when the chunk already has complete lines
// before it (single-line chunks with no \n are plain output, not input).
const highlightCount =
hasMultipleLines && !endsWithNewline ? lines.length - 1 : lines.length;
return lines
.map((line, i) =>
i < highlightCount ? highlightLine(line, activePatterns) : line,
)
.join("\n");
}
+2
View File
@@ -821,6 +821,8 @@ export const DEFAULT_TERMINAL_CONFIG = {
keepaliveInterval: undefined as number | undefined,
keepaliveCountMax: undefined as number | undefined,
autoTmux: false,
backgroundImage: "" as string,
backgroundImageOpacity: 0.15,
};
export type TerminalConfigType = typeof DEFAULT_TERMINAL_CONFIG;
+6
View File
@@ -41,6 +41,12 @@ export const DASHBOARD_CARDS: DashboardCardConfig[] = [
description: "Visual map of host network topology",
defaultEnabled: false,
},
{
id: "service_links",
label: "Service Links",
description: "Clickable buttons linking to services on your servers",
defaultEnabled: false,
},
];
export const ACCENT_PRESET_COLORS = [
+216 -12
View File
@@ -58,7 +58,10 @@
"embeddedDesc": "Run Termix with the built-in local server (no remote server needed)",
"embeddedConnecting": "Connecting to local server...",
"embeddedNotReady": "Local server is not ready yet. Please wait a moment and try again.",
"localServer": "Local Server"
"localServer": "Local Server",
"savedServers": "Saved Servers",
"noSavedServers": "No saved servers",
"removeServer": "Remove"
},
"versionCheck": {
"error": "Version Check Error",
@@ -105,6 +108,7 @@
"cancel": "Cancel",
"username": "Username",
"login": "Login",
"logout": "Logout",
"register": "Register",
"password": "Password",
"confirmPassword": "Confirm Password",
@@ -165,6 +169,7 @@
"noPasswordAvailable": "No password available",
"failedToCopyPassword": "Failed to copy password",
"refreshTab": "Refresh connection",
"renameTab": "Rename tab",
"openFileManager": "Open File Manager",
"dashboard": "Dashboard",
"networkGraph": "Network Graph",
@@ -190,6 +195,7 @@
"downloadSample": "Download Sample",
"failedToDeleteHost": "Failed to delete {{name}}",
"importSkipExisting": "Import (skip existing)",
"importSSHConfig": "Import from SSH config",
"connectionDetails": "Connection Details",
"ssh": "SSH",
"telnet": "Telnet",
@@ -264,6 +270,7 @@
"forceKeyboardInteractive": "Force Keyboard-Interactive",
"overrideCredentialUsername": "Override Credential Username",
"overrideCredentialUsernameDesc": "Use the username specified above instead of the credential's username",
"oidcUsernameHint": "Use $oidc.preferred_username to substitute your OIDC login name.",
"jumpHostChain": "Jump Host Chain",
"portKnocking": "Port Knocking",
"addKnock": "Add Port",
@@ -297,6 +304,8 @@
"addressIp": "Address / IP",
"friendlyName": "Friendly Name",
"macAddress": "MAC Address",
"wolBroadcastAddress": "WoL Broadcast Address",
"wolBroadcastAddressDesc": "Optional directed broadcast for Docker/routed networks (e.g. 192.168.1.255). Leave empty to use 255.255.255.255.",
"folderAndAdvanced": "Folder & Advanced",
"privateNotes": "Private Notes",
"privateNotesPlaceholder": "Details about this server...",
@@ -339,6 +348,8 @@
"docsLink": "View docs",
"opksshLabel": "OPKSSH",
"opksshDesc": "Sign in to this host using your identity provider instead of a password or key. Requires OPKSSH set up on the server.",
"warpgateLabel": "Warpgate Gateway",
"warpgateDesc": "This host connects through a Warpgate SSH proxy. Termix will handle the browser-based approval flow automatically after authenticating.",
"tailscaleDeviceSelect": "Select Tailscale device",
"tailscaleDeviceSelectPlaceholder": "Select a device...",
"tailscaleNoApiKey": "No Tailscale API key configured. Add one in Admin Settings to enable device discovery.",
@@ -348,6 +359,9 @@
"tailscaleDeviceAutoFill": "Selecting a device will auto-fill the host IP address.",
"forceKeyboardInteractiveLabel": "Force Keyboard Interactive",
"forceKeyboardInteractiveShortDesc": "Force manual password entry even if keys are present",
"allowLegacyAlgorithmsLabel": "Allow Legacy Algorithms",
"allowLegacyAlgorithmsDesc": "Enable deprecated SSH algorithms (ssh-dss, ssh-rsa, diffie-hellman-group1-sha1, hmac-md5, 3des-cbc) for connections to old devices that cannot be upgraded.",
"insecure": "Insecure",
"terminalAppearance": "Terminal Appearance",
"colorTheme": "Color Theme",
"fontFamilyLabel": "Font Family",
@@ -361,6 +375,9 @@
"cursorBlinkingDesc": "Enable blinking animation for the terminal cursor",
"rightClickSelectsWordLabel": "Right-click Selects Word",
"rightClickSelectsWordShortDesc": "Select the word under cursor on right-click",
"backgroundImageLabel": "Background Image URL",
"backgroundImageDesc": "Optional URL for a terminal background image",
"backgroundImageOpacityLabel": "Background Image Opacity",
"syntaxHighlightingLabel": "Syntax Highlighting",
"syntaxHighlightingDesc": "Colorize terminal output (errors, paths, IPs, timestamps)",
"syntaxHighlightingCategories": "Highlight Categories",
@@ -382,6 +399,8 @@
"scrollbackMaxLines": "Maximum number of lines kept in history",
"sshAgentForwardingLabel": "SSH Agent Forwarding",
"sshAgentForwardingShortDesc": "Pass your local SSH keys to this host",
"useSSHTitleLabel": "Use SSH Window Title",
"useSSHTitleDesc": "Update the tab title from the shell's window title instead of the host name",
"enableAutoMosh": "Enable Auto-Mosh",
"enableAutoMoshDesc": "Prefer Mosh over SSH if available",
"enableAutoTmux": "Enable Auto-Tmux",
@@ -390,6 +409,11 @@
"enableSessionLoggingDesc": "Record terminal session output for later review",
"enableCommandHistory": "Command History",
"enableCommandHistoryDesc": "Record commands run in this terminal for history and autocomplete",
"linkClickBehaviorLabel": "Link Click Behavior",
"linkClickBehaviorDesc": "Controls what happens when you click a link in the terminal. Use 'Default' to follow the app-level setting.",
"linkClickBehaviorDefault": "Default (follow app setting)",
"linkClickBehaviorConfirm": "Show popup to open or copy",
"linkClickBehaviorDirect": "Open directly",
"sudoPasswordAutoFillLabel": "Sudo Password Auto-fill",
"sudoPasswordAutoFillShortDesc": "Automatically provide sudo password when prompted",
"sudoPasswordAutoFillDesc": "Store a sudo password so host metrics, terminal prompts, and others can run privileged commands automatically.",
@@ -436,8 +460,15 @@
"proxmoxIntegration": "Proxmox Integration",
"enableProxmox": "Enable Proxmox",
"enableProxmoxDesc": "Mark this host as a Proxmox node. Enables guest discovery and import directly from this host.",
"proxmoxDefaultAuthType": "Default Auth Type",
"proxmoxDefaultAuthTypeDesc": "Authentication method applied to imported guest hosts. Choose the auth type that matches how you connect to your guests.",
"authTypePassword": "Password",
"authTypeKey": "SSH Key",
"authTypeCredential": "Credential",
"authTypeOpkssh": "OPKSSH",
"authTypeNone": "None",
"proxmoxDefaultCredential": "Default Credential",
"proxmoxDefaultCredentialDesc": "Credential used for imported guest hosts. The credential's username is applied to all guests.",
"proxmoxDefaultCredentialDesc": "Credential used for imported guest hosts when auth type is set to Credential.",
"proxmoxWindowsDetection": "Windows / RDP detection",
"proxmoxWindowsDetectionDesc": "Comma-separated name patterns that trigger RDP instead of SSH (case-insensitive)",
"proxmoxDockerDetection": "Docker detection",
@@ -465,6 +496,8 @@
"proxmoxImportFailed": "Import failed",
"enableFileManagerMonitor": "Enable File Manager",
"enableFileManagerMonitorDesc": "Browse and manage files on this host over SFTP",
"scpLegacyLabel": "SCP Legacy Mode",
"scpLegacyDesc": "Use legacy file transfer for servers that do not support the SFTP subsystem (e.g. embedded or minimal SSH servers).",
"defaultPathLabel": "Default Path",
"fileManagerPathHint": "The directory to open when the file manager launches for this host.",
"statusChecksLabel": "Status Checks",
@@ -522,6 +555,7 @@
"credentialUpdated": "Credential updated",
"credentialCreated": "Credential created",
"failedToSaveCredential": "Failed to save credential",
"credentialNameRequired": "Please enter a name for the credential",
"backToHosts": "Back to Hosts",
"backToCredentials": "Back to Credentials",
"pinned": "Pinned",
@@ -686,6 +720,7 @@
"nSelected": "{{count}} selected",
"featuresMenu": "Features",
"moveMenu": "Move",
"connectSelected": "Connect",
"cancelSelection": "Cancel",
"deployDialogDesc": "Deploy {{name}} to a host's authorized_keys.",
"targetHostLabel": "Target Host",
@@ -746,6 +781,12 @@
"guac": {
"connection": "Connection",
"authentication": "Authentication",
"storedCredential": "Stored Credential",
"noCredential": "No credential (direct credentials below)",
"authMethod": "Auth Method",
"authTypeDirect": "Direct",
"authTypeCredential": "Credential",
"selectCredential": "Select a credential...",
"connectionSettings": "Connection Settings",
"displaySettings": "Display Settings",
"audioSettings": "Audio Settings",
@@ -773,6 +814,13 @@
"initialProgram": "Initial Program",
"serverLayout": "Server Layout",
"timezone": "Timezone",
"loadBalanceInfo": "Load Balance Info / Cookie",
"loadBalanceInfoDesc": "RD Connection Broker cookie for RDS farm load balancing (e.g. tsv://MS Terminal Services Plugin.1.CollectionName)",
"guacdProxy": "guacd Proxy",
"guacdHostname": "guacd Host",
"guacdHostnamePlaceholder": "Global default",
"guacdPort": "guacd Port",
"guacdProxyDesc": "Override the global guacd instance for this connection. Leave blank to use the globally configured guacd.",
"gatewayHostname": "Gateway Hostname",
"gatewayPort": "Gateway Port",
"gatewayUsername": "Gateway Username",
@@ -937,7 +985,8 @@
"persisted": "Persisted in background",
"expiresIn": "Expires in {{duration}}",
"search": "Search connections...",
"noSearchResults": "No connections match your search"
"noSearchResults": "No connections match your search",
"rename": "Rename session"
},
"guacamole": {
"connecting": "Connecting to {{type}} session...",
@@ -1034,6 +1083,9 @@
"opksshAuthFailed": "Authentication failed. Please check your credentials and try again.",
"opksshSignInWith": "Sign in with {{provider}}",
"sudoPasswordPopupTitle": "Insert Password?",
"linkDialogTitle": "Open Link",
"linkDialogOpen": "Open",
"linkDialogCopy": "Copy",
"websocketAbnormalClose": "Connection closed unexpectedly. This may be due to a reverse proxy or SSL configuration issue. Please check server logs.",
"connectionLogTitle": "Connection Log",
"connectionLogCopy": "Copy logs to clipboard",
@@ -1043,7 +1095,12 @@
"connectionLogCopyFailed": "Failed to copy logs to clipboard",
"connectionRejected": "Connection rejected by server. Please check your authentication and network configuration.",
"hostKeyRejected": "SSH host key verification rejected. Connection cancelled.",
"sessionTakenOver": "Session was opened in another tab. Reconnecting..."
"sessionTakenOver": "Session was opened in another tab. Reconnecting...",
"split": {
"splitTab": "Split Tab",
"addToSplit": "Add to Split",
"removeFromSplit": "Remove from Split"
}
},
"fileManager": {
"noHostSelected": "No host selected",
@@ -1124,6 +1181,10 @@
"pathCopiedToClipboard": "Path copied to clipboard",
"pathsCopiedToClipboard": "{{count}} paths copied to clipboard",
"failedToCopyPath": "Failed to copy path to clipboard",
"copyFolderLink": "Copy Link to Folder",
"copyCurrentFolderLink": "Copy Link to Current Folder",
"folderLinkCopied": "Folder link copied to clipboard",
"failedToCopyFolderLink": "Failed to copy folder link",
"movedItems": "Moved {{count}} items",
"failedToDeleteItem": "Failed to delete item",
"itemRenamedSuccessfully": "{{type}} renamed successfully",
@@ -1233,6 +1294,8 @@
"move": "Move",
"searchInFile": "Search in file (Ctrl+F)",
"showKeyboardShortcuts": "Show keyboard shortcuts",
"decreaseFontSize": "Decrease font size",
"increaseFontSize": "Increase font size",
"startWritingMarkdown": "Start writing your markdown content...",
"loadingFileComparison": "Loading file comparison...",
"reload": "Reload",
@@ -1248,6 +1311,7 @@
"totpVerificationFailed": "TOTP verification failed",
"warpgateVerificationFailed": "Warpgate authentication failed",
"authenticationFailed": "Authentication failed",
"incorrectPassphrase": "Incorrect passphrase. Please try again.",
"verificationCodePrompt": "Verification code:",
"changePermissions": "Change Permissions",
"currentPermissions": "Current Permissions",
@@ -1632,7 +1696,7 @@
},
"auth": {
"tagline": "Self-hosted SSH and remote desktop management",
"loginTitle": "Login to Termix",
"loginTitle": "Welcome back",
"registerTitle": "Create Account",
"forgotPassword": "Forgot Password?",
"rememberMe": "Remember Device for 30 Days (includes TOTP)",
@@ -1684,6 +1748,7 @@
"dataLossWarning": "Resetting your password this way will delete all your saved SSH hosts, credentials, and other encrypted data. This action cannot be undone. Only use this if you have forgotten your password and are not logged in.",
"authenticationDisabled": "Authentication Disabled",
"authenticationDisabledDesc": "All authentication methods are currently disabled. Please contact your administrator.",
"passwordLoginDisabledDesc": "Password login is disabled. Please use an external authentication provider below.",
"attemptsRemaining": "{{count}} attempts remaining"
},
"hostKey": {
@@ -1812,7 +1877,8 @@
"serverStatsCard": "Server Stats",
"panelMain": "Main",
"panelSide": "Side",
"justNow": "just now"
"justNow": "just now",
"serviceLinks": "Service Links"
},
"dashboardTab": {
"stable": "STABLE",
@@ -1833,7 +1899,17 @@
"done": "Done",
"editModeInstructions": "Drag cards to reorder · Drag the column divider to resize columns · Drag the bottom edge of a card to resize its height · Trash to remove",
"empty": "Empty",
"clear": "Clear"
"clear": "Clear",
"serviceLinksTitle": "Service Links",
"serviceLinksEmpty": "No service links yet",
"serviceLinksAddLabel": "Label",
"serviceLinksAddUrl": "URL",
"serviceLinksAdd": "Add",
"serviceLinksLabelPlaceholder": "My Service",
"serviceLinksUrlPlaceholder": "http://192.168.1.10:8080",
"serviceLinksInvalidUrl": "Must be a valid http or https URL",
"disk": "Disk",
"viewServerDetails": "View server details"
},
"sessionLogs": {
"title": "Session Logs",
@@ -2036,6 +2112,38 @@
"sectionDatabase": "Database",
"sectionApiKeys": "API Keys",
"sectionAuditLog": "Audit Log",
"sectionSsl": "SSL / Let's Encrypt",
"sslDescription": "Automatically issue and renew a trusted SSL certificate from Let's Encrypt. Requires a public domain and port 80 or DNS access.",
"sslDocsLink": "View SSL docs",
"sslDomain": "Domain",
"sslDomainPlaceholder": "termix.example.com",
"sslDomainDesc": "The public domain name for the certificate.",
"sslEmail": "Email",
"sslEmailPlaceholder": "admin@example.com",
"sslEmailDesc": "Contact email for Let's Encrypt notifications and account.",
"sslChallengeType": "Challenge Type",
"sslChallengeTypeDesc": "How to prove domain ownership to Let's Encrypt.",
"sslChallengeHttp": "HTTP (webroot) - requires port 80 accessible from the internet",
"sslChallengeDns": "DNS (Cloudflare) - requires a Cloudflare API token",
"sslCloudflareToken": "Cloudflare API Token",
"sslCloudflareTokenPlaceholder": "Enter token...",
"sslCloudflareTokenDesc": "Scoped token with Zone:DNS:Edit permission for your domain.",
"sslCertStatus": "Certificate Status",
"sslCertStatusNone": "No certificate",
"sslCertStatusValid": "Valid",
"sslCertStatusExpiring": "Expiring soon",
"sslCertStatusExpired": "Expired",
"sslCertExpiresAt": "Expires {{date}}",
"sslLastIssued": "Last issued {{date}}",
"sslRequestCert": "Issue / Renew Certificate",
"sslRequestCertLoading": "Requesting certificate...",
"sslRequestCertSuccess": "Certificate issued and installed successfully",
"sslRequestCertFailed": "Certificate request failed",
"sslSave": "Save Settings",
"sslSaved": "SSL settings saved",
"sslSaveFailed": "Failed to save SSL settings",
"sslRequiresDomain": "Domain and email are required",
"sslInfoNote": "After issuing a certificate, enable SSL in your environment variables (ENABLE_SSL=true) and restart Termix.",
"auditLogTotal": "{{total}} total entries",
"auditLogEmpty": "No audit log entries found",
"auditLogSuccess": "Success",
@@ -2052,11 +2160,13 @@
"auditLogFilterTo": "To",
"auditLogFilterAll": "All",
"allowRegistration": "Allow User Registration",
"allowRegistrationDesc": "Let new users self-register",
"allowRegistrationDesc": "Let new users self-register with a username and password",
"allowPasswordLogin": "Allow Password Login",
"allowPasswordLoginDesc": "Username/password login",
"oidcAutoProvision": "OIDC Auto-Provision",
"oidcAutoProvisionDesc": "Auto-create accounts for OIDC users even when registration is disabled",
"oidcAutoProvisionDesc": "Auto-create accounts for OIDC/SSO users on first login (independent of the registration toggle)",
"oidcSilentLoginDefault": "Silent OIDC Login by Default",
"oidcSilentLoginDefaultDesc": "Automatically redirect to OIDC login on every visit, skipping the login form entirely",
"allowPasswordReset": "Allow Password Reset",
"allowPasswordResetDesc": "Reset code via Docker logs",
"commandHistoryEnabled": "Command History",
@@ -2094,6 +2204,8 @@
"oidcAdminGroupDesc": "Users in this group are granted admin. Leave empty to disable group sync.",
"oidcGroupClaim": "Group Claim",
"oidcGroupClaimDesc": "Optional. The claim path that contains the user's groups. Defaults to groups, roles, then group. Use this for providers with a custom claim (e.g. Zitadel).",
"oidcCaCert": "Custom CA Certificate",
"oidcCaCertDesc": "Optional. PEM-encoded CA certificate for OIDC providers using a private or self-signed CA. Leave empty to use the system trust store.",
"removeOidc": "Remove",
"usersCount": "{{count}} users",
"createUser": "Create",
@@ -2193,10 +2305,19 @@
"linkAccountSuccess": "Accounts linked successfully",
"linkAccountFailed": "Failed to link accounts",
"linkAccountInProgress": "Linking...",
"unlinkAccountTitle": "Unlink OIDC",
"unlinkAccountDesc": "Remove OIDC authentication from {{username}}. They will only be able to log in with their password.",
"unlinkAccountWarning": "This will remove OIDC login from this account. The user must have a password set to continue logging in.",
"unlinkAccount": "Unlink OIDC",
"unlinkAccountInProgress": "Unlinking...",
"unlinkAccountSuccess": "OIDC unlinked successfully",
"unlinkAccountFailed": "Failed to unlink OIDC",
"saving": "Saving...",
"updateRegistrationFailed": "Failed to update registration setting",
"updatePasswordLoginFailed": "Failed to update password login setting",
"cannotDisablePasswordLoginWithTotp": "Cannot disable password login while 2FA is enabled for one or more users. Disable 2FA first.",
"updateOidcAutoProvisionFailed": "Failed to update OIDC auto-provision setting",
"updateOidcSilentLoginDefaultFailed": "Failed to update silent OIDC login setting",
"updatePasswordResetFailed": "Failed to update password reset setting",
"sessionTimeoutRange2": "Session timeout must be between 1 and 720 hours",
"sessionTimeoutSaved": "Session timeout saved",
@@ -2233,7 +2354,27 @@
"importSelectFile": "Please select a file first",
"importCompleted": "Import completed: {{total}} items imported, {{skipped}} skipped",
"importFailed": "Import failed: {{error}}",
"importError": "Database import failed"
"importError": "Database import failed",
"sectionHostDefaults": "Host Defaults",
"hostDefaultsDesc": "Settings applied automatically when creating a new host. Individual hosts can still override these.",
"hostDefaultsSocks5": "SOCKS5 Proxy",
"hostDefaultsUseSocks5": "Enable SOCKS5 Proxy",
"hostDefaultsUseSocks5Desc": "Pre-fill SOCKS5 proxy on all new hosts",
"hostDefaultsSocks5Host": "Proxy Host / Port",
"hostDefaultsSocks5Username": "Proxy Username",
"hostDefaultsSocks5Password": "Proxy Password",
"hostDefaultsMetrics": "Host Metrics",
"hostDefaultsMetricsEnabled": "Enable Metrics",
"hostDefaultsMetricsEnabledDesc": "Collect CPU, memory, and other stats on new hosts by default",
"hostDefaultsStatusCheckEnabled": "Enable Status Check",
"hostDefaultsStatusCheckEnabledDesc": "Poll online/offline status on new hosts by default",
"hostDefaultsTerminal": "Terminal",
"hostDefaultsSessionLogging": "Session Logging",
"hostDefaultsSessionLoggingDesc": "Record terminal sessions on new hosts by default",
"hostDefaultsCommandHistory": "Command History",
"hostDefaultsCommandHistoryDesc": "Track command history on new hosts by default",
"hostDefaultsSaved": "Host defaults saved",
"hostDefaultsSaveFailed": "Failed to save host defaults"
},
"newUi": {
"sidebar": {
@@ -2292,7 +2433,13 @@
"splitTab": "Split Tab",
"addToSplit": "Add to Split",
"removeFromSplit": "Remove from Split",
"assignToPane": "Assign to pane"
"assignToPane": "Assign to pane",
"hotkeysTitle": "Keyboard Shortcuts",
"hotkeysSplitRight": "Toggle 2-way split",
"hotkeysSplitBelow": "Toggle 3-way split",
"hotkeysNavigatePane": "Navigate panes",
"hotkeysNextTab": "Next tab",
"hotkeysPrevTab": "Previous tab"
},
"snippets": {
"title": "Snippets",
@@ -2364,7 +2511,33 @@
"shareLoadError": "Failed to load share data",
"loading": "Loading...",
"close": "Close",
"reorderFailed": "Failed to save snippet order"
"reorderFailed": "Failed to save snippet order",
"importExport": "Import / Export",
"exportBtn": "Export JSON",
"importBtn": "Import JSON",
"exportSuccess": "Snippets exported successfully",
"exportFailed": "Failed to export snippets",
"importTitle": "Import Snippets",
"importDescription": "Import snippets and folders from a JSON file exported by Termix",
"importDropOrClick": "Drop a JSON file here or click to browse",
"importSelectedFile": "Selected: {{name}}",
"importOverwrite": "Overwrite existing snippets with the same name and folder",
"importStartBtn": "Import",
"importSuccess": "Import complete: {{snippets}} snippet(s) added, {{updated}} updated, {{skipped}} skipped, {{folders}} folder(s) added",
"importFailed": "Failed to import snippets",
"importInvalidFile": "Invalid file: expected a JSON object with snippets or folders arrays",
"targetHostsLabel": "Target Hosts",
"targetHostsHint": "Assign hosts to run this snippet directly without an open terminal.",
"noHostsAvailable": "No hosts configured",
"clearTargetHosts": "Clear all",
"hasTargetHosts": "Has target hosts",
"runOnTargets": "Run on Targets",
"directRunSuccess": "Ran \"{{name}}\" on {{count}} host(s)",
"directRunPartialFail": "\"{{name}}\" failed on one or more hosts",
"executionResultTitle": "Execution Results: {{name}}",
"executionResultDescription": "Output from running the snippet on each target host.",
"executionSuccess": "Success",
"executionFailed": "Failed"
},
"userProfile": {
"storageModeLocal": "Browser",
@@ -2389,6 +2562,7 @@
"versionLabel": "Version",
"deleteAccount": "Delete Account",
"deleteAccountDescription": "Permanently delete your account",
"changeServerDescription": "Switch to a different Termix backend server",
"deleteButton": "Delete",
"deleteAccountPermanent": "This action is permanent and cannot be undone.",
"deleteAccountWarning": "All sessions, hosts, credentials, and settings will be permanently deleted.",
@@ -2400,6 +2574,8 @@
"settingsTerminal": "Terminal",
"commandAutocomplete": "Command Autocomplete",
"commandAutocompleteDesc": "Show autocomplete while typing",
"terminalLinkBehavior": "Terminal Link Click",
"terminalLinkBehaviorDesc": "Default behavior when clicking links in the terminal",
"historyTracking": "History Tracking",
"historyTrackingDesc": "Track terminal commands",
"commandPalette": "Command Palette",
@@ -2413,6 +2589,10 @@
"showHostTagsDesc": "Display tags in host list",
"hostTrayOnClick": "Click to Expand Host Actions",
"hostTrayOnClickDesc": "Always show connection buttons; click to expand management options instead of hover",
"compactHostView": "Compact Host View",
"compactHostViewDesc": "Collapse each host to a single line showing only its name and address",
"statusColors": "Real Status Colors",
"statusColorsDesc": "Use green/red for online/offline status instead of the accent color",
"pinAppRail": "Pin App Rail",
"pinAppRailDesc": "Keep the left sidebar app rail always expanded instead of expanding on hover",
"settingsNavigation": "Navigation",
@@ -2581,5 +2761,29 @@
"timeMinutes": "{{count}}m ago",
"timeHours": "{{count}}h ago",
"timeDays": "{{count}}d ago"
},
"mobileKeyboard": {
"shift": "Shift",
"ctrl": "Ctrl",
"esc": "Esc",
"tab": "Tab",
"backTab": "⇥",
"arrowUp": "Arrow Up",
"arrowDown": "Arrow Down",
"arrowLeft": "Arrow Left",
"arrowRight": "Arrow Right",
"home": "Home",
"end": "End",
"pageUp": "PgUp",
"pageDown": "PgDn",
"delete": "Del",
"editQuickKeys": "Edit quick keys",
"quickKeysTitle": "Quick Keys",
"quickKeysDesc": "Tap × to remove. Supports up to 8 characters.",
"quickKeyPlaceholder": "e.g. sudo ",
"addQuickKey": "Add",
"removeQuickKey": "Remove",
"resetDefaults": "Reset to defaults",
"done": "Done"
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More