Files
Netcatty/domain/terminalHostResolution.ts
T
陈大猫 2bf8611919 feat(local-terminal): support optional startup command on local terminal hosts (#4326)
* feat(local-terminal): support optional startup command on local terminal hosts

* fix(local-terminal): validate saved local launch target before overlaying startup command
2026-11-25 10:26:36 +08:00

239 lines
8.4 KiB
TypeScript

import type { GroupConfig, Host, ProxyProfile, TerminalSession } from "./models";
import { applyGroupDefaults, resolveGroupDefaults } from "./groupConfig";
import { materializeHostProxyProfile } from "./proxyProfiles";
import { sanitizePluginConnection } from "./pluginConnection";
import { resolveHostDefaultLocalShell, type ResolveDefaultLocalShellContext } from "./localShellHost";
import { canServeAsSshJumpHost } from "./terminalProtocol";
type LocalOs = Host["os"];
interface ResolveEffectiveHostOptions {
host: Host;
groupConfigs: GroupConfig[];
proxyProfiles: ProxyProfile[];
validProxyProfileIds?: ReadonlySet<string>;
/** When provided, saved local hosts with no shell resolve the Settings shell. */
defaultLocalShell?: ResolveDefaultLocalShellContext;
}
interface ResolveTerminalSessionHostOptions {
session: TerminalSession;
hosts: Host[];
groupConfigs: GroupConfig[];
proxyProfiles: ProxyProfile[];
localOs: LocalOs;
/** When provided, saved local hosts with no shell resolve the Settings shell. */
defaultLocalShell?: ResolveDefaultLocalShellContext;
}
interface ResolveTerminalChainHostsOptions {
host: Host | null | undefined;
hosts: Host[];
groupConfigs: GroupConfig[];
proxyProfiles: ProxyProfile[];
validProxyProfileIds?: ReadonlySet<string>;
}
const resolveSerialBackspaceBehavior = (
serialConfig: Host["serialConfig"],
): Host["backspaceBehavior"] | null => {
if (serialConfig?.backspaceBehavior === "ctrl-h") return "ctrl-h";
if (serialConfig?.backspaceBehavior === "default") return undefined;
return null;
};
export function resolveEffectiveTerminalHost({
host,
groupConfigs,
proxyProfiles,
validProxyProfileIds = new Set(proxyProfiles.map((profile) => profile.id)),
defaultLocalShell,
}: ResolveEffectiveHostOptions): Host {
const groupDefaults = host.group
? resolveGroupDefaults(host.group, groupConfigs, { validProxyProfileIds })
: {};
const effectiveHost = materializeHostProxyProfile(
applyGroupDefaults(host, groupDefaults, { validProxyProfileIds }),
proxyProfiles,
);
return defaultLocalShell
? resolveHostDefaultLocalShell(effectiveHost, defaultLocalShell)
: effectiveHost;
}
const suppressDeviceTypeForShellTransport = (host: Host): Host => {
if (!host.moshEnabled && !host.etEnabled) return host;
if (host.deviceType === undefined) return host;
return { ...host, deviceType: undefined };
};
function buildFallbackHostFromSession(
session: TerminalSession,
localOs: LocalOs,
): Host {
const fallbackProtocol = session.protocol ?? "ssh";
return {
id: session.hostId,
label: session.hostLabel || "Local Terminal",
hostname: session.hostname || "localhost",
username: session.username || (fallbackProtocol === "serial" ? "" : "local"),
port: session.port ?? 22,
os: fallbackProtocol === "local" ? localOs : "linux",
group: "",
tags: [],
protocol: fallbackProtocol,
pluginConnection: sanitizePluginConnection(session.pluginConnection, fallbackProtocol),
moshEnabled: session.moshEnabled,
etEnabled: session.etEnabled,
charset: session.charset,
serialConfig: session.serialConfig,
backspaceBehavior: session.serialConfig?.backspaceBehavior === "ctrl-h" ? "ctrl-h" : undefined,
localShell: session.localShell,
localShellArgs: session.localShellArgs,
localShellName: session.localShellName,
localShellIcon: session.localShellIcon,
localStartDir: session.localStartDir,
};
}
const sameLocalShellArgs = (
left: string[] | undefined,
right: string[] | undefined,
): boolean => {
const normalizedLeft = left?.length ? left : undefined;
const normalizedRight = right?.length ? right : undefined;
if (!normalizedLeft && !normalizedRight) return true;
if (!normalizedLeft || !normalizedRight || normalizedLeft.length !== normalizedRight.length) {
return false;
}
return normalizedLeft.every((arg, index) => arg === normalizedRight[index]);
};
const matchesSavedLocalLaunchTarget = (
savedHost: Host,
overlaid: Pick<Host, "localShell" | "localShellArgs" | "localStartDir">,
): boolean => (
savedHost.protocol === "local"
&& (overlaid.localShell ?? "") === (savedHost.localShell ?? "")
&& sameLocalShellArgs(overlaid.localShellArgs, savedHost.localShellArgs)
&& (overlaid.localStartDir || "~") === (savedHost.localStartDir || "~")
);
// A local session carries a shell snapshot (shell path, args, name, icon,
// start dir) captured at launch time; the saved host may have been edited
// since. Popup/clone flows must relaunch the session's shell, not the host's
// current one, so overlay the snapshot onto the resolved host. When the saved
// host now targets a different protocol, shell, args, or start directory, drop
// its startup command so a command authored for the edited target cannot run
// inside the old session.
const overlaySessionLocalShell = (
session: TerminalSession,
host: Host,
savedHost: Host,
): Host => {
if (session.protocol !== "local") return host;
const localShell = session.localShell ?? host.localShell;
const localShellArgs = session.localShellArgs ?? host.localShellArgs;
const localStartDir = session.localStartDir ?? host.localStartDir;
const keepsSavedStartupCommand = matchesSavedLocalLaunchTarget(savedHost, {
localShell,
localShellArgs,
localStartDir,
});
return {
...host,
username: session.username,
localShell,
localShellArgs,
localShellName: session.localShellName ?? host.localShellName,
localShellIcon: session.localShellIcon ?? host.localShellIcon,
localStartDir,
...(keepsSavedStartupCommand
? {}
: { startupCommand: undefined, startupCommandRunMode: undefined }),
};
};
export function resolveTerminalSessionHost({
session,
hosts,
groupConfigs,
proxyProfiles,
localOs,
defaultLocalShell,
}: ResolveTerminalSessionHostOptions): Host {
const vaultHost = hosts.find((host) => host.id === session.hostId);
if (!vaultHost) return buildFallbackHostFromSession(session, localOs);
const existingHost = resolveEffectiveTerminalHost({
host: vaultHost,
groupConfigs,
proxyProfiles,
defaultLocalShell,
});
const protocol = session.protocol ?? existingHost.protocol;
const pluginConnection = sanitizePluginConnection(session.pluginConnection, protocol)
?? sanitizePluginConnection(existingHost.pluginConnection, protocol);
const port = session.port ?? existingHost.port;
const moshEnabled = session.moshEnabled ?? existingHost.moshEnabled;
const etEnabled = session.etEnabled ?? existingHost.etEnabled;
const sessionSerialBackspace = resolveSerialBackspaceBehavior(session.serialConfig);
const hostSerialBackspace = resolveSerialBackspaceBehavior(existingHost.serialConfig);
const backspaceBehavior = protocol === "serial"
? sessionSerialBackspace !== null
? sessionSerialBackspace
: hostSerialBackspace !== null
? hostSerialBackspace
: existingHost.backspaceBehavior
: existingHost.backspaceBehavior;
if (
protocol === existingHost.protocol &&
port === existingHost.port &&
moshEnabled === existingHost.moshEnabled &&
etEnabled === existingHost.etEnabled &&
JSON.stringify(pluginConnection) === JSON.stringify(existingHost.pluginConnection) &&
backspaceBehavior === existingHost.backspaceBehavior
) {
return suppressDeviceTypeForShellTransport(
overlaySessionLocalShell(session, existingHost, existingHost),
);
}
return suppressDeviceTypeForShellTransport(overlaySessionLocalShell(session, {
...existingHost,
protocol,
port,
moshEnabled,
etEnabled,
pluginConnection,
backspaceBehavior,
}, existingHost));
}
export function resolveTerminalChainHosts({
host,
hosts,
groupConfigs,
proxyProfiles,
validProxyProfileIds = new Set(proxyProfiles.map((profile) => profile.id)),
}: ResolveTerminalChainHostsOptions): Host[] {
if (!host?.hostChain?.hostIds?.length) return [];
const hostMap = new Map(hosts.map((candidate) => [candidate.id, candidate]));
return host.hostChain.hostIds
.map((hostId) => {
const chainHost = hostMap.get(hostId);
// Jump hops are dialed over SSH; skip local/serial/telnet/plugin entries
// that can never serve as a ProxyJump hop (e.g. saved local shells).
if (!chainHost || !canServeAsSshJumpHost(chainHost)) return undefined;
return resolveEffectiveTerminalHost({
host: chainHost,
groupConfigs,
proxyProfiles,
validProxyProfileIds,
});
})
.filter((value): value is Host => Boolean(value));
}