mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-07-16 05:13:36 +00:00
v2.3.2 (#874)
* fix: patch critical security vulnerabilities (GHSA-5fqh, GHSA-ccm8, GHSA-wqfw, GHSA-xmjh) - Remove passwordHash from /users/list API response - Require both password and TOTP code for MFA-critical operations - Restrict tunnel kill commands to tunnelMarker-only matching - Add session ownership middleware for file manager endpoints * fix: allow navigating away from split-view to non-pane tabs Show the normal view container on top of the split view when the active tab is not assigned to any pane, so users can switch to dashboard or other tabs while split mode is active. Closes #739 * fix: add inline quick-action buttons on host name row Show Terminal, Files, RDP, and VNC shortcut icons on the host name row on hover, so users can launch connections with a single click without expanding the full action tray. Closes #736 * fix: restore SSH keepalive interval to 30s to prevent random disconnects Revert keepalive defaults from 60s/5 to 30s/3 across terminal, tunnel, and server-stats SSH connections. The 60s interval introduced in 2.3.0 causes firewalls and NAT devices to drop idle connections before the next keepalive probe. Closes #733 * fix: apply guacamole-lite protocol patch in Docker builds The Dockerfile uses --ignore-scripts which skips the postinstall hook that patches guacamole-lite for guacd 1.6.0 protocol VERSION_1_5_0. Without this patch, the timezone handshake instruction is not sent for protocol versions above 1.1.0, causing VNC connections to fail immediately on connect. Closes #734 * fix: show correct icons for network interface types Detect interface type from name pattern and show appropriate icons: WiFi for wlan/wl*, Ethernet (Cable) for eth/en*, Container for docker/bridge/virtual, generic Network for others. Closes #720 * fix: resolve sudo password for shared host users The password endpoint required hosts.userId to match the requesting user, which fails for shared hosts. Now falls back to decrypting with the owner's key when the requesting user doesn't own the host. Closes #717 * fix: use jump hosts for online status check and metrics collection Status polling now pings the first jump host instead of the unreachable target when jump hosts are configured. The /metrics/start endpoint now tunnels through the jump host chain to reach the target host. Closes #716 * fix: broaden sudo prompt detection for newer distros Add patterns for 'password for <user>:' and bare 'Password:' prompts in addition to the existing [sudo] and sudo: patterns. Covers Ubuntu 26.04 and other distros that use different sudo prompt formats. Closes #718 * fix: recalculate terminal layout after web fonts load xterm.js measures character widths at open() time. If custom fonts haven't loaded yet, measurements use the fallback font and spacing becomes incorrect. Now refresh and re-fit the terminal once document.fonts.ready resolves. Closes #710 * fix: improve terminal cwd detection and initial directory command Remove '&& pwd' from initial directory command — the shell prompt shows the new directory naturally. Fixes PowerShell 5.1 which doesn't support '&&' as a statement separator. Prepend Ctrl+U to get_cwd command to clear any pending input before injecting the cwd probe, reducing interference with foreground programs. Closes #713, #714 * fix: decode base64 file content as UTF-8 in file manager Replace bare atob() with TextDecoder('utf-8') for base64 content decoding. atob() only handles Latin-1, so multi-byte UTF-8 characters like 'é' were decoded as 'é'. Closes #719 * fix: normalize lazy import default exports for iOS compatibility Wrap all lazy() imports with explicit .then(m => ({ default: m.default })) to ensure consistent module resolution across platforms. iOS Safari/WebView may handle bare lazy(() => import(...)) differently, returning the module object instead of extracting the default export. Closes #721 * fix: prevent RDP display from snapping back after container resize Remove immediate rescaleDisplay() from ResizeObserver callback. The display.onresize event already triggers rescaling when the RDP server responds with the new resolution. Calling rescaleDisplay before the server responds uses stale display dimensions, causing the bottom of the screen to be truncated. Closes #725 * fix: add portal Desktop DBus permission for Flatpak URL opening Flatpak sandbox blocks window.open() without the portal permission, causing terminal link clicks to open about:blank. Add talk-name for org.freedesktop.portal.Desktop to enable xdg-desktop-portal URL handling. Closes #704 * chore: remove unused code and fix PR checks (#851) * chore: remove unused frontend code * chore: prune unused theme exports * ci: fix pr check failures * chore: reduce lint warnings * feat(oidc): expose admin_group via OIDC_ADMIN_GROUP env var (#828) The admin-group OIDC sync added in 2.3.0 (#782) reads `config.admin_group` to sync the user's admin flag from OIDC group membership on each login. That field is only populated when the OIDC config is stored in the in-app DB — `getOIDCConfigFromEnv()` does not expose it, so deployments using the env-var config path (declarative IaC: Helm/Compose/Puppet) cannot enable the feature without abandoning env vars and pasting the client_secret into the admin UI. Add `admin_group: process.env.OIDC_ADMIN_GROUP || ""` to the env-config return type and object. Backward compatible: when unset, the existing `if (config.admin_group)` guard at users.ts:1336 keeps the sync block skipped, matching today's behavior. * chore: reduce explicit-any warnings * chore: reduce more explicit-any warnings * chore: reduce lint warnings * chore: silence intentional hook dependency warnings * chore: clean dependency tooling * chore: narrow frontend tsconfig scope * chore: reduce type assertion debt * refactor: split host manager components * refactor: split host editor sections * refactor: split api client modules * refactor: split more api clients * refactor: split user settings api clients * refactor: split tab and history api clients * refactor: split tunnel api clients * refactor: split server stats api client * refactor: split file manager data api * refactor: split ssh file operations api * refactor: split host editor general tab * refactor: split host editor guacamole tabs * refactor: split ssh host management api * refactor: split admin general settings sections * refactor: split admin database section * refactor: split admin management sections * refactor: split admin keys and dialogs * refactor: split system status api clients * refactor: split user route helpers * refactor: split host route helpers * refactor: split file manager ssh helpers * refactor: split file manager session helpers * refactor: split file manager listing routes * refactor: split host opkssh routes * refactor: split file manager content routes * refactor: split user api key routes * refactor: split host folder routes * refactor: split user settings routes * refactor: split user totp routes * refactor: split host file manager bookmark routes * refactor: split file manager operation routes * refactor: split server stats settings routes * refactor: split user session routes * refactor: split host command history routes * refactor: split server stats viewer routes * refactor: split docker container routes * refactor: split user oidc account routes * refactor: split host autostart routes * refactor: split host internal routes * refactor: split host network routes * refactor: split user password reset routes * refactor: split user admin routes * refactor: split user data access routes * refactor: split credential key routes * refactor: split credential deploy routes * refactor: split host bulk routes * refactor: split server stats connection helpers * refactor: split tunnel helpers * refactor: split file manager action routes * refactor: split terminal auth helpers * refactor: split terminal jump host helpers * refactor: split tunnel relay helpers * refactor: split tunnel socks relay helpers * refactor: split tunnel c2s relay handlers * refactor: split server stats session helpers * refactor: split terminal presentation helpers * refactor: split file manager presentation helpers * refactor: split file manager toolbar * fix(guacamole-lite): send name instruction for protocol >= 1.3.0 The Guacamole protocol added the `name` handshake instruction in 1.3.0 (an optional human-readable identifier for the joining user). guacd 1.6.0 began requiring it during the VNC handshake even when negotiating older protocol versions, causing connections to silently drop right after the "User joined" log line with no client-visible error. This patch extends scripts/patch-guacamole-lite.cjs with a third idempotent string-replacement that injects the `name` instruction send when guacamole-lite has negotiated protocol VERSION_1_3_0 or VERSION_1_5_0. Verified end-to-end: guacd debug logs now show `Processing instruction: name` and `Client is using protocol version "VERSION_1_5_0"` (previously stuck at VERSION_1_1_0). VNC session connects successfully against guacd 1.5.5 / macOS Tahoe target. Related: Termix-SSH/Support#567, #734 * fix: resolve recent support bugs * fix(admin): wire up OIDC-to-password link dialog submit + visibility The admin user-management UI already shipped a link icon and a "Link Account" dialog, but two things blocked the flow: 1. The submit button had no onClick handler and the username input was uncontrolled (no value/onChange). Clicking "Link Accounts" was a no-op — no network request, no console error, no toast. 2. The link icon's visibility condition was `user.isOidc && !user.passwordHash`, which hid the button on OIDC users that had been auto-provisioned with a passwordHash. Termix's OIDC provisioning sets a passwordHash by default, so the button was hidden on virtually every OIDC-provisioned user. This change: - Adds `linkOIDCToPasswordAccount` to the imports from `@/main-axios`. - Adds two pieces of dialog state: `linkAccountTargetUsername` and `linkAccountSubmitting`. - Makes the dialog's Input field a controlled component. - Wires the submit Button's onClick to call `linkOIDCToPasswordAccount`, emit success/error toasts, refresh the local user list, and close the dialog. - Loosens the visibility condition to `user.isOidc` (the backend handler already enforces all integrity checks). - Adds `linkAccountSuccess`, `linkAccountFailed`, and `linkAccountInProgress` translation keys to `en.json`. Verified locally: full Docker build via docker/Dockerfile passes; `tsc --noEmit` is clean; `prettier --check .` is clean; ESLint produces the same warning count as upstream (16 pre-existing `any`-type warnings, 0 errors). * fix: support native oidc callbacks (#856) * docs: add cloudflare tunnel guidance (#857) * fix: sync appearance preferences (#858) * fix: pass through terminal tab completion (#859) * fix: resolve terminal jump hosts server-side (#860) * fix(electron): auto-allow SSL certificates for private network hosts (#861) Add private network IP detection (RFC 1918, link-local, loopback, IPv6 ULA) to the Electron certificate-error handler so that connections to local/private servers like 192.168.x.x bypass SSL validation automatically. Also add an explicit "Allow invalid certificate" toggle in the server config UI for public HTTPS servers with self-signed certs. * fix: restore host password copy actions (#862) * feat: support single-host direct tunnels (ssh -L style) (#863) Add direct tunnel mode that uses a single SSH host for port forwarding, matching the behavior of ssh -L / ssh -R / ssh -D without requiring a second endpoint host in the Termix database. The Termix server creates a local TCP listener and forwards through the SSH channel directly. * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * fix: backend build errors (Type) * fix: mobile auth failing to login with webview * fix: mobile app geting incorrectly sent auth token * feat: commit existing frontend/backend e2e/unit tests (skipped tests containing private info like OIDC and real server testing) * feat: host-to-host file transfer via server relay * feat: removed host management from command palette, fixed command palette opening wrong protocol, export/import failing for ssh key hosts, docker ssh2 native crypto not compiled, persisted terminal tabs attempt SSh on RDP hosts after migration, improved layout for click to expand hosts, show ip/username without having to hover over hosts * fix: credentials not indexing into host manager until refresh * feat: update credentials lists to match hosts list UI/UX * feat: add rename folder UI * feat: improve transfer to host UI/UX * chore: increment ver * feat: improve transfer to host UI * feat: implement initial auto release system --------- Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com> Co-authored-by: nicodarge <43711429+nicodarge@users.noreply.github.com> Co-authored-by: Raman Gupta <7243222+raman325@users.noreply.github.com> Co-authored-by: luc <luc_cook@hotmail.co.uk>
This commit is contained in:
Binary file not shown.
@@ -0,0 +1,93 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import crypto from "crypto";
|
||||
import { FieldCrypto } from "./field-crypto.js";
|
||||
|
||||
const masterKey = crypto.randomBytes(32);
|
||||
|
||||
describe("FieldCrypto.encryptField / decryptField", () => {
|
||||
it("round-trips a plaintext value", () => {
|
||||
const encrypted = FieldCrypto.encryptField(
|
||||
"s3cr3t-password",
|
||||
masterKey,
|
||||
"record-1",
|
||||
"password",
|
||||
);
|
||||
const decrypted = FieldCrypto.decryptField(
|
||||
encrypted,
|
||||
masterKey,
|
||||
"record-1",
|
||||
"password",
|
||||
);
|
||||
expect(decrypted).toBe("s3cr3t-password");
|
||||
});
|
||||
|
||||
it("returns empty string for empty input", () => {
|
||||
expect(FieldCrypto.encryptField("", masterKey, "r", "f")).toBe("");
|
||||
expect(FieldCrypto.decryptField("", masterKey, "r", "f")).toBe("");
|
||||
});
|
||||
|
||||
it("produces different ciphertext each time (random IV + salt)", () => {
|
||||
const a = FieldCrypto.encryptField("same", masterKey, "r", "f");
|
||||
const b = FieldCrypto.encryptField("same", masterKey, "r", "f");
|
||||
expect(a).not.toBe(b);
|
||||
expect(FieldCrypto.decryptField(a, masterKey, "r", "f")).toBe("same");
|
||||
expect(FieldCrypto.decryptField(b, masterKey, "r", "f")).toBe("same");
|
||||
});
|
||||
|
||||
it("fails to decrypt with the wrong master key", () => {
|
||||
const encrypted = FieldCrypto.encryptField("value", masterKey, "r", "f");
|
||||
const wrongKey = crypto.randomBytes(32);
|
||||
expect(() =>
|
||||
FieldCrypto.decryptField(encrypted, wrongKey, "r", "f"),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("fails to decrypt when the field name context differs", () => {
|
||||
const encrypted = FieldCrypto.encryptField(
|
||||
"value",
|
||||
masterKey,
|
||||
"r",
|
||||
"password",
|
||||
);
|
||||
expect(() =>
|
||||
FieldCrypto.decryptField(encrypted, masterKey, "r", "key"),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("detects tampering with the ciphertext (GCM auth tag)", () => {
|
||||
const encrypted = FieldCrypto.encryptField("value", masterKey, "r", "f");
|
||||
const parsed = JSON.parse(encrypted);
|
||||
// Flip a hex char in the encrypted data.
|
||||
parsed.data = (parsed.data[0] === "a" ? "b" : "a") + parsed.data.slice(1);
|
||||
const tampered = JSON.stringify(parsed);
|
||||
expect(() =>
|
||||
FieldCrypto.decryptField(tampered, masterKey, "r", "f"),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("throws when the encrypted payload is missing recordId context", () => {
|
||||
const encrypted = FieldCrypto.encryptField("value", masterKey, "r", "f");
|
||||
const parsed = JSON.parse(encrypted);
|
||||
delete parsed.recordId;
|
||||
expect(() =>
|
||||
FieldCrypto.decryptField(JSON.stringify(parsed), masterKey, "r", "f"),
|
||||
).toThrow(/recordId/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("FieldCrypto.shouldEncryptField", () => {
|
||||
it("identifies encrypted fields per table", () => {
|
||||
expect(FieldCrypto.shouldEncryptField("users", "passwordHash")).toBe(true);
|
||||
expect(FieldCrypto.shouldEncryptField("ssh_data", "password")).toBe(true);
|
||||
expect(
|
||||
FieldCrypto.shouldEncryptField("ssh_credentials", "privateKey"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false for non-encrypted fields and unknown tables", () => {
|
||||
expect(FieldCrypto.shouldEncryptField("users", "username")).toBe(false);
|
||||
expect(FieldCrypto.shouldEncryptField("unknown_table", "password")).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { loginRateLimiter } from "./login-rate-limiter.js";
|
||||
|
||||
// The limiter is a shared singleton, so each test uses unique ip/username keys
|
||||
// and resets them to stay isolated.
|
||||
describe("loginRateLimiter login attempts", () => {
|
||||
let ip: string;
|
||||
let username: string;
|
||||
let counter = 0;
|
||||
|
||||
beforeEach(() => {
|
||||
counter += 1;
|
||||
ip = `10.0.0.${counter}`;
|
||||
username = `user${counter}`;
|
||||
loginRateLimiter.resetAttempts(ip, username);
|
||||
});
|
||||
|
||||
it("starts unlocked with the full attempt budget", () => {
|
||||
expect(loginRateLimiter.isLocked(ip, username).locked).toBe(false);
|
||||
expect(loginRateLimiter.getRemainingAttempts(ip, username)).toBe(5);
|
||||
});
|
||||
|
||||
it("decrements remaining attempts on each failure", () => {
|
||||
loginRateLimiter.recordFailedAttempt(ip, username);
|
||||
expect(loginRateLimiter.getRemainingAttempts(ip, username)).toBe(4);
|
||||
loginRateLimiter.recordFailedAttempt(ip, username);
|
||||
expect(loginRateLimiter.getRemainingAttempts(ip, username)).toBe(3);
|
||||
});
|
||||
|
||||
it("locks the account after 5 failed attempts", () => {
|
||||
for (let i = 0; i < 5; i++) {
|
||||
loginRateLimiter.recordFailedAttempt(ip, username);
|
||||
}
|
||||
const result = loginRateLimiter.isLocked(ip, username);
|
||||
expect(result.locked).toBe(true);
|
||||
expect(result.remainingTime).toBeGreaterThan(0);
|
||||
expect(loginRateLimiter.getRemainingAttempts(ip, username)).toBe(0);
|
||||
});
|
||||
|
||||
it("clears the lock and counters on reset (successful login)", () => {
|
||||
for (let i = 0; i < 5; i++) {
|
||||
loginRateLimiter.recordFailedAttempt(ip, username);
|
||||
}
|
||||
expect(loginRateLimiter.isLocked(ip, username).locked).toBe(true);
|
||||
|
||||
loginRateLimiter.resetAttempts(ip, username);
|
||||
expect(loginRateLimiter.isLocked(ip, username).locked).toBe(false);
|
||||
expect(loginRateLimiter.getRemainingAttempts(ip, username)).toBe(5);
|
||||
});
|
||||
|
||||
it("locks by IP even without a username", () => {
|
||||
const soloIp = `192.168.1.${counter}`;
|
||||
for (let i = 0; i < 5; i++) {
|
||||
loginRateLimiter.recordFailedAttempt(soloIp);
|
||||
}
|
||||
expect(loginRateLimiter.isLocked(soloIp).locked).toBe(true);
|
||||
loginRateLimiter.resetAttempts(soloIp);
|
||||
});
|
||||
});
|
||||
|
||||
describe("loginRateLimiter TOTP attempts", () => {
|
||||
let userId: string;
|
||||
let counter = 0;
|
||||
|
||||
beforeEach(() => {
|
||||
counter += 1;
|
||||
userId = `totp-user${counter}`;
|
||||
loginRateLimiter.resetTOTPAttempts(userId);
|
||||
});
|
||||
|
||||
it("locks TOTP after 5 failures and resets cleanly", () => {
|
||||
expect(loginRateLimiter.isTOTPLocked(userId).locked).toBe(false);
|
||||
for (let i = 0; i < 5; i++) {
|
||||
loginRateLimiter.recordFailedTOTPAttempt(userId);
|
||||
}
|
||||
expect(loginRateLimiter.isTOTPLocked(userId).locked).toBe(true);
|
||||
expect(loginRateLimiter.getRemainingTOTPAttempts(userId)).toBe(0);
|
||||
|
||||
loginRateLimiter.resetTOTPAttempts(userId);
|
||||
expect(loginRateLimiter.isTOTPLocked(userId).locked).toBe(false);
|
||||
expect(loginRateLimiter.getRemainingTOTPAttempts(userId)).toBe(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe("loginRateLimiter password-reset-code attempts", () => {
|
||||
let username: string;
|
||||
let counter = 0;
|
||||
|
||||
beforeEach(() => {
|
||||
counter += 1;
|
||||
username = `reset-user${counter}`;
|
||||
loginRateLimiter.resetResetCodeAttempts(username);
|
||||
});
|
||||
|
||||
it("locks reset codes after 5 failures and resets cleanly", () => {
|
||||
expect(loginRateLimiter.isResetCodeLocked(username).locked).toBe(false);
|
||||
for (let i = 0; i < 5; i++) {
|
||||
loginRateLimiter.recordResetCodeAttempt(username);
|
||||
}
|
||||
expect(loginRateLimiter.isResetCodeLocked(username).locked).toBe(true);
|
||||
|
||||
loginRateLimiter.resetResetCodeAttempts(username);
|
||||
expect(loginRateLimiter.isResetCodeLocked(username).locked).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
// permission-manager imports the side-effectful DB barrel and the logger at the
|
||||
// top level. Stub both so importing the module does not spin up the real
|
||||
// database / encryption stack. We then drive hasPermission via a spied
|
||||
// getUserPermissions so we test the wildcard-matching logic in isolation.
|
||||
vi.mock("../database/db/index.js", () => ({ db: {} }));
|
||||
vi.mock("./logger.js", () => ({
|
||||
databaseLogger: {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const { PermissionManager } = await import("./permission-manager.js");
|
||||
|
||||
type PermissionManagerInstance = ReturnType<
|
||||
typeof PermissionManager.getInstance
|
||||
>;
|
||||
|
||||
describe("PermissionManager.hasPermission wildcard matching", () => {
|
||||
let manager: PermissionManagerInstance;
|
||||
|
||||
function withPermissions(permissions: string[]) {
|
||||
vi.spyOn(manager, "getUserPermissions").mockResolvedValue(permissions);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
manager = PermissionManager.getInstance();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("grants everything for the global wildcard '*'", async () => {
|
||||
withPermissions(["*"]);
|
||||
expect(await manager.hasPermission("u1", "hosts.read")).toBe(true);
|
||||
expect(await manager.hasPermission("u1", "anything.at.all")).toBe(true);
|
||||
});
|
||||
|
||||
it("grants an exact permission match", async () => {
|
||||
withPermissions(["hosts.read", "hosts.write"]);
|
||||
expect(await manager.hasPermission("u1", "hosts.read")).toBe(true);
|
||||
});
|
||||
|
||||
it("grants via a prefix wildcard", async () => {
|
||||
withPermissions(["hosts.*"]);
|
||||
expect(await manager.hasPermission("u1", "hosts.read")).toBe(true);
|
||||
expect(await manager.hasPermission("u1", "hosts.write")).toBe(true);
|
||||
});
|
||||
|
||||
it("grants via a deep prefix wildcard", async () => {
|
||||
withPermissions(["admin.users.*"]);
|
||||
expect(await manager.hasPermission("u1", "admin.users.delete")).toBe(true);
|
||||
});
|
||||
|
||||
it("denies when no exact or wildcard permission matches", async () => {
|
||||
withPermissions(["hosts.read"]);
|
||||
expect(await manager.hasPermission("u1", "hosts.write")).toBe(false);
|
||||
expect(await manager.hasPermission("u1", "credentials.read")).toBe(false);
|
||||
});
|
||||
|
||||
it("denies when the user has no permissions", async () => {
|
||||
withPermissions([]);
|
||||
expect(await manager.hasPermission("u1", "hosts.read")).toBe(false);
|
||||
});
|
||||
|
||||
it("does not let a narrower wildcard grant a sibling branch", async () => {
|
||||
withPermissions(["hosts.read.*"]);
|
||||
expect(await manager.hasPermission("u1", "hosts.write")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,39 @@
|
||||
import { SocksClient } from "socks";
|
||||
import type { SocksClientOptions } from "socks";
|
||||
import net from "net";
|
||||
import dns from "dns/promises";
|
||||
import { sshLogger } from "./logger.js";
|
||||
import type { ProxyNode } from "../../types/index.js";
|
||||
|
||||
function isBlockedAddress(ip: string): boolean {
|
||||
if (ip === "0.0.0.0" || ip === "::1" || ip === "::") return true;
|
||||
|
||||
const parts = ip.split(".").map(Number);
|
||||
if (parts.length !== 4) return false;
|
||||
|
||||
if (parts[0] === 127) return true;
|
||||
if (parts[0] === 10) return true;
|
||||
if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;
|
||||
if (parts[0] === 192 && parts[1] === 168) return true;
|
||||
if (parts[0] === 169 && parts[1] === 254) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
async function validateHost(host: string): Promise<void> {
|
||||
if (net.isIP(host)) {
|
||||
if (isBlockedAddress(host)) {
|
||||
throw new Error("Proxy target address is not allowed");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const { address } = await dns.lookup(host);
|
||||
if (isBlockedAddress(address)) {
|
||||
throw new Error("Proxy target address is not allowed");
|
||||
}
|
||||
}
|
||||
|
||||
export interface SOCKS5Config {
|
||||
useSocks5?: boolean;
|
||||
socks5Host?: string;
|
||||
@@ -289,6 +319,17 @@ export async function testProxyConnectivity(options: {
|
||||
testTarget?: { host: string; port: number };
|
||||
}): Promise<{ success: boolean; latencyMs: number }> {
|
||||
const target = options.testTarget ?? { host: "google.com", port: 443 };
|
||||
|
||||
await validateHost(target.host);
|
||||
if (options.singleProxy) {
|
||||
await validateHost(options.singleProxy.host);
|
||||
}
|
||||
if (options.proxyChain) {
|
||||
for (const node of options.proxyChain) {
|
||||
await validateHost(node.host);
|
||||
}
|
||||
}
|
||||
|
||||
const start = Date.now();
|
||||
|
||||
let socket: net.Socket | null = null;
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import crypto from "crypto";
|
||||
import { createRequire } from "module";
|
||||
import type { ConnectConfig, CipherAlgorithm } from "ssh2";
|
||||
|
||||
const nativeRequire = createRequire(import.meta.url);
|
||||
const availableCiphers = new Set(crypto.getCiphers());
|
||||
|
||||
// Maps SSH cipher names to their OpenSSL equivalents
|
||||
@@ -20,7 +22,7 @@ const SSH_CIPHER_SSL_NAME: Partial<Record<CipherAlgorithm, string>> = {
|
||||
// Check if ssh2's native crypto binding is available (needed for chacha20-poly1305)
|
||||
let ssh2BindingAvailable = false;
|
||||
try {
|
||||
require("ssh2/lib/protocol/crypto/build/Release/sshcrypto.node");
|
||||
nativeRequire("ssh2/lib/protocol/crypto/build/Release/sshcrypto.node");
|
||||
ssh2BindingAvailable = true;
|
||||
} catch {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
parseSSHKey,
|
||||
parsePublicKey,
|
||||
getFriendlyKeyTypeName,
|
||||
validateKeyPair,
|
||||
} from "./ssh-key-utils.js";
|
||||
|
||||
// A real OpenSSH ed25519 keypair generated solely for these tests. It grants no
|
||||
// access to anything and exists only so the ssh2 parsing path is exercised for
|
||||
// real rather than only via the text-fallback heuristics.
|
||||
const ED25519_PRIVATE = `-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||
QyNTUxOQAAACBR/hJLX7eMinS4wJMfG2gWSttUiuSLvqDwVYT53x0qewAAAJihJo4koSaO
|
||||
JAAAAAtzc2gtZWQyNTUxOQAAACBR/hJLX7eMinS4wJMfG2gWSttUiuSLvqDwVYT53x0qew
|
||||
AAAEDLo85Twyg0v6V1zsJaeRaxq9KPQXkqGY0HiJtVMzCXEFH+Ektft4yKdLjAkx8baBZK
|
||||
21SK5Iu+oPBVhPnfHSp7AAAAEHRlc3RAdGVybWl4LnRlc3QBAgMEBQ==
|
||||
-----END OPENSSH PRIVATE KEY-----`;
|
||||
|
||||
const ED25519_PUBLIC =
|
||||
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFH+Ektft4yKdLjAkx8baBZK21SK5Iu+oPBVhPnfHSp7 test@termix.test";
|
||||
|
||||
describe("parsePublicKey", () => {
|
||||
it("detects ssh-ed25519 public keys", () => {
|
||||
const info = parsePublicKey(ED25519_PUBLIC);
|
||||
expect(info.keyType).toBe("ssh-ed25519");
|
||||
expect(info.success).toBe(true);
|
||||
});
|
||||
|
||||
it("detects ssh-rsa public keys", () => {
|
||||
const info = parsePublicKey("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABFakeData");
|
||||
expect(info.keyType).toBe("ssh-rsa");
|
||||
expect(info.success).toBe(true);
|
||||
});
|
||||
|
||||
it("detects ecdsa public keys", () => {
|
||||
const info = parsePublicKey(
|
||||
"ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYData",
|
||||
);
|
||||
expect(info.keyType).toBe("ecdsa-sha2-nistp256");
|
||||
});
|
||||
|
||||
it("detects OpenSSH certificate types before plain types", () => {
|
||||
const info = parsePublicKey(
|
||||
"ssh-ed25519-cert-v01@openssh.com AAAAData comment",
|
||||
);
|
||||
expect(info.keyType).toBe("ssh-ed25519-cert-v01@openssh.com");
|
||||
});
|
||||
|
||||
it("returns unknown for unrecognized content", () => {
|
||||
const info = parsePublicKey("not-a-key");
|
||||
expect(info.keyType).toBe("unknown");
|
||||
expect(info.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseSSHKey", () => {
|
||||
it("parses a valid ed25519 private key and derives its type", () => {
|
||||
const info = parseSSHKey(ED25519_PRIVATE);
|
||||
expect(info.success).toBe(true);
|
||||
expect(info.keyType).toContain("ed25519");
|
||||
// ssh2 successfully derives the public key for a real OpenSSH key.
|
||||
expect(info.publicKey).toContain("ssh-ed25519");
|
||||
});
|
||||
|
||||
it("reports failure for garbage input", () => {
|
||||
const info = parseSSHKey("definitely not a key");
|
||||
expect(info.success).toBe(false);
|
||||
expect(info.keyType).toBe("unknown");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getFriendlyKeyTypeName", () => {
|
||||
it("maps known key types to friendly names", () => {
|
||||
expect(getFriendlyKeyTypeName("ssh-rsa")).toBe("RSA");
|
||||
expect(getFriendlyKeyTypeName("ssh-ed25519")).toBe("Ed25519");
|
||||
expect(getFriendlyKeyTypeName("ecdsa-sha2-nistp256")).toBe("ECDSA P-256");
|
||||
expect(getFriendlyKeyTypeName("ssh-dss")).toBe("DSA");
|
||||
});
|
||||
|
||||
it("passes unknown types through unchanged", () => {
|
||||
expect(getFriendlyKeyTypeName("some-future-type")).toBe("some-future-type");
|
||||
});
|
||||
});
|
||||
|
||||
describe("validateKeyPair", () => {
|
||||
it("validates a genuinely matching ed25519 key pair", () => {
|
||||
const result = validateKeyPair(ED25519_PRIVATE, ED25519_PUBLIC);
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.privateKeyType).toContain("ed25519");
|
||||
expect(result.publicKeyType).toBe("ssh-ed25519");
|
||||
});
|
||||
|
||||
it("fails when private and public key types mismatch", () => {
|
||||
const result = validateKeyPair(
|
||||
ED25519_PRIVATE,
|
||||
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABFakeData",
|
||||
);
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.error).toMatch(/mismatch|match/i);
|
||||
});
|
||||
|
||||
it("fails when the public key is invalid", () => {
|
||||
const result = validateKeyPair(ED25519_PRIVATE, "garbage");
|
||||
expect(result.isValid).toBe(false);
|
||||
});
|
||||
|
||||
it("fails when the private key is invalid", () => {
|
||||
const result = validateKeyPair(
|
||||
"garbage",
|
||||
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAData",
|
||||
);
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.error).toMatch(/private key/i);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,147 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import type { Request } from "express";
|
||||
import {
|
||||
detectPlatform,
|
||||
parseUserAgent,
|
||||
generateDeviceFingerprint,
|
||||
} from "./user-agent-parser.js";
|
||||
|
||||
function reqWith(headers: Record<string, string>): Request {
|
||||
return { headers } as unknown as Request;
|
||||
}
|
||||
|
||||
describe("detectPlatform", () => {
|
||||
it("detects desktop from the x-electron-app header", () => {
|
||||
expect(detectPlatform(reqWith({ "x-electron-app": "true" }))).toBe(
|
||||
"desktop",
|
||||
);
|
||||
});
|
||||
|
||||
it("detects desktop from a Termix-Desktop user agent", () => {
|
||||
expect(
|
||||
detectPlatform(reqWith({ "user-agent": "Termix-Desktop/1.0 (Windows)" })),
|
||||
).toBe("desktop");
|
||||
});
|
||||
|
||||
it("detects mobile from a Termix-Mobile user agent", () => {
|
||||
expect(
|
||||
detectPlatform(reqWith({ "user-agent": "Termix-Mobile/Android 1.0" })),
|
||||
).toBe("mobile");
|
||||
});
|
||||
|
||||
it("detects mobile phones/tablets", () => {
|
||||
expect(
|
||||
detectPlatform(reqWith({ "user-agent": "Mozilla/5.0 (iPhone; ...)" })),
|
||||
).toBe("mobile");
|
||||
});
|
||||
|
||||
it("treats Android-on-desktop-OS as web", () => {
|
||||
expect(
|
||||
detectPlatform(
|
||||
reqWith({ "user-agent": "Mozilla/5.0 (X11; Linux x86_64) Android" }),
|
||||
),
|
||||
).toBe("web");
|
||||
});
|
||||
|
||||
it("defaults to web for a desktop browser", () => {
|
||||
expect(
|
||||
detectPlatform(
|
||||
reqWith({
|
||||
"user-agent": "Mozilla/5.0 (Windows NT 10.0) Chrome/120.0",
|
||||
}),
|
||||
),
|
||||
).toBe("web");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseUserAgent", () => {
|
||||
it("parses a Chrome-on-Windows web client", () => {
|
||||
const info = parseUserAgent(
|
||||
reqWith({
|
||||
"user-agent":
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.6099.71 Safari/537.36",
|
||||
}),
|
||||
);
|
||||
expect(info.type).toBe("web");
|
||||
expect(info.browser).toBe("Chrome");
|
||||
expect(info.version).toBe("120.0");
|
||||
expect(info.os).toBe("Windows 10/11");
|
||||
});
|
||||
|
||||
it("parses Edge distinctly from Chrome", () => {
|
||||
const info = parseUserAgent(
|
||||
reqWith({
|
||||
"user-agent":
|
||||
"Mozilla/5.0 (Windows NT 10.0) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0",
|
||||
}),
|
||||
);
|
||||
expect(info.browser).toBe("Edge");
|
||||
});
|
||||
|
||||
it("parses a Termix desktop user agent", () => {
|
||||
const info = parseUserAgent(
|
||||
reqWith({ "user-agent": "Termix-Desktop/2.3.1 (macOS; arm64)" }),
|
||||
);
|
||||
expect(info.type).toBe("desktop");
|
||||
expect(info.browser).toBe("Termix Desktop");
|
||||
expect(info.version).toBe("2.3.1");
|
||||
expect(info.os).toBe("macOS");
|
||||
});
|
||||
|
||||
it("parses an iOS mobile user agent", () => {
|
||||
const info = parseUserAgent(
|
||||
reqWith({ "user-agent": "Termix-Mobile/iOS1.5 (OS 17_2)" }),
|
||||
);
|
||||
expect(info.type).toBe("mobile");
|
||||
expect(info.os).toContain("iOS");
|
||||
});
|
||||
});
|
||||
|
||||
describe("generateDeviceFingerprint", () => {
|
||||
it("is stable across minor browser version bumps on web", () => {
|
||||
const a = generateDeviceFingerprint({
|
||||
type: "web",
|
||||
browser: "Chrome",
|
||||
version: "120.5",
|
||||
os: "Windows 10/11",
|
||||
deviceInfo: "Chrome 120.5 on Windows 10/11",
|
||||
});
|
||||
const b = generateDeviceFingerprint({
|
||||
type: "web",
|
||||
browser: "Chrome",
|
||||
version: "120.9",
|
||||
os: "Windows 10/11",
|
||||
deviceInfo: "Chrome 120.9 on Windows 10/11",
|
||||
});
|
||||
expect(a).toBe(b);
|
||||
});
|
||||
|
||||
it("differs across major browser versions on web", () => {
|
||||
const a = generateDeviceFingerprint({
|
||||
type: "web",
|
||||
browser: "Chrome",
|
||||
version: "120.0",
|
||||
os: "Windows 10/11",
|
||||
deviceInfo: "",
|
||||
});
|
||||
const b = generateDeviceFingerprint({
|
||||
type: "web",
|
||||
browser: "Chrome",
|
||||
version: "121.0",
|
||||
os: "Windows 10/11",
|
||||
deviceInfo: "",
|
||||
});
|
||||
expect(a).not.toBe(b);
|
||||
});
|
||||
|
||||
it("produces a 64-char hex sha256 digest", () => {
|
||||
const fp = generateDeviceFingerprint({
|
||||
type: "desktop",
|
||||
browser: "Termix Desktop",
|
||||
version: "2.3.1",
|
||||
os: "macOS",
|
||||
deviceInfo: "",
|
||||
});
|
||||
expect(fp).toMatch(/^[0-9a-f]{64}$/);
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
fileManagerRecent,
|
||||
fileManagerPinned,
|
||||
fileManagerShortcuts,
|
||||
transferRecent,
|
||||
dismissedAlerts,
|
||||
} from "../database/db/schema.js";
|
||||
import { eq } from "drizzle-orm";
|
||||
@@ -24,6 +25,7 @@ interface UserExportData {
|
||||
recent: unknown[];
|
||||
pinned: unknown[];
|
||||
shortcuts: unknown[];
|
||||
transferRecent: unknown[];
|
||||
};
|
||||
dismissedAlerts: unknown[];
|
||||
};
|
||||
@@ -102,20 +104,25 @@ class UserDataExport {
|
||||
: credentials;
|
||||
}
|
||||
|
||||
const [recentFiles, pinnedFiles, shortcuts] = await Promise.all([
|
||||
getDb()
|
||||
.select()
|
||||
.from(fileManagerRecent)
|
||||
.where(eq(fileManagerRecent.userId, userId)),
|
||||
getDb()
|
||||
.select()
|
||||
.from(fileManagerPinned)
|
||||
.where(eq(fileManagerPinned.userId, userId)),
|
||||
getDb()
|
||||
.select()
|
||||
.from(fileManagerShortcuts)
|
||||
.where(eq(fileManagerShortcuts.userId, userId)),
|
||||
]);
|
||||
const [recentFiles, pinnedFiles, shortcuts, transferRecentData] =
|
||||
await Promise.all([
|
||||
getDb()
|
||||
.select()
|
||||
.from(fileManagerRecent)
|
||||
.where(eq(fileManagerRecent.userId, userId)),
|
||||
getDb()
|
||||
.select()
|
||||
.from(fileManagerPinned)
|
||||
.where(eq(fileManagerPinned.userId, userId)),
|
||||
getDb()
|
||||
.select()
|
||||
.from(fileManagerShortcuts)
|
||||
.where(eq(fileManagerShortcuts.userId, userId)),
|
||||
getDb()
|
||||
.select()
|
||||
.from(transferRecent)
|
||||
.where(eq(transferRecent.userId, userId)),
|
||||
]);
|
||||
|
||||
const alerts = await getDb()
|
||||
.select()
|
||||
@@ -134,6 +141,7 @@ class UserDataExport {
|
||||
recent: recentFiles,
|
||||
pinned: pinnedFiles,
|
||||
shortcuts: shortcuts,
|
||||
transferRecent: transferRecentData,
|
||||
},
|
||||
dismissedAlerts: alerts,
|
||||
},
|
||||
@@ -144,6 +152,7 @@ class UserDataExport {
|
||||
recentFiles.length +
|
||||
pinnedFiles.length +
|
||||
shortcuts.length +
|
||||
transferRecentData.length +
|
||||
alerts.length,
|
||||
encrypted: format === "encrypted",
|
||||
exportType: scope,
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { isValidMac, buildMagicPacket } from "./wake-on-lan.js";
|
||||
|
||||
describe("isValidMac", () => {
|
||||
it("accepts colon-separated MAC addresses", () => {
|
||||
expect(isValidMac("01:23:45:67:89:AB")).toBe(true);
|
||||
expect(isValidMac("aa:bb:cc:dd:ee:ff")).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts hyphen-separated MAC addresses", () => {
|
||||
expect(isValidMac("01-23-45-67-89-AB")).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects malformed MAC addresses", () => {
|
||||
expect(isValidMac("")).toBe(false);
|
||||
expect(isValidMac("01:23:45:67:89")).toBe(false);
|
||||
expect(isValidMac("01:23:45:67:89:AB:CD")).toBe(false);
|
||||
expect(isValidMac("0123456789AB")).toBe(false);
|
||||
expect(isValidMac("zz:23:45:67:89:ab")).toBe(false);
|
||||
expect(isValidMac("01:23:45:67:89:AB ")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildMagicPacket", () => {
|
||||
it("produces a 102-byte packet", () => {
|
||||
const packet = buildMagicPacket("01:23:45:67:89:AB");
|
||||
expect(packet.length).toBe(102);
|
||||
});
|
||||
|
||||
it("starts with six 0xFF bytes", () => {
|
||||
const packet = buildMagicPacket("01:23:45:67:89:AB");
|
||||
expect([...packet.subarray(0, 6)]).toEqual([
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
]);
|
||||
});
|
||||
|
||||
it("repeats the MAC bytes 16 times after the header", () => {
|
||||
const packet = buildMagicPacket("01:23:45:67:89:AB");
|
||||
const mac = Buffer.from([0x01, 0x23, 0x45, 0x67, 0x89, 0xab]);
|
||||
for (let i = 0; i < 16; i++) {
|
||||
const offset = 6 + i * 6;
|
||||
expect([...packet.subarray(offset, offset + 6)]).toEqual([...mac]);
|
||||
}
|
||||
});
|
||||
|
||||
it("treats colon and hyphen separators identically", () => {
|
||||
const colon = buildMagicPacket("aa:bb:cc:dd:ee:ff");
|
||||
const hyphen = buildMagicPacket("aa-bb-cc-dd-ee-ff");
|
||||
expect(colon.equals(hyphen)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -6,7 +6,7 @@ function parseMac(mac: string): Buffer {
|
||||
return Buffer.from(mac.replace(/[:-]/g, ""), "hex");
|
||||
}
|
||||
|
||||
function buildMagicPacket(mac: string): Buffer {
|
||||
export function buildMagicPacket(mac: string): Buffer {
|
||||
const macBytes = parseMac(mac);
|
||||
const packet = Buffer.alloc(102);
|
||||
packet.fill(0xff, 0, 6);
|
||||
|
||||
Reference in New Issue
Block a user