Files
Netcatty/electron/bridges/hostKeyVerifier.cjs
T
205d1591e8 feat(terminal): add disconnect/reconnect on workspace split status bar (#2769) (#2771)
* feat(terminal): add disconnect/reconnect controls on session status bar

Workspace panes could not reach tab-level reconnect. Expose disconnect
(without closing the pane) and reconnect beside the host info actions so
split sessions stay operable. Closes #2769.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): abort in-flight boot on status-bar disconnect

Disconnect keeps the pane mounted, so cancel's unmount cleanup never runs.
Flip isBootActiveRef (and isCancelling) so a late startSSH/startMosh attach
cannot resurrect the session after the user disconnects mid-connect.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): ignore stale start UI after status-bar disconnect

When disconnect aborts an in-flight connect, starter catch paths must not
reopen auth or repopulate errors. Gate SSH/telnet/mosh/ET/local/serial
failure UI on isTerminalBootActive and harden the boot effect awaits.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): hide disconnect/reconnect on compact popup terminals

Owned command popups use compactToolbar with a one-shot startup command.
Exposing reconnect there can re-run that command; keep the controls on
normal tabs/workspace panes only.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): use boot epoch so reconnect cannot revive aborted starts

Disconnect alone flipping isBootActiveRef is not enough: an immediate
reconnect re-arms boot, and a late startSSH from the aborted attempt can
still attach. Capture a boot epoch per attempt and ignore stale attaches/UI.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): do not let stale attach abort a newer reconnect

tryAttach failure for an expired boot epoch must close the orphan session
only. Calling abortSessionStartAfterUnmount() would force disconnected on
a reconnect that already re-armed boot.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): reject late host-key prompts after disconnect

Disconnect can land before pendingHostKeyRequestId is set. Auto-deny
onHostKeyVerification when boot is inactive or status is disconnected
so approval UI cannot reopen on an aborted pane.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): cancel wake and MFA when status-bar disconnects

Invalidate hibernation reconnect-wake tokens on disconnect so a late wake
cannot re-arm boot. Reject/cancel keyboard-interactive prompts for
disconnected panes and clear any already-queued MFA for that session.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): ignore stale SSH catch UI and password fallback

Check boot attempt currency before resetting reconnect UI state on
SSH start failure, and before launching key→password fallback after
disconnect so a replacement reconnect is not interrupted.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): guard stale SSH progress and host-key prompts

Ignore chain-progress callbacks from superseded boot attempts, and
thread bootEpoch through SSH host-key verification so a late prompt
from an aborted start cannot overwrite a replacement reconnect.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): correlate MFA and jump host-keys with boot epoch

Forward bootEpoch through jump-host verification and keyboard-interactive
prompts, and reject superseded MFA when the retained tab has already
started a replacement reconnect.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): keep replacement SSH session alive across stale starts

Skip closeSession for superseded starts while a newer boot still owns
the shared sessionId, and avoid clearing MFA wait state before the
attempt-freshness guard on SSH success.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): own shared sessionIds by boot epoch

Claim SSH/local registry slots with bootEpoch so a stale start cannot
overwrite a replacement, and make closeSession no-op when the payload
epoch does not match the live session owner.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): claim bootEpoch for all reconnectable backends

Pass bootEpoch through Telnet/Mosh/ET/serial starts, claim registry slots
the same way as SSH/local, and dispose displaced owners when a newer
boot replaces the shared sessionId.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): protect preload listeners and ET artifacts on displace

Defer epoch-scoped closeSession listener teardown until main confirms
ownership, and remove ET external-auth temp artifacts when a newer boot
displaces the previous registry owner.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): clean rejected Mosh starts and keep replacement listeners

Kill superseded Mosh/ET PTYs and auth temp files when claimSessionSlot
rejects, and never clear shared preload listeners on epoch-scoped closes.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): settle superseded boots and stop displaced log streams

Reject Telnet/SSH claim failures through Promise reject/failReuse instead of
uncaught EventEmitter/.then throws, and stop a displaced session's log stream
so a logging-disabled reconnect cannot append into the old file.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): keep woken runtime when disconnect cancels hibernate wake

Disconnect invalidates in-flight hibernated reconnects with keep mode so a
successful wake that already cleared hibernatedRef is not disposed into a
dead pane that can never reconnect. Unmount still disposes orphan runtimes.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): bind reused SSH shellPid only to the claimed session

Late PID discovery after Copy Tab reuse must not write onto a newer
bootEpoch that already replaced the shared sessionId registry slot.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): await plugin cancel cleanup and clear boot epochs on teardown

Track plugin start/cancel promises so Disconnect→Reconnect waits until the
external session finishes unregistering, and stop unmount teardown from
republishing boot epochs into the process-wide map.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): cancel SSH passphrase prompts on disconnect

Register a pending-boot AbortSignal for SSH starts, abort it (and session-
scoped passphrase requests) from closeSession even before a registry slot
exists, and filter/drop late passphrase modals by boot epoch / disconnect.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): close owned boot epoch and scope passphrase cancels

Capture the pre-bump epoch for disconnect/teardown closeSession so live
transports are not skipped by epoch mismatch, cancel only passphrase prompts
at or below that epoch, and revalidate boot currency after async passphrase
lookups before queuing a modal.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): tag Telnet auto-login and Mosh ready with bootEpoch

Emit bootEpoch on telnet auto-login and mosh:ready events so overlapping
Disconnect→Reconnect boots ignore cross-delivered callbacks meant for an
older shared sessionId.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): update disconnect assertion and cancel pending serial opens

Align the disconnect source regression with invalidateBootEpochForClose, and
abort in-flight serialPort.open attempts via pending boot AbortSignal so
Disconnect→Reconnect cannot leave a stale open racing the replacement.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): keep flow-pause leases on skipped epoch closes

Worker close:await previously cleared pause ownership in finally even when
the worker returned skipped for an epoch mismatch, dropping the live
replacement's lease. Only clear on non-skipped closes; epoch-scoped
fire-and-forget close similarly defers to onSessionClosed.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>
2026-08-06 15:47:20 +08:00

280 lines
8.3 KiB
JavaScript

const crypto = require("node:crypto");
const { randomUUID } = require("node:crypto");
const { utils: sshUtils } = require("ssh2");
const REQUEST_TTL_MS = 2 * 60 * 1000;
const hostKeyRequests = new Map();
const normalizeFingerprint = (value) => {
if (typeof value !== "string") return "";
return value
.trim()
.replace(/^SHA256:/i, "")
.replace(/=+$/g, "");
};
const normalizeHostname = (value) => String(value || "").trim().toLowerCase();
const parseKnownHostPattern = (hostname) => {
const value = String(hostname || "").trim();
if (!value) return { hostname: "", port: undefined };
const first = value.split(",")[0];
const bracketMatch = first.match(/^\[([^\]]+)\]:(\d+)$/);
if (bracketMatch) {
return {
hostname: normalizeHostname(bracketMatch[1]),
port: Number.parseInt(bracketMatch[2], 10),
};
}
return { hostname: normalizeHostname(first), port: undefined };
};
const getKnownHostPort = (knownHost) => {
const parsed = parseKnownHostPattern(knownHost?.hostname);
if (Number.isFinite(knownHost?.port)) return Number(knownHost.port);
if (Number.isFinite(parsed.port)) return Number(parsed.port);
return 22;
};
const matchesHostAndPort = (knownHost, hostname, port) => {
const parsed = parseKnownHostPattern(knownHost?.hostname);
if (!parsed.hostname || parsed.hostname === "(hashed)") return false;
return parsed.hostname === normalizeHostname(hostname) && getKnownHostPort(knownHost) === (port || 22);
};
const describeRawPublicKeyBlob = (key) => {
if (!Buffer.isBuffer(key) || key.length < 8) return null;
const typeLength = key.readUInt32BE(0);
if (typeLength <= 0 || typeLength > 128 || 4 + typeLength > key.length) return null;
const keyType = key.subarray(4, 4 + typeLength).toString("ascii");
if (!/^[A-Za-z0-9@._+-]+$/.test(keyType)) return null;
return {
keyType,
publicKey: `${keyType} ${key.toString("base64")}`,
};
};
const fingerprintFromPublicKey = (publicKey) => {
if (typeof publicKey !== "string") return "";
const trimmed = publicKey.trim();
if (!trimmed) return "";
if (/^SHA256:/i.test(trimmed)) return normalizeFingerprint(trimmed);
const parts = trimmed.split(/\s+/);
if (parts.length >= 2 && /^ssh-|^ecdsa-|^sk-/.test(parts[0])) {
try {
return crypto.createHash("sha256")
.update(Buffer.from(parts[1], "base64"))
.digest("base64")
.replace(/=+$/g, "");
} catch {
return "";
}
}
return normalizeFingerprint(trimmed);
};
const getKnownHostFingerprint = (knownHost) => {
return normalizeFingerprint(knownHost?.fingerprint)
|| fingerprintFromPublicKey(knownHost?.publicKey);
};
// Classification rules, in order:
// 1. Any record for (host, port) whose fingerprint matches the live key →
// trusted. Fingerprint is the ground truth; key type is metadata.
// 2. A record matching (host, port, keyType) *exactly* with a non-matching
// fingerprint → changed. Only this case is a real "key rotated" alarm —
// the user already trusted this exact algorithm on this host and the
// server now presents a different key of the same type.
// 3. Otherwise → unknown. This includes the case where the server presents
// a key of an algorithm we have no record for, even if the host has
// records for other algorithms. Tabby and OpenSSH both treat that as a
// first-time prompt rather than a mismatch warning (#972).
const classifyHostKey = ({ knownHosts = [], hostname, port = 22, keyType, fingerprint }) => {
const normalizedFingerprint = normalizeFingerprint(fingerprint);
const candidates = Array.isArray(knownHosts)
? knownHosts.filter((knownHost) => matchesHostAndPort(knownHost, hostname, port))
: [];
if (candidates.length === 0) {
return { status: "unknown" };
}
const comparableCandidates = candidates
.map((knownHost) => ({
knownHost,
fingerprint: getKnownHostFingerprint(knownHost),
}))
.filter((entry) => entry.fingerprint);
const match = comparableCandidates.find((entry) => entry.fingerprint === normalizedFingerprint);
if (match) {
return { status: "trusted", knownHost: match.knownHost };
}
const normalizedKeyType = typeof keyType === "string" ? keyType.trim() : "";
if (normalizedKeyType && normalizedKeyType !== "unknown") {
const sameTypeMismatch = comparableCandidates.find(
(entry) => entry.knownHost.keyType === normalizedKeyType,
);
if (sameTypeMismatch) {
return {
status: "changed",
knownHost: sameTypeMismatch.knownHost,
expectedFingerprint: sameTypeMismatch.fingerprint,
};
}
}
return { status: "unknown" };
};
const describeHostKey = (rawKey) => {
const key = Buffer.isBuffer(rawKey) ? rawKey : Buffer.from(rawKey || "");
const fingerprint = crypto.createHash("sha256")
.update(key)
.digest("base64")
.replace(/=+$/g, "");
let keyType = "unknown";
let publicKey;
const rawPublicKey = describeRawPublicKeyBlob(key);
if (rawPublicKey) {
keyType = rawPublicKey.keyType;
publicKey = rawPublicKey.publicKey;
}
try {
const parsed = sshUtils.parseKey(key);
const parsedKey = Array.isArray(parsed) ? parsed[0] : parsed;
if (parsedKey && !(parsedKey instanceof Error)) {
keyType = parsedKey.type || keyType;
const publicSsh = parsedKey.getPublicSSH?.();
if (publicSsh) publicKey = publicSsh.toString("utf8");
}
} catch {
// Keep the fingerprint; key type/public key are best-effort metadata.
}
return { keyType, fingerprint, publicKey };
};
const generateRequestId = () => `hostkey-${randomUUID()}`;
const settleRequest = (requestId, response) => {
const pending = hostKeyRequests.get(requestId);
if (!pending) return { success: false, error: "Request not found" };
if (pending.timeoutId) clearTimeout(pending.timeoutId);
hostKeyRequests.delete(requestId);
pending.resolve(response);
return { success: true };
};
const requestHostKeyVerification = (sender, info) => new Promise((resolve) => {
if (!sender || sender.isDestroyed?.()) {
resolve({ accept: false });
return;
}
const requestId = generateRequestId();
const timeoutId = setTimeout(() => {
settleRequest(requestId, { accept: false, timeout: true });
}, REQUEST_TTL_MS);
hostKeyRequests.set(requestId, {
resolve,
timeoutId,
createdAt: Date.now(),
webContentsId: sender.id,
sessionId: info.sessionId,
});
try {
sender.send("netcatty:host-key:verify", {
requestId,
...info,
});
} catch {
settleRequest(requestId, { accept: false });
}
});
const createHostVerifier = ({
sender,
sessionId,
hostname,
port = 22,
knownHosts = [],
verifyHostKeys = true,
bootEpoch,
}) => (rawKey, callback) => {
if (verifyHostKeys === false) {
callback(true);
return;
}
const keyInfo = describeHostKey(rawKey);
const decision = classifyHostKey({
knownHosts,
hostname,
port,
keyType: keyInfo.keyType,
fingerprint: keyInfo.fingerprint,
});
if (decision.status === "trusted") {
callback(true);
return;
}
void requestHostKeyVerification(sender, {
sessionId,
hostname,
port,
status: decision.status,
keyType: keyInfo.keyType,
fingerprint: keyInfo.fingerprint,
publicKey: keyInfo.publicKey,
knownHostId: decision.knownHost?.id,
knownFingerprint: decision.expectedFingerprint,
...(Number.isFinite(bootEpoch) ? { bootEpoch: Number(bootEpoch) } : {}),
}).then((response) => {
callback(Boolean(response?.accept));
}).catch(() => {
callback(false);
});
};
const handleResponse = (_event, payload) => {
const { requestId, accept, addToKnownHosts } = payload || {};
const pending = hostKeyRequests.get(requestId);
if (!pending) return { success: false, error: "Request not found" };
if (_event?.sender?.id !== pending.webContentsId) {
return { success: false, error: "Wrong sender" };
}
return settleRequest(requestId, {
accept: Boolean(accept),
addToKnownHosts: Boolean(addToKnownHosts),
});
};
const registerHandler = (ipcMain) => {
ipcMain.handle("netcatty:host-key:respond", handleResponse);
};
const getRequests = () => hostKeyRequests;
module.exports = {
classifyHostKey,
createHostVerifier,
describeHostKey,
getKnownHostFingerprint,
handleResponse,
normalizeFingerprint,
registerHandler,
requestHostKeyVerification,
getRequests,
};