mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-20 23:20:46 +00:00
* fix(ssh): per-host skipEcdsaHostKey toggle + advanced algorithm overrides (#1027) #1027 reported an old Huawei S7706 (SSH banner `SSH-2.0--`, empty software-version field) where the legacy-algorithms toggle still couldn't get a connection through. The debug log shows the handshake makes it through every negotiation step, picks `ecdsa-sha2-nistp521` for the host key, then dies at: Handshake failed: signature verification failed i.e. ssh2's strict RFC verifier rejects the ECDSA signature the switch produces. OpenSSH on the same machine connects because its known_hosts is already pinned to an RSA fingerprint, so it never advertises ECDSA in the first place. This adds two layers of escape hatch: A. `host.skipEcdsaHostKey` (one-click) — drops every `ecdsa-sha2-*` from the offered host-key list. Forces the fallback to ssh-rsa / ssh-dss / ssh-ed25519 that those old stacks implement correctly. Wired through ssh / sftp / port-forwarding bridges, inheritable from the group default. B. `host.algorithms` (advanced) — per-category override lists (`kex`, `cipher`, `hmac`, `serverHostKey`, `compress`). When a category's array is non-empty, it fully replaces the negotiated list for that category. Exposed in a collapsible "Advanced algorithm overrides" panel on both host and group settings, inspired by Tabby's per-profile algorithm UI. Empty arrays normalize to "use default" so picking zero algorithms in a category doesn't bench the connection with "no matching algorithm". Overrides apply BEFORE `skipEcdsaHostKey` so the latter stays an unconditional kill switch even if the user explicitly puts `ecdsa-*` back into the host-key list. Behavior with default values (neither toggle set, no override list) is identical to before — zero change for hosts that aren't opted in. Tests cover the new options on both `buildAlgorithms` and `buildSftpAlgorithms`, plus group→host inheritance for both fields. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(ssh): address Codex review on #1116 — proper seed + jump-host carry + missing call sites Four review findings from the Codex pass on #1116, all real: 1. AlgorithmOverridesPanel was seeding the first customization in a category from `SUPPORTED_ALGORITHMS_BY_CATEGORY`, which contains legacy algorithms (CBC, arcfour, MD5, ssh-dss, group1-sha1...). Unchecking a single modern algorithm in a host that had legacy mode *off* would silently start offering those legacy algorithms. Now seeds from `effectiveDefaultAlgorithms(legacyEnabled)`, mirroring what `buildAlgorithms` actually emits at connect time. - New `effectiveDefaultAlgorithms` pure helper in `domain/sshAlgorithmList.ts` with its own test suite (also asserts the modern subset contains no SHA-1 KEX / CBC / arcfour / MD5) - `AlgorithmOverridesPanel` takes a `legacyEnabled` prop - `isChecked` now reflects the effective-default state for an untouched category, so unchecked rows visually represent algorithms the connection wouldn't currently advertise 2. The chain-mode jump-host loop in `sshBridge.cjs` was applying the target host's `skipEcdsaHostKey` / `algorithmOverrides` to every bastion hop, which is wrong when the bastion has its own settings. This was actually a pre-existing issue with `legacyAlgorithms` too — `NetcattyJumpHost` simply didn't carry any of these fields. - `NetcattyJumpHost` gains `legacyAlgorithms`, `skipEcdsaHostKey`, `algorithmOverrides` - `createTerminalSessionStarters` populates them from each jump host's own configuration - The jump-host bridge call now reads `jump.* ?? options.*` so a hop with its own setting wins, but unset hops still fall back to the target's settings (preserves historic chain-wide behavior when nothing is overridden) 3. `infrastructure/services/portForwardingService.ts` only forwarded `legacyAlgorithms` to the port-forwarding bridge, so a host that needed the ECDSA skip or advanced overrides could connect through the terminal but its auto-start tunnels would still hit the original handshake failure. - Forward `skipEcdsaHostKey` and `algorithmOverrides` at the target call site and at the jump-host map. 4. `application/state/sftp/useSftpHostCredentials.ts` built `NetcattySSHOptions` for `openSftp` without any of the algorithm fields — and on inspection it didn't even forward `legacyAlgorithms` to begin with, so SFTP panes for legacy-mode hosts were silently negotiating with the modern default list. Same gap at the jump-host map. - Forward all three fields at both the target and the jump-host map. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * polish(hosts): make the advanced-algorithm collapsible trigger a real button The first cut used a plain underlined caption for the "Advanced algorithm overrides" collapsible trigger. That blends into the surrounding helper text and doesn't read as an interactive control — users couldn't tell that the per-category checkbox editor was reachable at all. Match the project's existing collapsible-trigger pattern (see `SerialConnectModal`): full-width ghost Button, label on the left, ChevronDown / ChevronUp on the right that flips with open state, controlled via `useState`. Applied in both `HostDetailsPanel` and `GroupDetailsPanel`. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * polish(hosts): rename Legacy Algorithms card to SSH Algorithms; split Backspace into its own section The card now carries three algorithm controls (Allow Legacy / Skip ECDSA / Advanced overrides) plus a Backspace Behavior dropdown that doesn't belong with the rest. Two cleanups: 1. Rename the card from "Legacy Algorithms" to "SSH Algorithms". The original title only described the first toggle; the section now covers the whole algorithm-negotiation surface, including the ECDSA host-key skip and the per-category override editor. - i18n key renamed `hostDetails.section.legacyAlgorithms` -> `hostDetails.section.sshAlgorithms` in zh-CN / en / ru - `HostDetailsPanel` references the new key 2. Move the Backspace Behavior control out of the algorithm card. - `HostDetailsPanel`: new dedicated "Terminal Behavior" card (TerminalSquare icon) placed between SSH Algorithms and Keepalive. New i18n key `hostDetails.section.terminalBehavior`. - `GroupDetailsPanel`: no separate Card scaffolding for group defaults — moved Backspace to the bottom of the SSH section (after Mosh) so it visually separates from the algorithm block above without introducing a new card heading. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(sftp): per-hop algorithm settings in SFTP chain (Codex review on #1116) `sshBridge.cjs`'s jump loop already reads `jump.* ?? options.*` for the three algorithm fields, but `sftpBridge.cjs#connectThroughChainForSftp` was missed in that change and still applied the target host's `options.legacyAlgorithms` / `skipEcdsaHostKey` / `algorithmOverrides` to every bastion. A bastion that needed the ECDSA skip or a custom algorithm list while the target didn't would still fail the SFTP handshake before reaching the target. Mirror the sshBridge fix: read each setting from the jump host first, falling back to the target options when the hop didn't override. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(ssh): keychain SSH exec + advanced editor seed honor inherited algorithm settings Two findings from a local Codex review pass on the branch: 1. The keychain "export public key to host" flow opens its own one-off SSH connection through `sshBridge#execCommand`, but the connectOpts built there didn't include any `algorithms`. ssh2 then negotiated with its built-in modern defaults regardless of what the host had set, so a host that needs the ECDSA skip (or legacy mode) would connect in the terminal but the keychain export would fail with the original signature-verification error. - `sshBridge.cjs#execCommand` now sets `algorithms` from `payload.legacyAlgorithms` / `skipEcdsaHostKey` / `algorithmOverrides`, mirroring `startSSHSession`. - `useKeychainBackend`'s `execCommand` typing gets the three new optional fields. - `KeychainManager` forwards the host's `legacyAlgorithms`, `skipEcdsaHostKey`, and `algorithms` when invoking the export. 2. The Advanced Algorithm Overrides editor seeded its first customization from `form.legacyAlgorithms`, which is the host's own field — it doesn't reflect a value the host *inherits* from its group's default. A user in a group with `legacyAlgorithms=true` editing a host that hadn't explicitly set the flag would see the editor seed in modern-only mode, and saving could silently drop the legacy algorithms the host actually needed. - `HostDetailsPanel` passes `form.legacyAlgorithms ?? groupDefaults?.legacyAlgorithms`. - `GroupDetailsPanel` adds an `inheritedLegacyAlgorithms` memo resolved from the parent group chain via `resolveGroupDefaults`, and the editor uses `form.legacyAlgorithms ?? inheritedLegacyAlgorithms`. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(keychain): export-public-key honors group-inherited algorithm settings Second-pass Codex review on PR #1116 flagged that the keychain "export public key to host" flow now carries the three algorithm fields end-to-end, but only reads them from `exportHost.*` directly — which doesn't reflect values the host inherits from its group's defaults. A host that left `legacyAlgorithms` / `skipEcdsaHostKey` / `algorithms` unset but sat inside a group that turned them on would work fine in the terminal (the terminal starter applies group defaults before sending the IPC payload) but its keychain export would silently fall back to ssh2's modern defaults and hit the original signature-verification failure. Resolve the effective host with `applyGroupDefaults` + `resolveGroupDefaults` before the `execCommand` call, then read the algorithm fields off the effective host. Requires plumbing `groupConfigs` into `KeychainManager` (added as an optional prop, forwarded by `VaultView`). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(host-details): algorithm-overrides editor reads currently selected group's defaults Third-pass Codex review caught that the editor seed was reading from the `groupDefaults` prop, which is whatever group the host belonged to when the panel opened. If a user switched the host into a different group inside the panel and then opened the Advanced Algorithm Overrides collapsible before saving, the editor would seed from the old group's `legacyAlgorithms` flag and could save the wrong list. The panel already memoizes `effectiveGroupDefaults` from `form.group`/`defaultGroup`/`groupConfigs` for exactly this kind of re-resolution (used by theme/font effective lookups). Read the inherited flag from there instead of the stale prop. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(algorithms): trim UI cipher list to algorithms ssh2 actually supports Fourth-pass Codex review flagged that `SUPPORTED_CIPHER_ALGORITHMS` included `blowfish-cbc`, `cast128-cbc`, and the `arcfour*` family, but OpenSSL 3 disabled those primitives, so ssh2's `canUseCipher` filter drops them from `SUPPORTED_CIPHER` at startup. Selecting any of them in the Advanced Algorithm Overrides editor would make `ssh2.Client.connect()` throw `Unsupported algorithm` synchronously, turning the override into a "host now unreachable" footgun instead of a narrowing knob. Realigned each `SUPPORTED_*_ALGORITHMS` list to ssh2's actual `SUPPORTED_*` constants: - `SUPPORTED_CIPHER_ALGORITHMS`: dropped blowfish / cast128 / arcfour; added the no-suffix `aes128-gcm` / `aes256-gcm` variants ssh2 also accepts. - `SUPPORTED_KEX_ALGORITHMS`: added `diffie-hellman-group15-sha512` and `diffie-hellman-group17-sha512` (present in ssh2 but missing from the UI list); reordered to ssh2's canonical order. - `SUPPORTED_HMAC_ALGORITHMS`: reordered so the ETM/SHA-2 grouping matches ssh2's `DEFAULT_MAC` and lookups are predictable. Locked the invariant in `sshAlgorithmList.test.ts` with a new test that asserts every UI-offered algorithm is a member of ssh2's `SUPPORTED_*` for its category. A future ssh2 bump that drops an algorithm we still expose will fail this test instead of silently becoming a connect-time error for users. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(algorithms): run KEX override through the runtime fixed-DH filter Codex round-N flagged a gap in `applyAlgorithmOverrides`: when the user supplies a custom KEX list via the advanced editor, the previous implementation copied it verbatim into the negotiated `algorithms.kex` field. The default builder already passes its KEX list through `filterSupportedFixedDhKex` to drop fixed-DH groups the runtime doesn't support (notably `diffie-hellman-group1-sha1` on Electron/BoringSSL, which lacks modp2), but the override path bypassed that filter — so an Electron user enabling legacy mode and saving any KEX checkbox state would re-advertise group1-sha1 and the handshake would crash with "Unknown DH group" instead of failing fast. Apply the same `filterSupportedFixedDhKex` to the override list. New test in `sshAlgorithms.test.cjs` exercises a simulated BoringSSL runtime that lacks modp2 and asserts the override-filtered KEX no longer includes group1-sha1, while group14-sha1 / group-exchange-sha1 remain. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(algorithms): run HMAC override through the FIPS MD5 filter Codex flagged the same runtime-bypass pattern Round-N-1 fixed for KEX, now in HMAC: `applyLegacyHmacAlgorithms` gates `hmac-md5` behind `md5Supported()` so FIPS Node builds don't get it, but the UI's `effectiveDefaultAlgorithms(true)` seed adds `hmac-md5` / `hmac-md5-96` unconditionally. A user with legacy mode on who saves any HMAC checkbox change would push those MD5 entries through `applyAlgorithmOverrides`, which previously copied the override verbatim — bypassing the FIPS gate and making ssh2 throw "Unsupported algorithm" before negotiation. New `filterRuntimeUnsupportedHmac` helper applies the same `md5Supported()` gate to a user override. `applyAlgorithmOverrides` routes the HMAC override through it (mirrors how the same function already routes KEX overrides through `filterSupportedFixedDhKex`). New test simulates a FIPS-disabled MD5 runtime and asserts MD5 variants drop from the final HMAC list while SHA-1 / SHA-2 entries remain. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(ssh): jump-host overrides no longer inherit the leaf's algorithm overrides Codex flagged that the jump-loop fallback I added for chain convenience applied the target's per-host \`algorithmOverrides\` to every bastion whose own override wasn't set, which is wrong: a target restricted to e.g. \`serverHostKey: [\"ssh-rsa\"]\` would lock the hop to ssh-rsa too and break negotiation against an Ed25519-only bastion. The fallback IS still correct for \`legacyAlgorithms\` and \`skipEcdsaHostKey\` — those are append/safety toggles that widen the offered list, so propagating them to a bastion is safe and matches the historic chain-wide behavior of \`options.legacyAlgorithms\` (single-toggle convenience for a chain with one old leaf). Treat \`algorithmOverrides\` strictly per-host instead. Same change in both \`sshBridge.cjs\` and \`sftpBridge.cjs\` jump loops, with a comment block explaining the asymmetry so a future refactor doesn't "clean up" the distinction. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * ui(host-details): surface inherited algorithm overrides in the advanced editor Codex flagged a real gap in the inheritance model: when a parent group has set algorithm overrides (e.g. \`algorithms.kex: [...]\`), a host or child group under it can't simply Reset a category back to NetCatty's defaults — \`applyGroupDefaults\` treats an unset host field as "inherit", so the local Reset falls back to the group's list rather than to ssh2's defaults. Cleanly distinguishing "reset to NetCatty defaults" from "inherit from group" needs a new schema field or sentinel, which is a non-trivial design change well beyond the scope of this PR. For now, surface the situation in the UI so the user understands why Reset doesn't behave the way they might expect and where to go to actually clear the restriction: - \`AlgorithmOverridesPanel\` accepts an optional \`inheritedFromGroup\` prop and, when populated, renders a blue inline notice listing the inherited categories and directing the user to the group's algorithm settings if they need to opt out. - \`HostDetailsPanel\` passes \`effectiveGroupDefaults?.algorithms\`. - \`GroupDetailsPanel\` adds a new \`inheritedAlgorithmOverrides\` memo that resolves the same way the existing \`inheritedLegacyAlgorithms\` does, and forwards it. - i18n strings added in zh-CN / en / ru. Follow-up (out of scope for this PR): if real users do hit this, introduce a \`host.algorithms = null\` (or explicit \`algorithmsOverride: boolean\`) sentinel and a Reset-to-defaults button that uses it. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(ssh): jump-host skipEcdsaHostKey is per-host; panel seeds from inherited overrides Three findings from the latest Codex pass: 1 & 2. `skipEcdsaHostKey` on the leaf was still falling back onto jump hosts in both `sshBridge.cjs` and `sftpBridge.cjs`. I had classified it with `legacyAlgorithms` as a "safety widening" knob, but Codex is right that it actually *narrows* the offered host-key list by dropping every `ecdsa-sha2-*`. An ECDSA-only bastion (or one where the operator pinned ECDSA via known_hosts) would still negotiate when ECDSA is offered, but fails when the leaf's skip is propagated to it. Same fix as `algorithmOverrides` last round: strictly per-host. Only `legacyAlgorithms` keeps the chain-wide fallback (append-only — it widens the offer, can never break a hop that wasn't already failing). 3. `AlgorithmOverridesPanel` was seeding the first customization of a category from the NetCatty/legacy effective default, ignoring any list the host inherits from its group for OTHER categories. Because `applyGroupDefaults` treats `host.algorithms` as an all-or-nothing inherit boundary, the moment the user saved any host-local override `{ cipher: [...] }`, the group's `{ serverHostKey: ["ssh-rsa"] }` restriction silently dropped from the effective host. Now: - `toggleAlgorithm`'s first-click seed reads `inheritedFromGroup?.[category] ?? effectiveDefault[category]`, so customizing one category preserves the group's narrowing on the others. - `updateCategory` initializes `next` from `{ ...inheritedFromGroup, ...value }` so saved overrides carry the inherited categories alongside the host's own edits. - `isChecked` reflects the inherited list when there's no local value, so the visible checkbox state matches what would actually be advertised. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(host-details): Reset preserves the inherited list instead of silently widening Codex caught a follow-on bug from the previous "carry inheritance" fix: pressing Reset on a category that's inherited from the group deleted that category from \`host.algorithms\` while other host-local or carried-inherited categories remained. Because \`applyGroupDefaults\` treats \`host.algorithms\` as all-or-nothing, the moment any host-local entry exists the group's \`algorithms\` object stops being inherited as a whole — so the freshly-deleted category fell back to NetCatty defaults rather than the group's narrower list. Effective result: Reset on an inherited category *widened* the offer instead of restoring it. Reset now persists the inherited list verbatim onto the host when the group has an override for that category, so "Reset" means "use what this host would otherwise inherit" in all cases. Also tightened \`isCustomized\` to suppress the "customized" badge (and the per-category Reset button) when the host's stored list is identical to the inherited list — those rows haven't really been customized by the user. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * ui(host-details): gate the inherited-notice / checkbox baseline on no host override Codex caught the asymmetry between the read and write sides of the panel. The write side (`updateCategory`, `toggleAlgorithm`, Reset) intentionally carries `inheritedFromGroup` onto the host on the first edit so the runtime's all-or-nothing inherit boundary in `applyGroupDefaults` doesn't silently widen the offer. But the read side (the inherited-notice banner and the `isChecked` baseline for unfilled categories) was applying inherited values *unconditionally* — including when the host already had any local `algorithms` object, which makes `applyGroupDefaults` stop inheriting from the group as a whole. Net effect on a host that only locally overrode `cipher`: the UI claimed the group's `serverHostKey` restriction was still in effect, while the runtime would actually use NetCatty's modern defaults for that category. Introduce `inheritedForDisplay`, defined as `value === undefined ? inheritedFromGroup : undefined`, and route the notice + the `isChecked` baseline through it. The write side keeps consulting the unconditional `inheritedFromGroup` so the carry-over still happens on first edit — that part is what makes the runtime behavior match what the UI used to advertise. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * ui(host-details): legacy/skipEcdsa toggles reflect group-inherited value Codex caught that the Skip ECDSA toggle in both the host and group panels read `form.skipEcdsaHostKey` directly, so a host whose group turned the flag on (and `applyGroupDefaults` therefore applied it to the runtime SSH negotiation) still saw the toggle rendered as off. Worse, clicking it computed `!form.skipEcdsaHostKey` — which is `!undefined` = `true` — so the first click could not actually disable the inherited setting on a per-host basis; it would just store `true` explicitly, the same effective state. The Allow Legacy Algorithms toggle had the same pre-existing issue. Fix both at once: each toggle now derives its enabled state from `form.<field> ?? <inherited>` and the onToggle handler flips that same effective value, so the toggle accurately represents what the runtime would do and a single click off correctly stores `false` (which `applyGroupDefaults` then leaves alone, breaking inheritance for this host). - `HostDetailsPanel` reads from `effectiveGroupDefaults`. - `GroupDetailsPanel` adds an `inheritedSkipEcdsaHostKey` memo alongside the existing `inheritedLegacyAlgorithms` and uses both. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1419 lines
54 KiB
TypeScript
1419 lines
54 KiB
TypeScript
import type { FitAddon } from "@xterm/addon-fit";
|
|
import type { SerializeAddon } from "@xterm/addon-serialize";
|
|
import type { Terminal as XTerm } from "@xterm/xterm";
|
|
import type { Dispatch, RefObject, SetStateAction } from "react";
|
|
import { shouldScrollOnTerminalOutput } from "../../../domain/terminalScroll";
|
|
import { logger } from "../../../lib/logger";
|
|
import type { Host, Identity, KnownHost, SerialConfig, SSHKey, TerminalSession, TerminalSettings } from "../../../types";
|
|
import {
|
|
isEncryptedCredentialPlaceholder,
|
|
sanitizeCredentialValue,
|
|
} from "../../../domain/credentials";
|
|
import { resolveHostAuth } from "../../../domain/sshAuth";
|
|
import {
|
|
detectVendorFromSshVersion,
|
|
resolveHostKeepalive,
|
|
resolveTelnetPassword,
|
|
resolveTelnetPort,
|
|
resolveTelnetUsername,
|
|
} from "../../../domain/host";
|
|
import {
|
|
clearPasteResidualAfterTerminalWrite,
|
|
prepareTerminalDataForUserPasteDisplay,
|
|
} from "./terminalUserPaste";
|
|
import {
|
|
markPromptLineBreakCommandPending,
|
|
prepareTerminalDataForPromptLineBreak,
|
|
syncPromptLineBreakState,
|
|
type PromptLineBreakState,
|
|
} from "./promptLineBreak";
|
|
import { createOutputFlowController, type OutputFlowController } from "./outputFlowController";
|
|
|
|
/**
|
|
* Per-connection token for stale-timer detection. The renderer reuses the
|
|
* same sessionId across reconnects within a tab, so comparing sessionIds
|
|
* cannot distinguish "the current attempt" from "a previous attempt on
|
|
* the same slot". We assign each startSSH call a fresh token object and
|
|
* store it in this module-local map, keyed by sessionId. A timer that
|
|
* was scheduled under an older token will see a different value here and
|
|
* bail out. The map entry for a sessionId is overwritten on each new
|
|
* connect and stays around until the app exits — since there is only one
|
|
* entry per active session, the memory cost is negligible.
|
|
*/
|
|
const connectionTokensBySessionId = new Map<string, object>();
|
|
|
|
const isConnectionTokenCurrent = (sessionId: string, token: object): boolean =>
|
|
connectionTokensBySessionId.get(sessionId) === token;
|
|
|
|
type TerminalBackendApi = {
|
|
backendAvailable: () => boolean;
|
|
telnetAvailable: () => boolean;
|
|
moshAvailable: () => boolean;
|
|
localAvailable: () => boolean;
|
|
serialAvailable: () => boolean;
|
|
execAvailable: () => boolean;
|
|
startSSHSession: (options: NetcattySSHOptions) => Promise<string>;
|
|
startTelnetSession: (
|
|
options: Parameters<NonNullable<NetcattyBridge["startTelnetSession"]>>[0],
|
|
) => Promise<string>;
|
|
startMoshSession: (
|
|
options: Parameters<NonNullable<NetcattyBridge["startMoshSession"]>>[0],
|
|
) => Promise<string>;
|
|
startLocalSession: (
|
|
options: Parameters<NonNullable<NetcattyBridge["startLocalSession"]>>[0],
|
|
) => Promise<string>;
|
|
startSerialSession: (
|
|
options: Parameters<NonNullable<NetcattyBridge["startSerialSession"]>>[0],
|
|
) => Promise<string>;
|
|
execCommand: (options: Parameters<NetcattyBridge["execCommand"]>[0]) => Promise<{
|
|
stdout?: string;
|
|
stderr?: string;
|
|
}>;
|
|
getSessionRemoteInfo?: (sessionId: string) => Promise<{
|
|
success: boolean;
|
|
remoteSshVersion?: string;
|
|
error?: string;
|
|
}>;
|
|
getSessionDistroInfo?: (sessionId: string) => Promise<{
|
|
success: boolean;
|
|
stdout?: string;
|
|
stderr?: string;
|
|
error?: string;
|
|
}>;
|
|
onSessionData: (sessionId: string, cb: (data: string) => void) => () => void;
|
|
onSessionExit: (
|
|
sessionId: string,
|
|
cb: (evt: { exitCode?: number; signal?: number; error?: string; reason?: "exited" | "error" | "timeout" | "closed" }) => void,
|
|
) => () => void;
|
|
onTelnetAutoLoginComplete?: (
|
|
sessionId: string,
|
|
cb: (evt: { sessionId: string }) => void,
|
|
) => (() => void) | undefined;
|
|
onTelnetAutoLoginCancelled?: (
|
|
sessionId: string,
|
|
cb: (evt: { sessionId: string }) => void,
|
|
) => (() => void) | undefined;
|
|
onChainProgress: (
|
|
cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string) => void,
|
|
) => (() => void) | undefined;
|
|
writeToSession: (sessionId: string, data: string, options?: { automated?: boolean }) => void;
|
|
resizeSession: (sessionId: string, cols: number, rows: number) => void;
|
|
/** Pause/resume the source stream for output back-pressure (optional). */
|
|
setSessionFlowPaused?: (sessionId: string, paused: boolean) => void;
|
|
};
|
|
|
|
export type PendingAuth = {
|
|
authMethod: "password" | "key" | "certificate";
|
|
username: string;
|
|
password?: string;
|
|
keyId?: string;
|
|
passphrase?: string;
|
|
} | null;
|
|
|
|
type ChainProgressState = {
|
|
currentHop: number;
|
|
totalHops: number;
|
|
currentHostLabel: string;
|
|
} | null;
|
|
|
|
export type SessionLogConfig = {
|
|
enabled: boolean;
|
|
directory: string;
|
|
format: string;
|
|
};
|
|
|
|
export type TerminalSessionStartersContext = {
|
|
host: Host;
|
|
keys: SSHKey[];
|
|
identities?: Identity[];
|
|
knownHosts?: KnownHost[];
|
|
resolvedChainHosts: Host[];
|
|
sessionId: string;
|
|
startupCommand?: string;
|
|
noAutoRun?: boolean;
|
|
terminalSettings?: TerminalSettings;
|
|
terminalSettingsRef?: RefObject<TerminalSettings | undefined>;
|
|
terminalBackend: TerminalBackendApi;
|
|
serialConfig?: SerialConfig;
|
|
sessionLog?: SessionLogConfig;
|
|
isVisibleRef?: RefObject<boolean>;
|
|
pendingOutputScrollRef?: RefObject<boolean>;
|
|
|
|
sessionRef: RefObject<string | null>;
|
|
hasConnectedRef: RefObject<boolean>;
|
|
hasRunStartupCommandRef: RefObject<boolean>;
|
|
disposeDataRef: RefObject<(() => void) | null>;
|
|
disposeExitRef: RefObject<(() => void) | null>;
|
|
fitAddonRef: RefObject<FitAddon | null>;
|
|
serializeAddonRef: RefObject<SerializeAddon | null>;
|
|
pendingAuthRef: RefObject<PendingAuth>;
|
|
promptLineBreakStateRef?: RefObject<PromptLineBreakState>;
|
|
|
|
updateStatus: (next: TerminalSession["status"]) => void;
|
|
setStatus: Dispatch<SetStateAction<TerminalSession["status"]>>;
|
|
setError: Dispatch<SetStateAction<string | null>>;
|
|
setNeedsAuth: Dispatch<SetStateAction<boolean>>;
|
|
setAuthRetryMessage: Dispatch<SetStateAction<string | null>>;
|
|
setAuthPassword: Dispatch<SetStateAction<string>>;
|
|
setProgressLogs: Dispatch<SetStateAction<string[]>>;
|
|
setProgressValue: Dispatch<SetStateAction<number>>;
|
|
setChainProgress: Dispatch<SetStateAction<ChainProgressState>>;
|
|
t?: (key: string) => string;
|
|
|
|
onSessionAttached?: (sessionId: string) => void;
|
|
onSessionExit?: (sessionId: string, evt: { exitCode?: number; signal?: number; error?: string; reason?: "exited" | "error" | "timeout" | "closed" }) => void;
|
|
onTerminalDataCapture?: (sessionId: string, data: string) => void;
|
|
onTerminalLogData?: (data: string) => void;
|
|
onOsDetected?: (hostId: string, distro: string) => void;
|
|
onCommandExecuted?: (
|
|
command: string,
|
|
hostId: string,
|
|
hostLabel: string,
|
|
sessionId: string,
|
|
) => void;
|
|
};
|
|
|
|
export const getMissingChainHostIds = (
|
|
host: Host,
|
|
resolvedChainHosts: Host[],
|
|
): string[] => {
|
|
const requestedIds = host.hostChain?.hostIds ?? [];
|
|
if (requestedIds.length === 0) return [];
|
|
const resolvedIds = new Set(resolvedChainHosts.map((chainHost) => chainHost.id));
|
|
return requestedIds.filter((hostId) => !resolvedIds.has(hostId));
|
|
};
|
|
|
|
const buildTermEnv = (host: Host, terminalSettings?: TerminalSettings) => {
|
|
const env: Record<string, string> = {
|
|
TERM: terminalSettings?.terminalEmulationType ?? "xterm-256color",
|
|
};
|
|
|
|
if (host.environmentVariables) {
|
|
for (const { name, value } of host.environmentVariables) {
|
|
if (name) env[name] = value;
|
|
}
|
|
}
|
|
|
|
return env;
|
|
};
|
|
|
|
const handleTerminalOutputAutoScroll = (
|
|
ctx: TerminalSessionStartersContext,
|
|
term: XTerm,
|
|
) => {
|
|
const settings = ctx.terminalSettingsRef?.current ?? ctx.terminalSettings;
|
|
if (!shouldScrollOnTerminalOutput(settings)) {
|
|
return;
|
|
}
|
|
|
|
if (ctx.isVisibleRef?.current === false) {
|
|
if (ctx.pendingOutputScrollRef) {
|
|
ctx.pendingOutputScrollRef.current = true;
|
|
}
|
|
return;
|
|
}
|
|
|
|
term.scrollToBottom();
|
|
};
|
|
|
|
type TerminalWriteQueue = {
|
|
writing: boolean;
|
|
pending: Array<() => void>;
|
|
};
|
|
|
|
const terminalWriteQueues = new WeakMap<XTerm, TerminalWriteQueue>();
|
|
|
|
const scheduleNextTerminalWrite = (term: XTerm, queue: TerminalWriteQueue) => {
|
|
const next = queue.pending.shift();
|
|
if (!next) {
|
|
queue.writing = false;
|
|
terminalWriteQueues.delete(term);
|
|
return;
|
|
}
|
|
|
|
queue.writing = true;
|
|
next();
|
|
};
|
|
|
|
const enqueueTerminalWrite = (
|
|
term: XTerm,
|
|
write: (done: () => void) => void,
|
|
) => {
|
|
let queue = terminalWriteQueues.get(term);
|
|
if (!queue) {
|
|
queue = { writing: false, pending: [] };
|
|
terminalWriteQueues.set(term, queue);
|
|
}
|
|
|
|
queue.pending.push(() => {
|
|
write(() => scheduleNextTerminalWrite(term, queue));
|
|
});
|
|
|
|
if (!queue.writing) {
|
|
scheduleNextTerminalWrite(term, queue);
|
|
}
|
|
};
|
|
|
|
// Output back-pressure. Without this the renderer can't slow a flooding source,
|
|
// so a busy stream grows the write queue and xterm's buffer unbounded. The
|
|
// controller tracks bytes received-but-not-yet-rendered and asks the main
|
|
// process to pause/resume the session's source stream at these watermarks.
|
|
const FLOW_HIGH_WATER_MARK = 256 * 1024; // pause the source above ~256KB backlog
|
|
const FLOW_LOW_WATER_MARK = 64 * 1024; // resume once drained to ~64KB
|
|
|
|
const terminalFlowControllers = new WeakMap<XTerm, OutputFlowController>();
|
|
|
|
const getFlowController = (
|
|
ctx: TerminalSessionStartersContext,
|
|
term: XTerm,
|
|
): OutputFlowController => {
|
|
let controller = terminalFlowControllers.get(term);
|
|
if (!controller) {
|
|
controller = createOutputFlowController({
|
|
highWaterMark: FLOW_HIGH_WATER_MARK,
|
|
lowWaterMark: FLOW_LOW_WATER_MARK,
|
|
onPause: () => {
|
|
const id = ctx.sessionRef.current;
|
|
if (id) ctx.terminalBackend.setSessionFlowPaused?.(id, true);
|
|
},
|
|
onResume: () => {
|
|
const id = ctx.sessionRef.current;
|
|
if (id) ctx.terminalBackend.setSessionFlowPaused?.(id, false);
|
|
},
|
|
});
|
|
terminalFlowControllers.set(term, controller);
|
|
}
|
|
return controller;
|
|
};
|
|
|
|
const writeTerminalLine = (
|
|
ctx: TerminalSessionStartersContext,
|
|
term: XTerm,
|
|
data: string,
|
|
) => {
|
|
enqueueTerminalWrite(term, (done) => {
|
|
const lineData = `${data}\r\n`;
|
|
ctx.onTerminalLogData?.(lineData);
|
|
term.write(lineData, done);
|
|
});
|
|
};
|
|
|
|
const writeSessionData = (
|
|
ctx: TerminalSessionStartersContext,
|
|
term: XTerm,
|
|
data: string,
|
|
) => {
|
|
const flow = getFlowController(ctx, term);
|
|
flow.received(data.length);
|
|
enqueueTerminalWrite(term, (done) => {
|
|
const settings = ctx.terminalSettingsRef?.current ?? ctx.terminalSettings;
|
|
const forcePromptNewLine = settings?.forcePromptNewLine ?? false;
|
|
if (!forcePromptNewLine && ctx.promptLineBreakStateRef?.current) {
|
|
ctx.promptLineBreakStateRef.current.pendingCommand = false;
|
|
ctx.promptLineBreakStateRef.current.suppressNextPromptCache = false;
|
|
}
|
|
const pasteDisplayData = prepareTerminalDataForUserPasteDisplay(term, data);
|
|
const displayData = prepareTerminalDataForPromptLineBreak(
|
|
term,
|
|
pasteDisplayData,
|
|
ctx.promptLineBreakStateRef?.current,
|
|
forcePromptNewLine,
|
|
);
|
|
ctx.onTerminalLogData?.(pasteDisplayData);
|
|
const clearPasteResidualAndCapture = () => {
|
|
const cleanupData = clearPasteResidualAfterTerminalWrite(term);
|
|
if (cleanupData) {
|
|
ctx.onTerminalLogData?.(cleanupData);
|
|
}
|
|
};
|
|
const syncPrompt = () => {
|
|
if (forcePromptNewLine) {
|
|
syncPromptLineBreakState(term, ctx.promptLineBreakStateRef?.current);
|
|
}
|
|
};
|
|
const afterWrite = () => {
|
|
clearPasteResidualAndCapture();
|
|
syncPrompt();
|
|
if (shouldScrollOnTerminalOutput(settings)) {
|
|
handleTerminalOutputAutoScroll(ctx, term);
|
|
}
|
|
done();
|
|
// Acknowledge the chunk so back-pressure can ease once xterm catches up.
|
|
flow.written(data.length);
|
|
};
|
|
|
|
term.write(displayData, afterWrite);
|
|
});
|
|
};
|
|
|
|
const attachSessionToTerminal = (
|
|
ctx: TerminalSessionStartersContext,
|
|
term: XTerm,
|
|
id: string,
|
|
opts?: {
|
|
onExitMessage?: (evt: { exitCode?: number; signal?: number; error?: string; reason?: string }) => string;
|
|
onConnected?: () => void;
|
|
onExit?: (evt: { exitCode?: number; signal?: number; error?: string; reason?: string }) => void;
|
|
// For serial: convert lone LF to CRLF to avoid "staircase effect"
|
|
convertLfToCrlf?: boolean;
|
|
},
|
|
) => {
|
|
ctx.sessionRef.current = id;
|
|
// Clear any stale back-pressure accounting from a prior session on this term.
|
|
getFlowController(ctx, term).reset();
|
|
ctx.onSessionAttached?.(id);
|
|
|
|
ctx.disposeDataRef.current = ctx.terminalBackend.onSessionData(id, (chunk) => {
|
|
let data = chunk;
|
|
// Convert lone LF (\n) to CRLF (\r\n) for proper terminal display
|
|
// This prevents the "staircase effect" common in serial terminals
|
|
if (opts?.convertLfToCrlf) {
|
|
// Replace \n that is not preceded by \r with \r\n
|
|
data = data.replace(/(?<!\r)\n/g, "\r\n");
|
|
}
|
|
writeSessionData(ctx, term, data);
|
|
if (!ctx.hasConnectedRef.current) {
|
|
ctx.updateStatus("connected");
|
|
opts?.onConnected?.();
|
|
setTimeout(() => {
|
|
if (!ctx.fitAddonRef.current) return;
|
|
try {
|
|
ctx.fitAddonRef.current.fit();
|
|
if (ctx.sessionRef.current) {
|
|
ctx.terminalBackend.resizeSession(ctx.sessionRef.current, term.cols, term.rows);
|
|
}
|
|
} catch (err) {
|
|
logger.warn("Post-connect fit failed", err);
|
|
}
|
|
}, 100);
|
|
}
|
|
});
|
|
|
|
ctx.disposeExitRef.current = ctx.terminalBackend.onSessionExit(id, (evt) => {
|
|
ctx.updateStatus("disconnected");
|
|
if (evt.error) {
|
|
ctx.setError(evt.error);
|
|
}
|
|
const exitMessage = opts?.onExitMessage?.(evt) ?? "\r\n[session closed]";
|
|
writeTerminalLine(ctx, term, exitMessage);
|
|
|
|
if (ctx.onTerminalDataCapture && ctx.serializeAddonRef.current) {
|
|
try {
|
|
const terminalData = ctx.serializeAddonRef.current.serialize();
|
|
ctx.onTerminalDataCapture(ctx.sessionId, terminalData);
|
|
} catch (err) {
|
|
logger.warn("Failed to serialize terminal data:", err);
|
|
}
|
|
}
|
|
|
|
// Clean up the connection token for this sessionId so stale timers
|
|
// that haven't fired yet will fail the isConnectionTokenCurrent check
|
|
// (previously they would see the old token still in the map and pass).
|
|
connectionTokensBySessionId.delete(ctx.sessionId);
|
|
|
|
opts?.onExit?.(evt);
|
|
ctx.onSessionExit?.(ctx.sessionId, evt);
|
|
});
|
|
};
|
|
|
|
const STARTUP_COMMAND_DEFAULT_DELAY_MS = 600;
|
|
const STARTUP_COMMAND_MAX_DELAY_MS = 10000;
|
|
|
|
/**
|
|
* Split a (possibly multi-line) startup command into non-empty lines, dropping
|
|
* blank/whitespace-only lines but preserving each line's content verbatim — so
|
|
* a single-line command stays byte-identical to what the user typed (e.g. a
|
|
* leading space for `HISTCONTROL=ignorespace` is kept). Trailing `\r` from
|
|
* CRLF input is normalized away.
|
|
*/
|
|
export function splitStartupCommandLines(commandText: string): string[] {
|
|
return String(commandText || "")
|
|
.split("\n")
|
|
.map((line) => line.replace(/\r$/, ""))
|
|
.filter((line) => line.trim().length > 0);
|
|
}
|
|
|
|
/** Clamp a configured startup-command delay; fall back to the default when unset/invalid. */
|
|
export function normalizeStartupCommandDelay(raw: number | undefined): number {
|
|
const value = typeof raw === "number" && Number.isFinite(raw) ? raw : STARTUP_COMMAND_DEFAULT_DELAY_MS;
|
|
return Math.max(0, Math.min(STARTUP_COMMAND_MAX_DELAY_MS, value));
|
|
}
|
|
|
|
const scheduleStartupCommand = (
|
|
ctx: TerminalSessionStartersContext,
|
|
term: XTerm,
|
|
id: string,
|
|
onSettled?: () => void,
|
|
): (() => void) | undefined => {
|
|
const commandToRun = ctx.startupCommand || ctx.host.startupCommand;
|
|
if (!commandToRun || ctx.hasRunStartupCommandRef.current) return undefined;
|
|
|
|
ctx.hasRunStartupCommandRef.current = true;
|
|
const scheduledSessionId = id;
|
|
const settings = ctx.terminalSettingsRef?.current ?? ctx.terminalSettings;
|
|
const delayMs = normalizeStartupCommandDelay(settings?.startupCommandDelayMs);
|
|
|
|
let cancelled = false;
|
|
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
|
const sessionIsCurrent = () =>
|
|
!!ctx.sessionRef.current && ctx.sessionRef.current === scheduledSessionId;
|
|
|
|
// noAutoRun (snippet "type but don't execute"): type the command as-is, no
|
|
// Enter and no line-splitting — unchanged behavior.
|
|
if (ctx.noAutoRun) {
|
|
timeoutId = setTimeout(() => {
|
|
if (cancelled) return;
|
|
if (!sessionIsCurrent()) {
|
|
onSettled?.();
|
|
return;
|
|
}
|
|
ctx.terminalBackend.writeToSession(ctx.sessionRef.current, commandToRun, { automated: true });
|
|
onSettled?.();
|
|
}, delayMs);
|
|
return () => {
|
|
cancelled = true;
|
|
if (timeoutId) clearTimeout(timeoutId);
|
|
};
|
|
}
|
|
|
|
// Auto-run: send each non-empty line in sequence, waiting delayMs before the
|
|
// first and between each, so a line runs inside any sub-shell opened by a
|
|
// previous line (e.g. `sudo -i` then `alias ...`).
|
|
const lines = splitStartupCommandLines(commandToRun);
|
|
if (lines.length === 0) {
|
|
onSettled?.();
|
|
return undefined;
|
|
}
|
|
|
|
let index = 0;
|
|
const runNext = () => {
|
|
if (cancelled) return;
|
|
if (!sessionIsCurrent()) {
|
|
onSettled?.();
|
|
return;
|
|
}
|
|
const line = lines[index];
|
|
ctx.terminalBackend.writeToSession(ctx.sessionRef.current, `${line}\r`, { automated: true });
|
|
markPromptLineBreakCommandPending(ctx.promptLineBreakStateRef, term, line);
|
|
ctx.onCommandExecuted?.(line, ctx.host.id, ctx.host.label, ctx.sessionId);
|
|
index += 1;
|
|
if (index < lines.length) {
|
|
timeoutId = setTimeout(runNext, delayMs);
|
|
} else {
|
|
onSettled?.();
|
|
}
|
|
};
|
|
|
|
timeoutId = setTimeout(runNext, delayMs);
|
|
return () => {
|
|
cancelled = true;
|
|
if (timeoutId) clearTimeout(timeoutId);
|
|
};
|
|
};
|
|
|
|
const runDistroDetection = async (
|
|
ctx: TerminalSessionStartersContext,
|
|
sessionId: string,
|
|
connectionToken: object,
|
|
) => {
|
|
// Stale-session guard: the renderer reuses ctx.sessionId across
|
|
// reconnects in the same tab, so comparing sessionIds is not enough.
|
|
// We compare against a per-connection token instead; if a newer
|
|
// connect attempt has run, it will have replaced the token in the
|
|
// module-level map and this check will fail. Repeated after every
|
|
// await because the session can change during an async call.
|
|
const isStillCurrent = () => isConnectionTokenCurrent(sessionId, connectionToken);
|
|
|
|
if (!isStillCurrent()) return;
|
|
|
|
// Step 1: try to classify from the SSH server identification string
|
|
// captured at handshake time. This is free (no extra channel) and
|
|
// reliably identifies most network-device vendors (Cisco IOS, Huawei
|
|
// VRP, HPE Comware, MikroTik, Fortinet, etc.) so we can skip the
|
|
// POSIX-shell probe entirely for those hosts — which otherwise fails
|
|
// and, on devices like Cisco / Juniper with AAA logging, generates an
|
|
// extra session log entry per connect.
|
|
try {
|
|
if (ctx.terminalBackend.getSessionRemoteInfo && sessionId) {
|
|
const info = await ctx.terminalBackend.getSessionRemoteInfo(sessionId);
|
|
if (!isStillCurrent()) return;
|
|
const vendor = detectVendorFromSshVersion(info?.remoteSshVersion);
|
|
if (vendor) {
|
|
ctx.onOsDetected?.(ctx.host.id, vendor);
|
|
return;
|
|
}
|
|
}
|
|
} catch (err) {
|
|
logger.warn("SSH banner vendor detection failed", err);
|
|
}
|
|
|
|
if (!isStillCurrent()) return;
|
|
|
|
// Step 2: unknown or generic OpenSSH/Dropbear — fall back to the
|
|
// /etc/os-release probe to pick a distro-specific icon. We deliberately
|
|
// use `getSessionDistroInfo` which runs the probe on the *existing*
|
|
// SSH connection's exec channel instead of spinning up a brand new
|
|
// SSH client the way `execCommand` would. That saves a full handshake
|
|
// round-trip on every connect, and on OpenSSH-fronted network devices
|
|
// that we couldn't identify from the banner (JUNOS, NX-OS, EOS) it
|
|
// avoids one extra AAA session log entry per connect.
|
|
try {
|
|
if (ctx.terminalBackend.getSessionDistroInfo && sessionId) {
|
|
const res = await ctx.terminalBackend.getSessionDistroInfo(sessionId);
|
|
if (!isStillCurrent()) return;
|
|
if (!res?.success) return;
|
|
const data = `${res.stdout || ""}\n${res.stderr || ""}`;
|
|
const idMatch = data.match(/^ID="?([\w-]+)"?$/im);
|
|
const distro = idMatch
|
|
? idMatch[1]
|
|
: (data.split(/\s+/)[0] || "").toLowerCase();
|
|
if (distro) ctx.onOsDetected?.(ctx.host.id, distro);
|
|
}
|
|
} catch (err) {
|
|
logger.warn("OS probe failed", err);
|
|
}
|
|
};
|
|
|
|
export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContext) => {
|
|
const tr = (key: string, fallback: string): string => {
|
|
const translated = ctx.t?.(key);
|
|
if (!translated || translated === key) return fallback;
|
|
return translated;
|
|
};
|
|
|
|
const startSSH = async (term: XTerm) => {
|
|
if (!ctx.terminalBackend.backendAvailable()) {
|
|
ctx.setError("Native SSH bridge unavailable. Launch via Electron app.");
|
|
writeTerminalLine(
|
|
ctx,
|
|
term,
|
|
"\r\n[netcatty SSH bridge unavailable. Please run the desktop build to connect.]",
|
|
);
|
|
ctx.updateStatus("disconnected");
|
|
return;
|
|
}
|
|
|
|
const missingChainHostIds = getMissingChainHostIds(ctx.host, ctx.resolvedChainHosts);
|
|
if (missingChainHostIds.length > 0) {
|
|
const base = tr(
|
|
"terminal.auth.jumpHostMissing",
|
|
"A configured jump host is missing. Open host settings and repair the jump host chain.",
|
|
);
|
|
const suffix = missingChainHostIds.length > 2
|
|
? ` +${missingChainHostIds.length - 2}`
|
|
: "";
|
|
const message = `${base} (${missingChainHostIds.slice(0, 2).join(", ")}${suffix})`;
|
|
ctx.setNeedsAuth(false);
|
|
ctx.setAuthRetryMessage(null);
|
|
ctx.setError(message);
|
|
writeTerminalLine(ctx, term, `\r\n[${message}]`);
|
|
ctx.updateStatus("disconnected");
|
|
return;
|
|
}
|
|
|
|
const pendingAuth = ctx.pendingAuthRef.current;
|
|
const resolvedAuth = resolveHostAuth({
|
|
host: ctx.host,
|
|
keys: ctx.keys,
|
|
identities: ctx.identities,
|
|
override: pendingAuth
|
|
? {
|
|
authMethod: pendingAuth.authMethod,
|
|
username: pendingAuth.username,
|
|
password: pendingAuth.password,
|
|
keyId: pendingAuth.keyId,
|
|
passphrase: pendingAuth.passphrase,
|
|
}
|
|
: null,
|
|
});
|
|
|
|
const effectiveUsername = resolvedAuth.username || "root";
|
|
const key = resolvedAuth.key;
|
|
const effectivePassword = sanitizeCredentialValue(resolvedAuth.password);
|
|
const effectivePassphrase = sanitizeCredentialValue(resolvedAuth.passphrase);
|
|
const hasEncryptedPrimaryPassword = isEncryptedCredentialPlaceholder(resolvedAuth.password);
|
|
const hasEncryptedPrimaryKey = isEncryptedCredentialPlaceholder(key?.privateKey);
|
|
|
|
const isAuthError = (err: unknown): boolean => {
|
|
if (!(err instanceof Error)) return false;
|
|
const msg = err.message.toLowerCase();
|
|
return (
|
|
msg.includes("authentication") ||
|
|
msg.includes("auth") ||
|
|
msg.includes("password") ||
|
|
msg.includes("permission denied")
|
|
);
|
|
};
|
|
|
|
const rawProxyPassword = ctx.host.proxyConfig?.password;
|
|
if (ctx.host.proxyProfileId && !ctx.host.proxyConfig) {
|
|
const message = `Saved proxy for host "${ctx.host.label || ctx.host.hostname}" is missing. Open host settings and select a valid proxy.`;
|
|
ctx.setError(message);
|
|
writeTerminalLine(ctx, term, `\r\n[${message}]`);
|
|
ctx.updateStatus("disconnected");
|
|
return;
|
|
}
|
|
const hasEncryptedProxyPassword = isEncryptedCredentialPlaceholder(rawProxyPassword);
|
|
const proxyConfig = ctx.host.proxyConfig
|
|
? {
|
|
type: ctx.host.proxyConfig.type,
|
|
host: ctx.host.proxyConfig.host,
|
|
port: ctx.host.proxyConfig.port,
|
|
username: ctx.host.proxyConfig.username,
|
|
password: sanitizeCredentialValue(rawProxyPassword),
|
|
}
|
|
: undefined;
|
|
|
|
const jumpHostsWithUnavailableCredentials: string[] = [];
|
|
const unresolvedJumpProxyHost = ctx.resolvedChainHosts.find((jumpHost) => jumpHost.proxyProfileId && !jumpHost.proxyConfig);
|
|
if (unresolvedJumpProxyHost) {
|
|
const message = `Saved proxy for jump host "${unresolvedJumpProxyHost.label || unresolvedJumpProxyHost.hostname}" is missing. Open host settings and select a valid proxy.`;
|
|
ctx.setError(message);
|
|
writeTerminalLine(ctx, term, `\r\n[${message}]`);
|
|
ctx.updateStatus("disconnected");
|
|
return;
|
|
}
|
|
const globalKeepalive = ctx.terminalSettings ?? { keepaliveInterval: 30, keepaliveCountMax: 10 };
|
|
const jumpHosts = ctx.resolvedChainHosts.map<NetcattyJumpHost>((jumpHost, index) => {
|
|
const jumpAuth = resolveHostAuth({
|
|
host: jumpHost,
|
|
keys: ctx.keys,
|
|
identities: ctx.identities,
|
|
});
|
|
const jumpKey = jumpAuth.key;
|
|
const rawJumpPassword = jumpAuth.password;
|
|
const rawJumpPrivateKey = jumpKey?.privateKey;
|
|
const rawJumpPassphrase = jumpAuth.passphrase || jumpKey?.passphrase;
|
|
const jumpPassword = sanitizeCredentialValue(rawJumpPassword);
|
|
const jumpPrivateKey = sanitizeCredentialValue(rawJumpPrivateKey);
|
|
const jumpPassphrase = sanitizeCredentialValue(rawJumpPassphrase);
|
|
const jumpAllowsLocalIdentityFallback = !jumpAuth.keyId;
|
|
const jumpReferenceKeyPath = jumpAuth.authMethod === "password"
|
|
? undefined
|
|
: jumpKey?.source === 'reference' ? jumpKey.filePath : undefined;
|
|
const jumpIdentityFilePaths = jumpAuth.authMethod === "password"
|
|
? undefined
|
|
: jumpReferenceKeyPath
|
|
? [jumpReferenceKeyPath]
|
|
: jumpAllowsLocalIdentityFallback
|
|
? jumpHost.identityFilePaths
|
|
: undefined;
|
|
const hasJumpKeyMaterial = Boolean(jumpPrivateKey || jumpIdentityFilePaths?.length);
|
|
const hasConfiguredJumpProxyEndpoint =
|
|
index === 0 &&
|
|
!!(jumpHost.proxyConfig?.host && jumpHost.proxyConfig?.port);
|
|
const hasEncryptedJumpProxyCredential =
|
|
hasConfiguredJumpProxyEndpoint &&
|
|
Boolean(jumpHost.proxyConfig?.username) &&
|
|
isEncryptedCredentialPlaceholder(jumpHost.proxyConfig?.password);
|
|
|
|
const hasEncryptedJumpCredential =
|
|
isEncryptedCredentialPlaceholder(rawJumpPassword) ||
|
|
isEncryptedCredentialPlaceholder(rawJumpPrivateKey) ||
|
|
isEncryptedCredentialPlaceholder(rawJumpPassphrase);
|
|
|
|
if (hasEncryptedJumpProxyCredential || (hasEncryptedJumpCredential && !jumpPassword && !hasJumpKeyMaterial)) {
|
|
jumpHostsWithUnavailableCredentials.push(jumpHost.label || jumpHost.hostname);
|
|
}
|
|
|
|
// Resolve keepalive for THIS hop. Each jump host carries its own
|
|
// override toggle, so a bastion that is a router (interval=0) can
|
|
// coexist with a cloud target host (interval=30) in the same chain.
|
|
const hopKeepalive = resolveHostKeepalive(jumpHost, globalKeepalive);
|
|
|
|
return {
|
|
hostname: jumpHost.hostname,
|
|
port: jumpHost.port || 22,
|
|
username: jumpAuth.username || "root",
|
|
password: jumpPassword,
|
|
privateKey: jumpKey?.source === 'reference' ? undefined : jumpPrivateKey,
|
|
certificate: jumpKey?.certificate,
|
|
passphrase: jumpPassphrase,
|
|
publicKey: jumpKey?.publicKey,
|
|
keyId: jumpAuth.keyId,
|
|
keySource: jumpKey?.source,
|
|
label: jumpHost.label,
|
|
proxy: jumpHost.proxyConfig?.host && jumpHost.proxyConfig?.port
|
|
? {
|
|
type: jumpHost.proxyConfig.type,
|
|
host: jumpHost.proxyConfig.host,
|
|
port: jumpHost.proxyConfig.port,
|
|
username: jumpHost.proxyConfig.username,
|
|
password: sanitizeCredentialValue(jumpHost.proxyConfig.password),
|
|
}
|
|
: undefined,
|
|
identityFilePaths: jumpIdentityFilePaths,
|
|
keepaliveInterval: hopKeepalive.interval,
|
|
keepaliveCountMax: hopKeepalive.countMax,
|
|
legacyAlgorithms: jumpHost.legacyAlgorithms,
|
|
skipEcdsaHostKey: jumpHost.skipEcdsaHostKey,
|
|
algorithmOverrides: jumpHost.algorithms,
|
|
};
|
|
});
|
|
|
|
const usesTargetProxyForFirstHop = !!proxyConfig && !jumpHosts[0]?.proxy;
|
|
if (usesTargetProxyForFirstHop && hasEncryptedProxyPassword && !proxyConfig?.password && proxyConfig?.username) {
|
|
const message = tr(
|
|
"terminal.auth.proxyCredentialsUnavailable",
|
|
"Proxy credentials cannot be decrypted on this device. Open host settings and re-enter the proxy password.",
|
|
);
|
|
ctx.setNeedsAuth(false);
|
|
ctx.setAuthRetryMessage(null);
|
|
ctx.setError(message);
|
|
writeTerminalLine(ctx, term, `\r\n[${message}]`);
|
|
ctx.updateStatus("disconnected");
|
|
return;
|
|
}
|
|
|
|
if (jumpHostsWithUnavailableCredentials.length > 0) {
|
|
const jumpList = jumpHostsWithUnavailableCredentials.slice(0, 2).join(", ");
|
|
const suffix =
|
|
jumpHostsWithUnavailableCredentials.length > 2
|
|
? ` +${jumpHostsWithUnavailableCredentials.length - 2}`
|
|
: "";
|
|
const base = tr(
|
|
"terminal.auth.jumpCredentialsUnavailable",
|
|
"A jump host has saved credentials that cannot be decrypted on this device. Open host settings and re-enter them.",
|
|
);
|
|
const message = `${base} (${jumpList}${suffix})`;
|
|
ctx.setNeedsAuth(false);
|
|
ctx.setAuthRetryMessage(null);
|
|
ctx.setError(message);
|
|
writeTerminalLine(ctx, term, `\r\n[${message}]`);
|
|
ctx.updateStatus("disconnected");
|
|
return;
|
|
}
|
|
|
|
const totalHops = jumpHosts.length + 1;
|
|
let unsubscribeChainProgress: (() => void) | undefined;
|
|
|
|
if (jumpHosts.length > 0) {
|
|
ctx.setChainProgress({
|
|
currentHop: 1,
|
|
totalHops,
|
|
currentHostLabel:
|
|
jumpHosts[0]?.label || jumpHosts[0]?.hostname || ctx.host.hostname,
|
|
});
|
|
}
|
|
|
|
{
|
|
const unsub = ctx.terminalBackend.onChainProgress((sid, hop, total, label, status, error) => {
|
|
// P1: Only process events for this session
|
|
if (sid !== ctx.sessionId) return;
|
|
|
|
// P3: Only show chain progress UI for multi-hop connections
|
|
if (total > 1) {
|
|
ctx.setChainProgress({
|
|
currentHop: hop,
|
|
totalHops: total,
|
|
currentHostLabel: label,
|
|
});
|
|
}
|
|
|
|
// Build human-readable log line
|
|
let logLine: string;
|
|
const prefix = total > 1 ? `[${hop}/${total}] ` : '';
|
|
|
|
switch (status) {
|
|
case 'connecting':
|
|
logLine = `${prefix}${tr("terminal.progress.connecting", "Connecting to")} ${label}...`;
|
|
break;
|
|
case 'authenticating':
|
|
logLine = `${prefix}${label} - ${tr("terminal.progress.keyExchangeComplete", "Key exchange complete")}`;
|
|
break;
|
|
case 'auth-attempt':
|
|
if (error?.endsWith('rejected')) {
|
|
logLine = `${prefix}${label} - ✗ ${error}`;
|
|
} else if (error === 'all methods exhausted') {
|
|
logLine = `${prefix}${label} - ✗ All authentication methods exhausted`;
|
|
} else if (error === 'waiting for user input...' || error === 'user responded') {
|
|
logLine = `${prefix}${label} - ${error}`;
|
|
} else {
|
|
logLine = `${prefix}${label} - ${tr("terminal.progress.trying", "Trying")} ${error}...`;
|
|
}
|
|
break;
|
|
case 'authenticated':
|
|
logLine = `${prefix}${label} - ${tr("terminal.progress.authenticated", "Authenticated")}`;
|
|
break;
|
|
case 'connected':
|
|
logLine = `${prefix}${label} - ${tr("terminal.progress.connected", "Connected")}`;
|
|
break;
|
|
case 'forwarding':
|
|
logLine = `${prefix}${label} - ${tr("terminal.progress.forwarding", "Forwarding")}...`;
|
|
break;
|
|
case 'shell':
|
|
logLine = `${prefix}${tr("terminal.progress.openingShell", "Opening shell")}...`;
|
|
break;
|
|
case 'error':
|
|
logLine = `${prefix}${label} - ${tr("terminal.progress.error", "Error")}${error ? `: ${error}` : ''}`;
|
|
break;
|
|
default:
|
|
logLine = `${prefix}${label} - ${status}${error ? `: ${error}` : ''}`;
|
|
}
|
|
|
|
ctx.setProgressLogs((prev) => [...prev, logLine]);
|
|
const hopProgress = (hop / total) * 80 + 10;
|
|
ctx.setProgressValue(Math.min(95, hopProgress));
|
|
});
|
|
if (unsub) unsubscribeChainProgress = unsub;
|
|
}
|
|
|
|
try {
|
|
const termEnv = buildTermEnv(ctx.host, ctx.terminalSettings);
|
|
|
|
const authMethod = resolvedAuth.authMethod;
|
|
const allowsLocalIdentityFallback = !resolvedAuth.keyId;
|
|
const targetReferenceKeyPath = key?.source === 'reference' ? key.filePath : undefined;
|
|
const targetIdentityFilePaths = authMethod === "password"
|
|
? undefined
|
|
: targetReferenceKeyPath
|
|
? [targetReferenceKeyPath]
|
|
: allowsLocalIdentityFallback
|
|
? ctx.host.identityFilePaths
|
|
: undefined;
|
|
|
|
const startAttempt = async (attempt: {
|
|
password?: string;
|
|
key?: SSHKey;
|
|
}): Promise<string> => {
|
|
// Resolve keepalive per-host: a host can opt into its own values
|
|
// (e.g. set interval=0 on an embedded device whose SSH stack
|
|
// doesn't reply to keepalive@openssh.com) while everything else
|
|
// inherits the cloud-friendly global setting.
|
|
const keepalive = resolveHostKeepalive(
|
|
ctx.host,
|
|
ctx.terminalSettings ?? { keepaliveInterval: 30, keepaliveCountMax: 10 },
|
|
);
|
|
return ctx.terminalBackend.startSSHSession({
|
|
sessionId: ctx.sessionId,
|
|
hostLabel: ctx.host.label,
|
|
hostname: ctx.host.hostname,
|
|
username: effectiveUsername,
|
|
port: ctx.host.port || 22,
|
|
password: attempt.password,
|
|
privateKey: attempt.key?.source === 'reference' ? undefined : sanitizeCredentialValue(attempt.key?.privateKey),
|
|
certificate: attempt.key?.certificate,
|
|
publicKey: attempt.key?.publicKey,
|
|
keyId: attempt.key?.id,
|
|
keySource: attempt.key?.source,
|
|
passphrase: attempt.key
|
|
? (effectivePassphrase || sanitizeCredentialValue(attempt.key.passphrase))
|
|
: undefined,
|
|
agentForwarding: ctx.host.agentForwarding,
|
|
x11Forwarding: ctx.host.x11Forwarding,
|
|
x11Display: ctx.terminalSettings?.x11Display,
|
|
legacyAlgorithms: ctx.host.legacyAlgorithms,
|
|
skipEcdsaHostKey: ctx.host.skipEcdsaHostKey,
|
|
algorithmOverrides: ctx.host.algorithms,
|
|
cols: term.cols,
|
|
rows: term.rows,
|
|
charset: ctx.host.charset,
|
|
env: termEnv,
|
|
proxy: proxyConfig,
|
|
jumpHosts: jumpHosts.length > 0 ? jumpHosts : undefined,
|
|
keepaliveInterval: keepalive.interval,
|
|
keepaliveCountMax: keepalive.countMax,
|
|
sessionLog: ctx.sessionLog?.enabled ? ctx.sessionLog : undefined,
|
|
identityFilePaths: attempt.password ? undefined : targetIdentityFilePaths,
|
|
knownHosts: ctx.knownHosts,
|
|
});
|
|
};
|
|
|
|
let id: string;
|
|
// Respect explicit auth method selection - don't use key if password auth was explicitly selected
|
|
const hasKeyMaterial = (!!sanitizeCredentialValue(key?.privateKey) || !!targetIdentityFilePaths?.length) && authMethod !== 'password';
|
|
const hasPassword = !!effectivePassword;
|
|
|
|
const needsCredentialReentry =
|
|
(authMethod === "password" && hasEncryptedPrimaryPassword && !hasPassword) ||
|
|
(authMethod !== "password" && hasEncryptedPrimaryKey && !hasKeyMaterial && !hasPassword);
|
|
|
|
if (needsCredentialReentry) {
|
|
if (unsubscribeChainProgress) unsubscribeChainProgress();
|
|
ctx.setError(null);
|
|
ctx.setNeedsAuth(true);
|
|
ctx.setAuthRetryMessage(
|
|
tr(
|
|
"terminal.auth.credentialsUnavailable",
|
|
"Saved credentials cannot be decrypted on this device. Please re-enter and save them again.",
|
|
),
|
|
);
|
|
ctx.setAuthPassword("");
|
|
ctx.setProgressLogs((prev) => [
|
|
...prev,
|
|
tr(
|
|
"terminal.auth.credentialsUnavailable",
|
|
"Saved credentials cannot be decrypted on this device. Please re-enter and save them again.",
|
|
),
|
|
]);
|
|
ctx.setStatus("connecting");
|
|
ctx.setChainProgress(null);
|
|
return;
|
|
}
|
|
|
|
if (!hasKeyMaterial && authMethod !== "password" && hasEncryptedPrimaryKey && hasPassword) {
|
|
ctx.setProgressLogs((prev) => [
|
|
...prev,
|
|
tr(
|
|
"terminal.auth.keyUnavailableFallbackPassword",
|
|
"Saved SSH key is unavailable on this device. Falling back to password authentication.",
|
|
),
|
|
]);
|
|
}
|
|
|
|
|
|
if (hasKeyMaterial) {
|
|
try {
|
|
id = await startAttempt({ key });
|
|
} catch (err) {
|
|
if (isAuthError(err) && hasPassword) {
|
|
ctx.setProgressLogs((prev) => [
|
|
...prev,
|
|
"Key auth failed. Trying password...",
|
|
]);
|
|
id = await startAttempt({ password: effectivePassword });
|
|
} else {
|
|
throw err;
|
|
}
|
|
}
|
|
} else {
|
|
id = await startAttempt({ password: effectivePassword });
|
|
}
|
|
|
|
if (unsubscribeChainProgress) unsubscribeChainProgress();
|
|
|
|
attachSessionToTerminal(ctx, term, id, {
|
|
onConnected: () => ctx.setChainProgress(null),
|
|
onExitMessage: (evt) =>
|
|
`\r\n[session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`,
|
|
});
|
|
|
|
scheduleStartupCommand(ctx, term, id);
|
|
|
|
// Run OS detection only after successful connection. Mint a fresh
|
|
// token for this specific connection attempt and register it as
|
|
// the current one for this sessionId slot; any previous timer
|
|
// scheduled against an earlier token will see the replacement
|
|
// and bail out. The detection function re-checks the token after
|
|
// every async await so a reconnect mid-probe is also caught.
|
|
{
|
|
const connectionToken = {};
|
|
connectionTokensBySessionId.set(id, connectionToken);
|
|
setTimeout(() => {
|
|
if (!isConnectionTokenCurrent(id, connectionToken)) return;
|
|
void runDistroDetection(ctx, id, connectionToken);
|
|
}, 600);
|
|
}
|
|
} catch (err) {
|
|
const message = err instanceof Error ? err.message : String(err);
|
|
const authError = isAuthError(err);
|
|
|
|
if (authError) {
|
|
ctx.setError(null);
|
|
ctx.setNeedsAuth(true);
|
|
ctx.setAuthRetryMessage(
|
|
"Authentication failed. Please check your credentials and try again.",
|
|
);
|
|
ctx.setAuthPassword("");
|
|
ctx.setProgressLogs((prev) => [
|
|
...prev,
|
|
"Authentication failed. Please try again.",
|
|
]);
|
|
ctx.setStatus("connecting");
|
|
} else {
|
|
ctx.setError(message);
|
|
writeTerminalLine(ctx, term, `\r\n[Failed to start SSH: ${message}]`);
|
|
ctx.updateStatus("disconnected");
|
|
}
|
|
|
|
ctx.setChainProgress(null);
|
|
if (unsubscribeChainProgress) unsubscribeChainProgress();
|
|
}
|
|
};
|
|
|
|
const startTelnet = async (term: XTerm) => {
|
|
if (!ctx.terminalBackend.telnetAvailable()) {
|
|
ctx.setError("Telnet bridge unavailable. Please run the desktop build.");
|
|
writeTerminalLine(ctx, term, "\r\n[Telnet bridge unavailable. Please run the desktop build.]");
|
|
ctx.updateStatus("disconnected");
|
|
return;
|
|
}
|
|
|
|
if (ctx.host.proxyProfileId && !ctx.host.proxyConfig) {
|
|
const message = `Saved proxy for host "${ctx.host.label || ctx.host.hostname}" is missing. Open host settings and select a valid proxy.`;
|
|
ctx.setError(message);
|
|
writeTerminalLine(ctx, term, `\r\n[${message}]`);
|
|
ctx.updateStatus("disconnected");
|
|
return;
|
|
}
|
|
|
|
if (ctx.host.proxyConfig?.host && ctx.host.proxyConfig?.port) {
|
|
const message = "Telnet does not support proxy connections. Use SSH for this host or remove the proxy from this connection.";
|
|
ctx.setError(message);
|
|
writeTerminalLine(ctx, term, `\r\n[${message}]`);
|
|
ctx.updateStatus("disconnected");
|
|
return;
|
|
}
|
|
|
|
let disposeAutoLoginComplete: (() => void) | undefined;
|
|
let disposeAutoLoginCancelled: (() => void) | undefined;
|
|
let cancelPendingStartupCommand: (() => void) | undefined;
|
|
const disposeAutoLoginListener = () => {
|
|
disposeAutoLoginComplete?.();
|
|
disposeAutoLoginComplete = undefined;
|
|
};
|
|
const disposeAutoLoginCancelListener = () => {
|
|
disposeAutoLoginCancelled?.();
|
|
disposeAutoLoginCancelled = undefined;
|
|
};
|
|
const cleanupTelnetStartupWait = () => {
|
|
disposeAutoLoginListener();
|
|
disposeAutoLoginCancelListener();
|
|
cancelPendingStartupCommand?.();
|
|
cancelPendingStartupCommand = undefined;
|
|
};
|
|
try {
|
|
const telnetEnv = buildTermEnv(ctx.host, ctx.terminalSettings);
|
|
const telnetUsername = resolveTelnetUsername(ctx.host);
|
|
const rawTelnetPassword = resolveTelnetPassword(ctx.host);
|
|
const telnetPassword = sanitizeCredentialValue(rawTelnetPassword);
|
|
const hasTelnetPasswordForAutoLogin = rawTelnetPassword !== undefined;
|
|
if (isEncryptedCredentialPlaceholder(rawTelnetPassword)) {
|
|
const message = tr(
|
|
"terminal.auth.credentialsUnavailable",
|
|
"Saved credentials cannot be decrypted on this device. Please re-enter and save them again.",
|
|
);
|
|
ctx.setNeedsAuth(false);
|
|
ctx.setAuthRetryMessage(null);
|
|
ctx.setError(message);
|
|
writeTerminalLine(ctx, term, `\r\n[${message}]`);
|
|
ctx.updateStatus("disconnected");
|
|
return;
|
|
}
|
|
const commandToRun = ctx.startupCommand || ctx.host.startupCommand;
|
|
const waitsForAutoLogin = Boolean(
|
|
commandToRun &&
|
|
(telnetUsername || hasTelnetPasswordForAutoLogin) &&
|
|
ctx.terminalBackend.onTelnetAutoLoginComplete,
|
|
);
|
|
let telnetSessionId = ctx.sessionId;
|
|
if (waitsForAutoLogin) {
|
|
disposeAutoLoginComplete = ctx.terminalBackend.onTelnetAutoLoginComplete?.(
|
|
ctx.sessionId,
|
|
() => {
|
|
disposeAutoLoginListener();
|
|
cancelPendingStartupCommand = scheduleStartupCommand(ctx, term, telnetSessionId, () => {
|
|
cancelPendingStartupCommand = undefined;
|
|
disposeAutoLoginCancelListener();
|
|
});
|
|
},
|
|
);
|
|
disposeAutoLoginCancelled = ctx.terminalBackend.onTelnetAutoLoginCancelled?.(
|
|
ctx.sessionId,
|
|
cleanupTelnetStartupWait,
|
|
);
|
|
}
|
|
const id = await ctx.terminalBackend.startTelnetSession({
|
|
sessionId: ctx.sessionId,
|
|
hostname: ctx.host.hostname,
|
|
port: resolveTelnetPort(ctx.host),
|
|
username: telnetUsername,
|
|
password: telnetPassword,
|
|
cols: term.cols,
|
|
rows: term.rows,
|
|
charset: ctx.host.charset,
|
|
env: telnetEnv,
|
|
sessionLog: ctx.sessionLog?.enabled ? ctx.sessionLog : undefined,
|
|
});
|
|
telnetSessionId = id;
|
|
|
|
attachSessionToTerminal(ctx, term, id, {
|
|
onExitMessage: (evt) =>
|
|
`\r\n[Telnet session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`,
|
|
onExit: cleanupTelnetStartupWait,
|
|
});
|
|
const disposeTelnetExit = ctx.disposeExitRef.current;
|
|
ctx.disposeExitRef.current = () => {
|
|
cleanupTelnetStartupWait();
|
|
disposeTelnetExit?.();
|
|
};
|
|
if (waitsForAutoLogin) {
|
|
return;
|
|
}
|
|
} catch (err) {
|
|
cleanupTelnetStartupWait();
|
|
const message = err instanceof Error ? err.message : String(err);
|
|
ctx.setError(message);
|
|
writeTerminalLine(ctx, term, `\r\n[Failed to start Telnet: ${message}]`);
|
|
ctx.updateStatus("disconnected");
|
|
}
|
|
};
|
|
|
|
const startMosh = async (term: XTerm) => {
|
|
if (!ctx.terminalBackend.moshAvailable()) {
|
|
ctx.setError("Mosh bridge unavailable. Please run the desktop build.");
|
|
writeTerminalLine(ctx, term, "\r\n[Mosh bridge unavailable. Please run the desktop build.]");
|
|
ctx.updateStatus("disconnected");
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const stopMosh = (message: string) => {
|
|
ctx.setError(message);
|
|
writeTerminalLine(ctx, term, `\r\n[${message}]`);
|
|
ctx.updateStatus("disconnected");
|
|
};
|
|
|
|
if (ctx.host.proxyProfileId && !ctx.host.proxyConfig) {
|
|
stopMosh(`Saved proxy for host "${ctx.host.label || ctx.host.hostname}" is missing. Open host settings and select a valid proxy.`);
|
|
return;
|
|
}
|
|
|
|
const hasConfiguredJumpHostChain =
|
|
(ctx.host.hostChain?.hostIds?.length || 0) > 0 ||
|
|
ctx.resolvedChainHosts.length > 0;
|
|
if (hasConfiguredJumpHostChain) {
|
|
stopMosh("Mosh does not support jump host chains. Use SSH for this host or remove the jump hosts from this connection.");
|
|
return;
|
|
}
|
|
|
|
const unresolvedJumpProxyHost = ctx.resolvedChainHosts.find((jumpHost) => jumpHost.proxyProfileId && !jumpHost.proxyConfig);
|
|
if (unresolvedJumpProxyHost) {
|
|
stopMosh(`Saved proxy for jump host "${unresolvedJumpProxyHost.label || unresolvedJumpProxyHost.hostname}" is missing. Open host settings and select a valid proxy.`);
|
|
return;
|
|
}
|
|
|
|
const hasConfiguredProxy =
|
|
Boolean(ctx.host.proxyConfig?.host && ctx.host.proxyConfig?.port) ||
|
|
ctx.resolvedChainHosts.some((jumpHost) => Boolean(jumpHost.proxyConfig?.host && jumpHost.proxyConfig?.port));
|
|
if (hasConfiguredProxy) {
|
|
stopMosh("Mosh does not support proxy connections. Use SSH for this host or remove the proxy from this connection.");
|
|
return;
|
|
}
|
|
|
|
const pendingAuth = ctx.pendingAuthRef.current;
|
|
const resolvedAuth = resolveHostAuth({
|
|
host: ctx.host,
|
|
keys: ctx.keys,
|
|
identities: ctx.identities,
|
|
override: pendingAuth
|
|
? {
|
|
authMethod: pendingAuth.authMethod,
|
|
username: pendingAuth.username,
|
|
password: pendingAuth.password,
|
|
keyId: pendingAuth.keyId,
|
|
passphrase: pendingAuth.passphrase,
|
|
}
|
|
: null,
|
|
});
|
|
const effectivePassword = sanitizeCredentialValue(resolvedAuth.password);
|
|
const effectivePassphrase = sanitizeCredentialValue(resolvedAuth.passphrase);
|
|
const authMethod = resolvedAuth.authMethod;
|
|
const key = authMethod === "password" ? undefined : resolvedAuth.key;
|
|
const hasEncryptedPrimaryPassword = isEncryptedCredentialPlaceholder(resolvedAuth.password);
|
|
const hasEncryptedPrimaryKey = isEncryptedCredentialPlaceholder(resolvedAuth.key?.privateKey);
|
|
const allowsLocalIdentityFallback = !resolvedAuth.keyId;
|
|
const moshReferenceKeyPath = key?.source === 'reference' ? key.filePath : undefined;
|
|
const moshIdentityFilePaths = authMethod === "password"
|
|
? undefined
|
|
: moshReferenceKeyPath
|
|
? [moshReferenceKeyPath]
|
|
: allowsLocalIdentityFallback
|
|
? ctx.host.identityFilePaths
|
|
: undefined;
|
|
const hasKeyMaterial = (!!sanitizeCredentialValue(key?.privateKey) || !!moshIdentityFilePaths?.length) && authMethod !== "password";
|
|
const hasPassword = !!effectivePassword;
|
|
const needsCredentialReentry =
|
|
(authMethod === "password" && hasEncryptedPrimaryPassword && !hasPassword) ||
|
|
(authMethod !== "password" && hasEncryptedPrimaryKey && !hasKeyMaterial && !hasPassword);
|
|
|
|
if (needsCredentialReentry) {
|
|
ctx.setError(null);
|
|
ctx.setNeedsAuth(true);
|
|
ctx.setAuthRetryMessage(
|
|
tr(
|
|
"terminal.auth.credentialsUnavailable",
|
|
"Saved credentials cannot be decrypted on this device. Please re-enter and save them again.",
|
|
),
|
|
);
|
|
ctx.setAuthPassword("");
|
|
ctx.setStatus("connecting");
|
|
return;
|
|
}
|
|
|
|
const moshEnv = buildTermEnv(ctx.host, ctx.terminalSettings);
|
|
const id = await ctx.terminalBackend.startMoshSession({
|
|
sessionId: ctx.sessionId,
|
|
hostname: ctx.host.hostname,
|
|
username: resolvedAuth.username || "root",
|
|
password: effectivePassword,
|
|
privateKey: key?.source === 'reference' ? undefined : sanitizeCredentialValue(key?.privateKey),
|
|
certificate: key?.certificate,
|
|
keyId: key?.id,
|
|
passphrase: key
|
|
? (effectivePassphrase || sanitizeCredentialValue(key.passphrase))
|
|
: undefined,
|
|
identityFilePaths: moshIdentityFilePaths,
|
|
port: ctx.host.port || 22,
|
|
moshServerPath: ctx.host.moshServerPath,
|
|
agentForwarding: ctx.host.agentForwarding,
|
|
cols: term.cols,
|
|
rows: term.rows,
|
|
charset: ctx.host.charset,
|
|
env: moshEnv,
|
|
sessionLog: ctx.sessionLog?.enabled ? ctx.sessionLog : undefined,
|
|
});
|
|
|
|
attachSessionToTerminal(ctx, term, id, {
|
|
onExitMessage: (evt) =>
|
|
`\r\n[Mosh session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`,
|
|
});
|
|
|
|
scheduleStartupCommand(ctx, term, id);
|
|
} catch (err) {
|
|
const message = err instanceof Error ? err.message : String(err);
|
|
ctx.setError(message);
|
|
writeTerminalLine(ctx, term, `\r\n[Failed to start Mosh: ${message}]`);
|
|
ctx.updateStatus("disconnected");
|
|
}
|
|
};
|
|
|
|
const startLocal = async (term: XTerm) => {
|
|
if (!ctx.terminalBackend.localAvailable()) {
|
|
ctx.setError("Local shell bridge unavailable. Please run the desktop build.");
|
|
writeTerminalLine(
|
|
ctx,
|
|
term,
|
|
"\r\n[Local shell bridge unavailable. Please run the desktop build to spawn a local terminal.]",
|
|
);
|
|
ctx.updateStatus("disconnected");
|
|
return;
|
|
}
|
|
|
|
try {
|
|
// Per-session shell (from QuickSwitcher discovery or split/copy) takes priority.
|
|
// The global terminalSettings.localShell may contain a shell ID (e.g., "wsl-ubuntu")
|
|
// which was already resolved to command+args and stored on the session object by App.tsx.
|
|
// Only pass shell/shellArgs when we have concrete per-session values;
|
|
// otherwise omit them so the backend uses its own default shell detection.
|
|
const sessionShell = ctx.host.localShell;
|
|
const sessionShellArgs = ctx.host.localShellArgs;
|
|
const localStartDir = ctx.terminalSettings?.localStartDir;
|
|
|
|
const id = await ctx.terminalBackend.startLocalSession({
|
|
sessionId: ctx.sessionId,
|
|
cols: term.cols,
|
|
rows: term.rows,
|
|
shell: sessionShell || undefined,
|
|
shellArgs: sessionShellArgs || undefined,
|
|
cwd: localStartDir,
|
|
env: {
|
|
TERM: ctx.terminalSettings?.terminalEmulationType ?? "xterm-256color",
|
|
},
|
|
sessionLog: ctx.sessionLog?.enabled ? ctx.sessionLog : undefined,
|
|
});
|
|
|
|
ctx.sessionRef.current = id;
|
|
getFlowController(ctx, term).reset();
|
|
ctx.disposeDataRef.current = ctx.terminalBackend.onSessionData(id, (chunk) => {
|
|
writeSessionData(ctx, term, chunk);
|
|
if (!ctx.hasConnectedRef.current) {
|
|
ctx.updateStatus("connected");
|
|
setTimeout(() => {
|
|
if (!ctx.fitAddonRef.current) return;
|
|
try {
|
|
ctx.fitAddonRef.current.fit();
|
|
if (ctx.sessionRef.current) {
|
|
ctx.terminalBackend.resizeSession(ctx.sessionRef.current, term.cols, term.rows);
|
|
}
|
|
} catch (err) {
|
|
logger.warn("Post-connect fit failed", err);
|
|
}
|
|
}, 100);
|
|
}
|
|
});
|
|
|
|
ctx.disposeExitRef.current = ctx.terminalBackend.onSessionExit(id, (evt) => {
|
|
ctx.updateStatus("disconnected");
|
|
const exitMessage = `\r\n[session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`;
|
|
writeTerminalLine(ctx, term, exitMessage);
|
|
|
|
logger.info("[Terminal] Session exit, capturing data", {
|
|
sessionId: ctx.sessionId,
|
|
hasCallback: !!ctx.onTerminalDataCapture,
|
|
hasSerializeAddon: !!ctx.serializeAddonRef.current,
|
|
});
|
|
|
|
if (ctx.onTerminalDataCapture && ctx.serializeAddonRef.current) {
|
|
try {
|
|
const terminalData = ctx.serializeAddonRef.current.serialize();
|
|
logger.info("[Terminal] Serialized terminal data", {
|
|
sessionId: ctx.sessionId,
|
|
dataLength: terminalData.length,
|
|
});
|
|
ctx.onTerminalDataCapture(ctx.sessionId, terminalData);
|
|
} catch (err) {
|
|
logger.warn("Failed to serialize terminal data:", err);
|
|
}
|
|
}
|
|
|
|
ctx.onSessionExit?.(ctx.sessionId, evt);
|
|
});
|
|
} catch (err) {
|
|
const message = err instanceof Error ? err.message : String(err);
|
|
ctx.setError(message);
|
|
writeTerminalLine(ctx, term, `\r\n[Failed to start local shell: ${message}]`);
|
|
ctx.updateStatus("disconnected");
|
|
}
|
|
};
|
|
|
|
// Start Serial session
|
|
const startSerial = async (term: XTerm) => {
|
|
if (!ctx.serialConfig) {
|
|
ctx.setError("No serial configuration provided");
|
|
writeTerminalLine(ctx, term, "\r\n[Error: No serial configuration provided]");
|
|
ctx.updateStatus("disconnected");
|
|
return;
|
|
}
|
|
|
|
try {
|
|
logger.info("[Serial] Starting serial session", {
|
|
port: ctx.serialConfig.path,
|
|
baudRate: ctx.serialConfig.baudRate,
|
|
});
|
|
|
|
const id = await ctx.terminalBackend.startSerialSession({
|
|
sessionId: ctx.sessionId,
|
|
path: ctx.serialConfig.path,
|
|
baudRate: ctx.serialConfig.baudRate,
|
|
dataBits: ctx.serialConfig.dataBits,
|
|
stopBits: ctx.serialConfig.stopBits,
|
|
parity: ctx.serialConfig.parity,
|
|
flowControl: ctx.serialConfig.flowControl,
|
|
charset: ctx.host.charset,
|
|
sessionLog: ctx.sessionLog?.enabled ? ctx.sessionLog : undefined,
|
|
});
|
|
|
|
// Serial connection is established immediately when session starts
|
|
// Update status right away since serial ports don't require handshake
|
|
ctx.updateStatus("connected");
|
|
ctx.setProgressValue(100);
|
|
writeTerminalLine(ctx, term, `[Connected to ${ctx.serialConfig.path} at ${ctx.serialConfig.baudRate} baud]`);
|
|
|
|
attachSessionToTerminal(ctx, term, id, {
|
|
onExitMessage: (evt) =>
|
|
`\r\n[serial port closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`,
|
|
// Convert lone LF to CRLF to prevent "staircase effect" in serial terminals
|
|
convertLfToCrlf: true,
|
|
});
|
|
} catch (err) {
|
|
const message = err instanceof Error ? err.message : String(err);
|
|
ctx.setError(message);
|
|
writeTerminalLine(ctx, term, `\r\n[Failed to connect to serial port: ${message}]`);
|
|
ctx.updateStatus("disconnected");
|
|
}
|
|
};
|
|
|
|
return { startSSH, startTelnet, startMosh, startLocal, startSerial };
|
|
};
|