mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-08-29 18:31:33 +00:00
release-2.7.1 (#1296)
* Add Helm and GitOps deployment setup * fix: build better-sqlite3 from source in Docker (#1267) * fix: preserve runtime SSL settings (#1268) * fix: support forwarding from the memory SSH agent (#1269) * fix: support forwarding from the memory agent * style: format memory agent test * fix: prompt for encrypted SFTP key passphrases (#1270) * fix: prompt for SFTP key passphrases * style: format SSH key utility test * fix: include host context in automation notifications (#1271) * fix: include host context in automation notifications * style: format automation notification changes * fix: reserve sidebar height for host tags (#1272) * fix: keep host action rows stable at large font sizes (#1273) * fix: honor certificate setting during server probe (#1274) * fix: package standard Linux icon sizes (#1275) * fix: avoid duplicate Docker HTTPS listener (#1276) * Fix host status without metrics collection (#1277) * fix: allow eight-digit secure auth codes (#1263) Allow TOTP prompts to accept secure auth codes longer than six digits without blocking valid authentication attempts. Generated with Codebuff 🤖 Co-authored-by: Chetan <chetan.development@gmail.com> Co-authored-by: Codebuff <noreply@codebuff.com> * Harden Helm deployment defaults * Update Helm workflow action * Exclude Helm templates from Prettier * Fix browser RDP file drops (#1279) * Fix Proxmox guest credential usernames (#1280) * Add WSL local terminal option (#1281) * refactor: split the transfer engine into focused modules (#1282) * refactor: extract SFTP promisify helpers into sftp-promisify module * refactor: extract transfer timing and rate stats into transfer-stats module * refactor: extract transfer error classes and recovery checks into transfer-errors module * refactor: extract host/path utility helpers into transfer-host-utils module * refactor: extract SFTP directory tree helpers into transfer-sftp-dir module * refactor: extract segment copy job builder into transfer-segment-copy module * refactor: extract file scan and sample helpers into transfer-scan module * refactor: move throttled progress helper into transfer-stats module * style: format transfer modules * perf: optimize tmux monitor aggregation (#1283) * fix: reserve credential tag row height (#1284) * feat: edit AI provider model settings (#1285) * fix: clarify click-to-expand host setting (#1286) * fix: allow portable imports on remote databases (#1287) * fix: allow HTTPS to share the configured port (#1288) * fix: resolve synced jump hosts on the server (#1289) * fix: make terminal clipboard shortcuts layout independent (#1290) * fix: use compatible fetch dispatcher for Tailscale (#1291) * fix: add OIDC environment recovery override (#1292) * fix: coalesce rapid mobile terminal input (#1293) * fix: coalesce rapid mobile terminal input * fix: support clean xterm patch installs * fix: resolve synced remote desktop host IDs (#1295) * feat: make the SFTP file manager path bar editable (#1294) Co-authored-by: Maxime Bonillo <257463937+dropafterfree@users.noreply.github.com> Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com> * feat: add passkey sign in to the login screen * fix: remove rounded corners from the host list search bar * fix: stop image storage settings text wrapping to one word per line * fix: prevent malformed websocket messages from crashing the server * chore: increment version * fix: remove gaps between host rows in the sidebar list Keep sub-pixel row measurements and stop wiping the size cache on hover. * fix: Failed to connect through jump hosts (#1180) https://github.com/Termix-SSH/Support/issues/1180 * feat: Progress bar for file downloads in the file manager (#1158) https://github.com/Termix-SSH/Support/issues/1158 * feat: Allow setting Silent OIDC Login via ENV var (#1174) https://github.com/Termix-SSH/Support/issues/1174 * feat: `IdentityFile` to limit the number of attempts by agents (#1165) https://github.com/Termix-SSH/Support/issues/1165 * feat: Credentials clone (#1159) https://github.com/Termix-SSH/Support/issues/1159 * chore: update release notes * docs: move helm setup guide to the docs site * fix: type errors in FilteredAgent agent identity handling * fix: remove stale better-sqlite3 prebuilds so the source build is used * fix: actually build better-sqlite3 from source so arm64 docker images work * fix: credential edit pencil in host editor and add clone action to credential list * fix: clear editingHost so the credential pencil actually opens the editor * chore: run format and lint * fix: folder drag and drop upload failing in the file manager * chore: sync Crowdin translations for 2.7.1 --------- Co-authored-by: alex-ctms <alex-ctms@users.noreply.github.com> Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com> Co-authored-by: Chetan Kumar <74929596+ckloop@users.noreply.github.com> Co-authored-by: Chetan <chetan.development@gmail.com> Co-authored-by: Codebuff <noreply@codebuff.com> Co-authored-by: ZacharyZcR <payasonorahc@protonmail.com> Co-authored-by: dropafterfree <maxime.bonillo@gmail.com> Co-authored-by: Maxime Bonillo <257463937+dropafterfree@users.noreply.github.com>
This commit is contained in:
co-authored by
Chetan
Codebuff
Maxime Bonillo
ZacharyZcR
alex-ctms
Chetan Kumar
ZacharyZcR
dropafterfree
parent
566b908daf
commit
76fd9eedbf
@@ -47,6 +47,12 @@ const repository = {
|
||||
}),
|
||||
};
|
||||
|
||||
const resolveHostById = vi.fn();
|
||||
|
||||
vi.mock("../../hosts/host-resolver.js", () => ({
|
||||
resolveHostById: (...args: unknown[]) => resolveHostById(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../database/repositories/factory.js", () => ({
|
||||
createCurrentAutomationRepository: () => repository,
|
||||
}));
|
||||
@@ -93,12 +99,41 @@ beforeEach(() => {
|
||||
nextRunId = 1;
|
||||
nextStepRowId = 1;
|
||||
vi.clearAllMocks();
|
||||
resolveHostById.mockResolvedValue(null);
|
||||
executeStep.mockResolvedValue({ success: true, output: "ok" });
|
||||
// The singleton carries in-flight state between tests.
|
||||
(AutomationEngine as unknown as { instance?: unknown }).instance = undefined;
|
||||
});
|
||||
|
||||
describe("AutomationEngine.run", () => {
|
||||
it("adds the trigger host name to the template context", async () => {
|
||||
defineAutomation([step({ id: "notify", type: "notify" })]);
|
||||
resolveHostById.mockResolvedValue({
|
||||
name: "Proxmox Node",
|
||||
ip: "10.0.0.11",
|
||||
username: "root",
|
||||
port: 22,
|
||||
});
|
||||
|
||||
await AutomationEngine.getInstance().run({
|
||||
automationId: 1,
|
||||
triggerType: "metric_threshold",
|
||||
triggerHostId: 11,
|
||||
triggerContext: { hostId: 11, value: 97 },
|
||||
});
|
||||
|
||||
const context = executeStep.mock.calls[0][1] as {
|
||||
template: {
|
||||
host: { id: number; name: string };
|
||||
trigger: { hostName: string };
|
||||
};
|
||||
};
|
||||
expect(context.template.host).toMatchObject({
|
||||
id: 11,
|
||||
name: "Proxmox Node",
|
||||
});
|
||||
expect(context.template.trigger.hostName).toBe("Proxmox Node");
|
||||
});
|
||||
it("runs steps in order and records each one", async () => {
|
||||
defineAutomation([
|
||||
step({ id: "a", type: "run_command" }),
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const automationFetch = vi.fn();
|
||||
|
||||
vi.mock("../../automations/http.js", () => ({
|
||||
automationFetch: (...args: unknown[]) => automationFetch(...args),
|
||||
}));
|
||||
|
||||
const { sendAutomationNotification } =
|
||||
await import("../../automations/notify.js");
|
||||
|
||||
beforeEach(() => {
|
||||
automationFetch.mockReset();
|
||||
automationFetch.mockResolvedValue({ ok: true });
|
||||
});
|
||||
|
||||
describe("sendAutomationNotification", () => {
|
||||
it("keeps alert-compatible host and rule fields in webhook payloads", async () => {
|
||||
await sendAutomationNotification(
|
||||
{ id: 1, type: "webhook", config: '{"url":"https://example.com"}' },
|
||||
{
|
||||
title: "CPU warning",
|
||||
body: "cpu.percent is at 97",
|
||||
severity: "warning",
|
||||
context: {
|
||||
host: { id: 11, name: "Proxmox Node" },
|
||||
trigger: { value: 97, threshold: 90 },
|
||||
run: { automationId: 42 },
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const options = automationFetch.mock.calls[0][1] as RequestInit;
|
||||
expect(JSON.parse(options.body as string)).toMatchObject({
|
||||
hostName: "Proxmox Node",
|
||||
hostId: 11,
|
||||
ruleName: "CPU warning",
|
||||
ruleId: 42,
|
||||
value: 97,
|
||||
threshold: 90,
|
||||
message: "cpu.percent is at 97",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,8 @@
|
||||
import { sql } from "drizzle-orm";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { HostRepository } from "../../../database/repositories/host-repository.js";
|
||||
import { DataCrypto } from "../../../utils/data-crypto.js";
|
||||
|
||||
describe("HostRepository.reorderForUser", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
@@ -72,3 +73,100 @@ describe("HostRepository.reorderForUser", () => {
|
||||
await expect(repo.reorderForUser("user-1", [])).resolves.toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("HostRepository Proxmox sync inserts", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
vi.restoreAllMocks();
|
||||
await adapter?.close();
|
||||
adapter = null;
|
||||
});
|
||||
|
||||
it("creates a discovered guest using the scheduled-sync payload", async () => {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
await adapter.exec(`
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash');
|
||||
INSERT INTO ssh_credentials (id, user_id, name, auth_type, username)
|
||||
VALUES (7, 'user-1', 'guest key', 'key', 'alice');
|
||||
`);
|
||||
const repository = new HostRepository(context);
|
||||
const now = new Date().toISOString();
|
||||
vi.spyOn(DataCrypto, "validateUserAccess").mockReturnValue(
|
||||
Buffer.alloc(32, 1),
|
||||
);
|
||||
|
||||
const created = await repository.createEncryptedForUser("user-1", {
|
||||
userId: "user-1",
|
||||
name: "guest",
|
||||
ip: "10.0.0.8",
|
||||
port: 22,
|
||||
username: "",
|
||||
connectionType: "ssh",
|
||||
folder: "Proxmox",
|
||||
tags: "proxmox,qemu,node-1,vm-100",
|
||||
proxmoxConfig: JSON.stringify({
|
||||
source: {
|
||||
source: "proxmox",
|
||||
sourceHostId: 1,
|
||||
node: "node-1",
|
||||
vmid: 100,
|
||||
type: "qemu",
|
||||
},
|
||||
}),
|
||||
updatedAt: now,
|
||||
createdAt: now,
|
||||
pin: false,
|
||||
authType: "credential",
|
||||
credentialId: 7,
|
||||
overrideCredentialUsername: 0,
|
||||
password: null,
|
||||
key: null,
|
||||
keyPassword: null,
|
||||
keyType: null,
|
||||
enableTerminal: true,
|
||||
enableFileManager: true,
|
||||
enableTunnel: true,
|
||||
enableDocker: false,
|
||||
enableSsh: true,
|
||||
enableRdp: false,
|
||||
rdpUser: null,
|
||||
rdpPassword: null,
|
||||
rdpDomain: null,
|
||||
rdpSecurity: null,
|
||||
rdpIgnoreCert: 0,
|
||||
rdpPort: null,
|
||||
vncUser: null,
|
||||
vncPassword: null,
|
||||
vncPort: null,
|
||||
telnetUser: null,
|
||||
telnetPassword: null,
|
||||
telnetPort: null,
|
||||
defaultPath: "/",
|
||||
tunnelConnections: "[]",
|
||||
jumpHosts: null,
|
||||
quickActions: null,
|
||||
statsConfig: null,
|
||||
dockerConfig: null,
|
||||
terminalConfig: null,
|
||||
forceKeyboardInteractive: "false",
|
||||
useSocks5: 0,
|
||||
socks5Host: null,
|
||||
socks5Port: null,
|
||||
socks5Username: null,
|
||||
socks5Password: null,
|
||||
socks5ProxyChain: null,
|
||||
portKnockSequence: null,
|
||||
showTerminalInSidebar: 0,
|
||||
showFileManagerInSidebar: 0,
|
||||
showTunnelInSidebar: 0,
|
||||
showDockerInSidebar: 0,
|
||||
showServerStatsInSidebar: 0,
|
||||
});
|
||||
|
||||
expect(created.username).toBe("");
|
||||
expect(created.credentialId).toBe(7);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const factory = vi.hoisted(() => ({
|
||||
getCurrentRepositorySqlite: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../../database/repositories/factory.js", () => factory);
|
||||
|
||||
import {
|
||||
withCurrentSqliteForeignKeysDisabled,
|
||||
withSqliteForeignKeysDisabled,
|
||||
} from "../../../database/repositories/sqlite-foreign-keys.js";
|
||||
|
||||
const previousDatabaseDialect = process.env.DATABASE_DIALECT;
|
||||
|
||||
afterEach(() => {
|
||||
if (previousDatabaseDialect === undefined)
|
||||
delete process.env.DATABASE_DIALECT;
|
||||
else process.env.DATABASE_DIALECT = previousDatabaseDialect;
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("withSqliteForeignKeysDisabled", () => {
|
||||
it("restores foreign keys after an import", async () => {
|
||||
const sqlite = { exec: vi.fn() };
|
||||
|
||||
await expect(
|
||||
withSqliteForeignKeysDisabled(sqlite, async () => "imported"),
|
||||
).resolves.toBe("imported");
|
||||
expect(sqlite.exec.mock.calls).toEqual([
|
||||
["PRAGMA foreign_keys = OFF"],
|
||||
["PRAGMA foreign_keys = ON"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("withCurrentSqliteForeignKeysDisabled", () => {
|
||||
it.each(["postgres", "mysql"])(
|
||||
"runs portable imports with constraints enabled on %s",
|
||||
async (dialect) => {
|
||||
process.env.DATABASE_DIALECT = dialect;
|
||||
const operation = vi.fn().mockResolvedValue("imported");
|
||||
|
||||
await expect(
|
||||
withCurrentSqliteForeignKeysDisabled(operation),
|
||||
).resolves.toBe("imported");
|
||||
expect(operation).toHaveBeenCalledOnce();
|
||||
expect(factory.getCurrentRepositorySqlite).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -9,7 +9,7 @@ describe("resolveProxmoxImportAuth", () => {
|
||||
expect(resolveProxmoxImportAuth("key", 7)).toEqual({
|
||||
authType: "credential",
|
||||
credentialId: 7,
|
||||
overrideCredentialUsername: 1,
|
||||
overrideCredentialUsername: 0,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -17,7 +17,7 @@ describe("resolveProxmoxImportAuth", () => {
|
||||
expect(resolveProxmoxImportAuth("password", 7)).toEqual({
|
||||
authType: "credential",
|
||||
credentialId: 7,
|
||||
overrideCredentialUsername: 1,
|
||||
overrideCredentialUsername: 0,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -35,7 +35,7 @@ describe("resolveProxmoxImportAuth", () => {
|
||||
expect(resolveProxmoxImportAuth(undefined, 42)).toEqual({
|
||||
authType: "credential",
|
||||
credentialId: 42,
|
||||
overrideCredentialUsername: 1,
|
||||
overrideCredentialUsername: 0,
|
||||
});
|
||||
expect(resolveProxmoxImportAuth(undefined, null)).toEqual({
|
||||
authType: "none",
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("../../../utils/auth-manager.js", () => ({
|
||||
AuthManager: {
|
||||
getInstance: () => ({ createAdminMiddleware: vi.fn() }),
|
||||
},
|
||||
}));
|
||||
|
||||
const { isValidOidcIssuer } =
|
||||
await import("../../../database/routes/sso-provider-routes.js");
|
||||
|
||||
describe("isValidOidcIssuer", () => {
|
||||
it("rejects userinfo endpoints used as issuer URLs", () => {
|
||||
expect(
|
||||
isValidOidcIssuer("https://auth.example/application/o/userinfo/"),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts an Authentik application issuer", () => {
|
||||
expect(isValidOidcIssuer("https://auth.example/application/o/termix")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -21,6 +21,7 @@ const {
|
||||
resolveOidcMappedRoles,
|
||||
verifyOIDCToken,
|
||||
describeFetchFailure,
|
||||
isOIDCEnvOverrideEnabled,
|
||||
} = await import("../../../database/routes/user-oidc-utils.js");
|
||||
|
||||
const BACKCHANNEL_LOGOUT_EVENT =
|
||||
@@ -281,6 +282,7 @@ describe("getOIDCConfigFromEnv", () => {
|
||||
"OIDC_SCOPES",
|
||||
"OIDC_ALLOWED_USERS",
|
||||
"OIDC_ADMIN_GROUP",
|
||||
"OIDC_ENV_OVERRIDE",
|
||||
];
|
||||
const saved: Record<string, string | undefined> = {};
|
||||
|
||||
@@ -334,6 +336,12 @@ describe("getOIDCConfigFromEnv", () => {
|
||||
expect(config?.identifier_path).toBe("email");
|
||||
expect(config?.scopes).toBe("openid");
|
||||
});
|
||||
|
||||
it("only enables database recovery override when explicitly requested", () => {
|
||||
expect(isOIDCEnvOverrideEnabled()).toBe(false);
|
||||
process.env.OIDC_ENV_OVERRIDE = "true";
|
||||
expect(isOIDCEnvOverrideEnabled()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractOidcGroups", () => {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { createRequire } from "node:module";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { resolveLocalShell } =
|
||||
require("../../../../electron/local-shell.cjs") as {
|
||||
resolveLocalShell: (
|
||||
platform: NodeJS.Platform,
|
||||
requestedShell?: string,
|
||||
env?: NodeJS.ProcessEnv,
|
||||
) => { file: string; args: string[] };
|
||||
};
|
||||
|
||||
describe("resolveLocalShell", () => {
|
||||
it("starts the default WSL distribution without PowerShell arguments", () => {
|
||||
expect(resolveLocalShell("win32", "wsl", {})).toEqual({
|
||||
file: "wsl.exe",
|
||||
args: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps PowerShell as the default Windows shell", () => {
|
||||
expect(resolveLocalShell("win32", "default", {})).toEqual({
|
||||
file: "powershell.exe",
|
||||
args: ["-NoLogo"],
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the configured shell on non-Windows platforms", () => {
|
||||
expect(resolveLocalShell("linux", "wsl", { SHELL: "/bin/fish" })).toEqual({
|
||||
file: "/bin/fish",
|
||||
args: ["-l"],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,6 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { generateKeyPairSync } from "crypto";
|
||||
import ssh2Pkg, { type ParsedKey } from "ssh2";
|
||||
|
||||
const mockAccess = vi.fn();
|
||||
|
||||
@@ -6,7 +8,57 @@ vi.mock("fs/promises", () => ({
|
||||
access: mockAccess,
|
||||
}));
|
||||
|
||||
import { resolveAgentSocket } from "../../hosts/terminal-auth-helpers.js";
|
||||
import {
|
||||
MemoryAgent,
|
||||
FilteredAgent,
|
||||
resolveAgentSocket,
|
||||
} from "../../hosts/terminal-auth-helpers.js";
|
||||
|
||||
describe("MemoryAgent", () => {
|
||||
it("serves identities and signatures over the agent protocol", async () => {
|
||||
const { privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
|
||||
const parsed = ssh2Pkg.utils.parseKey(
|
||||
privateKey.export({ type: "pkcs1", format: "pem" }),
|
||||
);
|
||||
expect(parsed).not.toBeInstanceOf(Error);
|
||||
|
||||
const agent = new MemoryAgent(parsed as ParsedKey);
|
||||
const stream = await new Promise<NodeJS.ReadWriteStream>(
|
||||
(resolve, reject) => {
|
||||
agent.getStream((error, result) => {
|
||||
if (error || !result)
|
||||
reject(error ?? new Error("Missing agent stream"));
|
||||
else resolve(result);
|
||||
});
|
||||
},
|
||||
);
|
||||
const client = new ssh2Pkg.AgentProtocol(true);
|
||||
client.pipe(stream).pipe(client);
|
||||
|
||||
const identities = await new Promise<ParsedKey[]>((resolve, reject) => {
|
||||
client.getIdentities((error, keys) => {
|
||||
if (error || !keys) reject(error ?? new Error("Missing identities"));
|
||||
else resolve(keys);
|
||||
});
|
||||
});
|
||||
expect(identities).toHaveLength(1);
|
||||
expect(identities[0].getPublicSSH()).toEqual(
|
||||
(parsed as ParsedKey).getPublicSSH(),
|
||||
);
|
||||
|
||||
const data = Buffer.from("forwarded-agent-test");
|
||||
const signature = await new Promise<Buffer>((resolve, reject) => {
|
||||
client.sign(identities[0], data, (error, result) => {
|
||||
if (error || !result) reject(error ?? new Error("Missing signature"));
|
||||
else resolve(result);
|
||||
});
|
||||
});
|
||||
expect((parsed as ParsedKey).verify(data, signature)).toBe(true);
|
||||
|
||||
client.destroy();
|
||||
stream.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAgentSocket", () => {
|
||||
const originalEnv = process.env.SSH_AUTH_SOCK;
|
||||
@@ -101,3 +153,78 @@ describe("resolveAgentSocket", () => {
|
||||
expect(mockAccess).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("FilteredAgent", () => {
|
||||
it("only returns identities matching the configured public key", async () => {
|
||||
const { privateKey: keyA } = generateKeyPairSync("rsa", {
|
||||
modulusLength: 2048,
|
||||
});
|
||||
const { privateKey: keyB } = generateKeyPairSync("rsa", {
|
||||
modulusLength: 2048,
|
||||
});
|
||||
const parsedA = ssh2Pkg.utils.parseKey(
|
||||
keyA.export({ type: "pkcs1", format: "pem" }),
|
||||
) as ParsedKey;
|
||||
const parsedB = ssh2Pkg.utils.parseKey(
|
||||
keyB.export({ type: "pkcs1", format: "pem" }),
|
||||
) as ParsedKey;
|
||||
|
||||
const inner = {
|
||||
getIdentities: (cb: (err: Error | null, keys: ParsedKey[]) => void) =>
|
||||
cb(null, [parsedA, parsedB]),
|
||||
getStream: vi.fn(),
|
||||
sign: vi.fn(),
|
||||
};
|
||||
|
||||
const filtered = new FilteredAgent(
|
||||
inner as unknown as ConstructorParameters<typeof FilteredAgent>[0],
|
||||
parsedB.getPublicSSH(),
|
||||
);
|
||||
|
||||
const identities = await new Promise<ParsedKey[]>((resolve, reject) => {
|
||||
filtered.getIdentities((err, keys) => {
|
||||
if (err || !keys) reject(err ?? new Error("Missing identities"));
|
||||
else resolve(keys);
|
||||
});
|
||||
});
|
||||
|
||||
expect(identities).toHaveLength(1);
|
||||
expect(identities[0].getPublicSSH()).toEqual(parsedB.getPublicSSH());
|
||||
});
|
||||
|
||||
it("returns no identities when nothing matches", async () => {
|
||||
const { privateKey: keyA } = generateKeyPairSync("rsa", {
|
||||
modulusLength: 2048,
|
||||
});
|
||||
const { privateKey: keyB } = generateKeyPairSync("rsa", {
|
||||
modulusLength: 2048,
|
||||
});
|
||||
const parsedA = ssh2Pkg.utils.parseKey(
|
||||
keyA.export({ type: "pkcs1", format: "pem" }),
|
||||
) as ParsedKey;
|
||||
const parsedB = ssh2Pkg.utils.parseKey(
|
||||
keyB.export({ type: "pkcs1", format: "pem" }),
|
||||
) as ParsedKey;
|
||||
|
||||
const inner = {
|
||||
getIdentities: (cb: (err: Error | null, keys: ParsedKey[]) => void) =>
|
||||
cb(null, [parsedA]),
|
||||
getStream: vi.fn(),
|
||||
sign: vi.fn(),
|
||||
};
|
||||
|
||||
const filtered = new FilteredAgent(
|
||||
inner as unknown as ConstructorParameters<typeof FilteredAgent>[0],
|
||||
parsedB.getPublicSSH(),
|
||||
);
|
||||
|
||||
const identities = await new Promise<ParsedKey[]>((resolve, reject) => {
|
||||
filtered.getIdentities((err, keys) => {
|
||||
if (err || !keys) reject(err ?? new Error("Missing identities"));
|
||||
else resolve(keys);
|
||||
});
|
||||
});
|
||||
|
||||
expect(identities).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
HostAddressMismatchError,
|
||||
HostNotOnThisServerError,
|
||||
normalizeHostAddress,
|
||||
resolveServerJumpHosts,
|
||||
} from "../../../hosts/terminal/host-identity.js";
|
||||
|
||||
/**
|
||||
@@ -59,6 +60,20 @@ describe("hostAddressMismatch", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveServerJumpHosts", () => {
|
||||
it("uses server-side ids for a sync-delegated connection", () => {
|
||||
expect(
|
||||
resolveServerJumpHosts([{ hostId: 7 }], [{ hostId: 42 }], "host-sync-id"),
|
||||
).toEqual([{ hostId: 42 }]);
|
||||
});
|
||||
|
||||
it("keeps client ids for a local id-based connection", () => {
|
||||
expect(resolveServerJumpHosts([{ hostId: 7 }], [{ hostId: 42 }])).toEqual([
|
||||
{ hostId: 7 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("HostAddressMismatchError", () => {
|
||||
it("survives the catch blocks that swallow resolution failures", () => {
|
||||
// SFTP host resolution sits inside "failed to resolve credentials, carry
|
||||
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
buildPaneMetrics,
|
||||
attachPanesToWindows,
|
||||
shellEscape,
|
||||
type ProcessInfo,
|
||||
type TmuxWindow,
|
||||
} from "../../../hosts/tmux/monitor-helpers.js";
|
||||
|
||||
function join(...fields: (string | number)[]): string {
|
||||
@@ -194,6 +196,28 @@ describe("buildPaneMetrics", () => {
|
||||
const metrics = buildPaneMetrics(pane, cyclic, new Map());
|
||||
expect(metrics[0].processCount).toBe(2);
|
||||
});
|
||||
|
||||
it("aggregates a wide process tree without dropping children", () => {
|
||||
const childCount = 2_000;
|
||||
const wideTree: ProcessInfo[] = [
|
||||
{ pid: 1, ppid: 0, cpu: 0, mem: 0, rss: 1, comm: "bash" },
|
||||
...Array.from({ length: childCount }, (_, index) => ({
|
||||
pid: index + 2,
|
||||
ppid: 1,
|
||||
cpu: 0.1,
|
||||
mem: 0,
|
||||
rss: 1,
|
||||
comm: `worker-${index}`,
|
||||
})),
|
||||
];
|
||||
const pane = parsePanes(
|
||||
join("wide", 0, "%1", 0, 1, 1, 80, 24, "bash", "/", "t"),
|
||||
);
|
||||
|
||||
const [metrics] = buildPaneMetrics(pane, wideTree, new Map());
|
||||
expect(metrics.processCount).toBe(childCount + 1);
|
||||
expect(metrics.memRssKb).toBe(childCount + 1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("attachPanesToWindows", () => {
|
||||
@@ -214,6 +238,29 @@ describe("attachPanesToWindows", () => {
|
||||
expect(windows.get("s1")![0].panes[0].id).toBe("%1");
|
||||
expect(windows.get("s1")![1].panes[0].id).toBe("%2");
|
||||
});
|
||||
|
||||
it("preserves first-match behavior for duplicate window indexes", () => {
|
||||
const first: TmuxWindow = {
|
||||
index: 0,
|
||||
name: "first",
|
||||
active: true,
|
||||
panes: [],
|
||||
};
|
||||
const duplicate: TmuxWindow = {
|
||||
index: 0,
|
||||
name: "duplicate",
|
||||
active: false,
|
||||
panes: [],
|
||||
};
|
||||
const windows = new Map([["s1", [first, duplicate]]]);
|
||||
const panes = parsePanes(
|
||||
join("s1", 0, "%1", 0, 100, 1, 80, 24, "bash", "/", "t"),
|
||||
);
|
||||
|
||||
attachPanesToWindows(windows, panes);
|
||||
expect(first.panes).toHaveLength(1);
|
||||
expect(duplicate.panes).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shellEscape", () => {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { createServer } from "node:http";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { fetchWithProxy } from "../../utils/proxy-agent.js";
|
||||
|
||||
describe("fetchWithProxy", () => {
|
||||
const savedProxies = {
|
||||
HTTP_PROXY: process.env.HTTP_PROXY,
|
||||
HTTPS_PROXY: process.env.HTTPS_PROXY,
|
||||
http_proxy: process.env.http_proxy,
|
||||
https_proxy: process.env.https_proxy,
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
for (const [name, value] of Object.entries(savedProxies)) {
|
||||
if (value === undefined) delete process.env[name];
|
||||
else process.env[name] = value;
|
||||
}
|
||||
});
|
||||
|
||||
it("uses a dispatcher compatible with the selected fetch implementation", async () => {
|
||||
delete process.env.HTTP_PROXY;
|
||||
delete process.env.HTTPS_PROXY;
|
||||
delete process.env.http_proxy;
|
||||
delete process.env.https_proxy;
|
||||
const server = createServer((_request, response) => response.end("ok"));
|
||||
await new Promise<void>((resolve) =>
|
||||
server.listen(0, "127.0.0.1", resolve),
|
||||
);
|
||||
|
||||
try {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("No port");
|
||||
const response = await fetchWithProxy(`http://127.0.0.1:${address.port}`);
|
||||
expect(await response.text()).toBe("ok");
|
||||
} finally {
|
||||
await new Promise<void>((resolve, reject) =>
|
||||
server.close((error) => (error ? reject(error) : resolve())),
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
parseSSHKey,
|
||||
parsePublicKey,
|
||||
preparePrivateKeyForSSH2,
|
||||
isPrivateKeyPassphraseError,
|
||||
getFriendlyKeyTypeName,
|
||||
validateKeyPair,
|
||||
} from "../../utils/ssh-key-utils.js";
|
||||
@@ -97,6 +98,22 @@ describe("parseSSHKey", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("isPrivateKeyPassphraseError", () => {
|
||||
it("recognizes missing and incorrect passphrase errors", () => {
|
||||
expect(
|
||||
isPrivateKeyPassphraseError(
|
||||
new Error(
|
||||
"Encrypted OpenSSH private key detected, but no passphrase given",
|
||||
),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(isPrivateKeyPassphraseError(new Error("Bad passphrase"))).toBe(true);
|
||||
expect(
|
||||
isPrivateKeyPassphraseError(new Error("Unsupported key format")),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getFriendlyKeyTypeName", () => {
|
||||
it("maps known key types to friendly names", () => {
|
||||
expect(getFriendlyKeyTypeName("ssh-rsa")).toBe("RSA");
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
parseWsMessage,
|
||||
asObject,
|
||||
asString,
|
||||
toTerminalDimension,
|
||||
WsMessageError,
|
||||
} from "../../utils/ws-message.js";
|
||||
|
||||
const frame = (s: string) => Buffer.from(s, "utf8");
|
||||
|
||||
describe("parseWsMessage", () => {
|
||||
it("parses a well-formed message", () => {
|
||||
expect(parseWsMessage(frame('{"type":"ping"}'))).toEqual({
|
||||
type: "ping",
|
||||
data: undefined,
|
||||
});
|
||||
expect(parseWsMessage(frame('{"type":"input","data":"ls"}'))).toEqual({
|
||||
type: "input",
|
||||
data: "ls",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects JSON that parses but cannot be destructured", () => {
|
||||
// The original DoS: JSON.parse("null") succeeds, so it escaped the
|
||||
// try/catch and threw a TypeError on destructure.
|
||||
for (const payload of ["null", "123", '"str"', "[1,2]", "true"]) {
|
||||
expect(() => parseWsMessage(frame(payload))).toThrow(WsMessageError);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects invalid JSON", () => {
|
||||
expect(() => parseWsMessage(frame("{oops"))).toThrow(WsMessageError);
|
||||
expect(() => parseWsMessage(frame(""))).toThrow(WsMessageError);
|
||||
});
|
||||
|
||||
it("rejects a missing or non-string type", () => {
|
||||
expect(() => parseWsMessage(frame("{}"))).toThrow(WsMessageError);
|
||||
expect(() => parseWsMessage(frame('{"type":5}'))).toThrow(WsMessageError);
|
||||
expect(() => parseWsMessage(frame('{"type":null}'))).toThrow(
|
||||
WsMessageError,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects oversized frames", () => {
|
||||
const huge = Buffer.alloc(1024 * 1024 + 1, 0x20);
|
||||
expect(() => parseWsMessage(huge)).toThrow(WsMessageError);
|
||||
});
|
||||
|
||||
it("never throws a TypeError for any malformed input", () => {
|
||||
const payloads = [
|
||||
"null",
|
||||
"0",
|
||||
"[]",
|
||||
"{}",
|
||||
'{"type":{}}',
|
||||
'{"data":"x"}',
|
||||
"undefined",
|
||||
'{"type":"a","data":null}',
|
||||
];
|
||||
for (const p of payloads) {
|
||||
try {
|
||||
parseWsMessage(frame(p));
|
||||
} catch (e) {
|
||||
expect(e).toBeInstanceOf(WsMessageError);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("asObject / asString", () => {
|
||||
it("narrows without throwing", () => {
|
||||
expect(asObject({ a: 1 })).toEqual({ a: 1 });
|
||||
expect(asObject(null)).toEqual({});
|
||||
expect(asObject([1])).toEqual({});
|
||||
expect(asObject("x")).toEqual({});
|
||||
expect(asString("x")).toBe("x");
|
||||
expect(asString(5)).toBe("");
|
||||
expect(asString(undefined)).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("toTerminalDimension", () => {
|
||||
it("accepts sane values", () => {
|
||||
expect(toTerminalDimension(80)).toBe(80);
|
||||
expect(toTerminalDimension("120")).toBe(120);
|
||||
expect(toTerminalDimension(24.7)).toBe(24);
|
||||
});
|
||||
|
||||
it("rejects values that would poison setWindow", () => {
|
||||
for (const bad of [0, -1, NaN, Infinity, null, undefined, "abc", {}]) {
|
||||
expect(toTerminalDimension(bad)).toBe(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("clamps absurdly large values", () => {
|
||||
expect(toTerminalDimension(1e9)).toBe(10000);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user