Files
Netcatty/electron/bridges/hostKeyVerifier.test.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

429 lines
12 KiB
JavaScript

const test = require("node:test");
const assert = require("node:assert/strict");
const crypto = require("node:crypto");
const {
classifyHostKey,
createHostVerifier,
describeHostKey,
handleResponse,
normalizeFingerprint,
} = require("./hostKeyVerifier.cjs");
const makeRawPublicKey = (keyType, body = "trusted imported host key") => {
const type = Buffer.from(keyType);
const length = Buffer.alloc(4);
length.writeUInt32BE(type.length, 0);
return Buffer.concat([length, type, Buffer.from(body)]);
};
test("classifyHostKey prompts for unknown hosts", () => {
const result = classifyHostKey({
knownHosts: [],
hostname: "switch.local",
port: 22,
keyType: "ssh-ed25519",
fingerprint: "new-key",
});
assert.equal(result.status, "unknown");
});
test("classifyHostKey trusts a matching known host fingerprint", () => {
const result = classifyHostKey({
knownHosts: [{
id: "kh-1",
hostname: "switch.local",
port: 22,
keyType: "ssh-ed25519",
publicKey: "SHA256:trusted-key",
discoveredAt: 1,
}],
hostname: "switch.local",
port: 22,
keyType: "ssh-ed25519",
fingerprint: "trusted-key",
});
assert.equal(result.status, "trusted");
});
test("classifyHostKey trusts a matching full known_hosts public key", () => {
const rawKey = makeRawPublicKey("ssh-ed25519");
const fingerprint = crypto.createHash("sha256").update(rawKey).digest("base64").replace(/=+$/g, "");
const result = classifyHostKey({
knownHosts: [{
id: "kh-1",
hostname: "switch.local",
port: 22,
keyType: "ssh-ed25519",
publicKey: `ssh-ed25519 ${rawKey.toString("base64")}`,
discoveredAt: 1,
}],
hostname: "switch.local",
port: 22,
keyType: "ssh-ed25519",
fingerprint,
});
assert.equal(result.status, "trusted");
});
test("describeHostKey preserves the full public key from raw SSH key blobs", () => {
const rawKey = makeRawPublicKey("ssh-ed25519");
const result = describeHostKey(rawKey);
assert.equal(result.keyType, "ssh-ed25519");
assert.equal(result.publicKey, `ssh-ed25519 ${rawKey.toString("base64")}`);
});
test("classifyHostKey warns when a known host fingerprint changes", () => {
const result = classifyHostKey({
knownHosts: [{
id: "kh-1",
hostname: "192.0.2.10",
port: 22,
keyType: "ssh-ed25519",
publicKey: "SHA256:old-key",
discoveredAt: 1,
}],
hostname: "192.0.2.10",
port: 22,
keyType: "ssh-ed25519",
fingerprint: "new-key",
});
assert.equal(result.status, "changed");
assert.equal(result.knownHost?.id, "kh-1");
assert.equal(result.expectedFingerprint, "old-key");
});
test("classifyHostKey treats the same hostname on a different port as unknown", () => {
const result = classifyHostKey({
knownHosts: [{
id: "kh-1",
hostname: "switch.local",
port: 2222,
keyType: "ssh-ed25519",
publicKey: "SHA256:trusted-key",
discoveredAt: 1,
}],
hostname: "switch.local",
port: 22,
keyType: "ssh-ed25519",
fingerprint: "trusted-key",
});
assert.equal(result.status, "unknown");
});
test("classifyHostKey reports unknown when only the incoming key type is unknown", () => {
// Without a confident key type from ssh2 we cannot tell whether this is a
// rotation of the stored key or a brand-new algorithm; force the user back
// through the first-time-trust path rather than scaring them with a
// "fingerprint changed" warning (#972).
const result = classifyHostKey({
knownHosts: [{
id: "kh-1",
hostname: "switch.local",
port: 22,
keyType: "ssh-ed25519",
publicKey: "SHA256:trusted-key",
discoveredAt: 1,
}],
hostname: "switch.local",
port: 22,
keyType: "unknown",
fingerprint: "new-key",
});
assert.equal(result.status, "unknown");
});
test("classifyHostKey reports unknown when the stored record has no key type", () => {
// Legacy / imported records sometimes have an empty or "unknown" keyType.
// Promoting those to "changed" on every connect was the root cause of #972;
// treat them as not-comparable so the user re-confirms cleanly.
const result = classifyHostKey({
knownHosts: [{
id: "kh-1",
hostname: "switch.local",
port: 22,
keyType: "unknown",
publicKey: "SHA256:trusted-key",
discoveredAt: 1,
}],
hostname: "switch.local",
port: 22,
keyType: "ssh-ed25519",
fingerprint: "new-key",
});
assert.equal(result.status, "unknown");
});
test("classifyHostKey reports unknown when the server presents a different key type than any stored record", () => {
// Server with ssh-rsa stored; presents ssh-ed25519 this time. OpenSSH treats
// this as a new key offering, not a rotation; we match that behavior so a
// host with multiple algorithms doesn't spam mismatch warnings on every
// algorithm renegotiation.
const result = classifyHostKey({
knownHosts: [{
id: "kh-rsa",
hostname: "switch.local",
port: 22,
keyType: "ssh-rsa",
publicKey: "SHA256:rsa-key",
discoveredAt: 1,
}],
hostname: "switch.local",
port: 22,
keyType: "ssh-ed25519",
fingerprint: "new-key",
});
assert.equal(result.status, "unknown");
});
test("classifyHostKey prefers exact key type mismatches when a host has multiple keys", () => {
const result = classifyHostKey({
knownHosts: [{
id: "kh-rsa",
hostname: "switch.local",
port: 22,
keyType: "ssh-rsa",
publicKey: "SHA256:rsa-key",
discoveredAt: 1,
}, {
id: "kh-ed25519",
hostname: "switch.local",
port: 22,
keyType: "ssh-ed25519",
publicKey: "SHA256:ed25519-key",
discoveredAt: 2,
}],
hostname: "switch.local",
port: 22,
keyType: "ssh-ed25519",
fingerprint: "new-key",
});
assert.equal(result.status, "changed");
assert.equal(result.knownHost?.id, "kh-ed25519");
});
test("classifyHostKey does not pick an arbitrary known host when incoming key type is unknown", () => {
const result = classifyHostKey({
knownHosts: [{
id: "kh-rsa",
hostname: "switch.local",
port: 22,
keyType: "ssh-rsa",
publicKey: "SHA256:rsa-key",
discoveredAt: 1,
}, {
id: "kh-ed25519",
hostname: "switch.local",
port: 22,
keyType: "ssh-ed25519",
publicKey: "SHA256:ed25519-key",
discoveredAt: 2,
}],
hostname: "switch.local",
port: 22,
keyType: "unknown",
fingerprint: "new-key",
});
assert.equal(result.status, "unknown");
});
test("normalizeFingerprint accepts SHA256-prefixed values", () => {
assert.equal(normalizeFingerprint("SHA256:abc123==="), "abc123");
});
test("createHostVerifier accepts trusted host keys without prompting", async () => {
const rawKey = Buffer.from("trusted server key");
const fingerprint = crypto.createHash("sha256").update(rawKey).digest("base64").replace(/=+$/g, "");
const sent = [];
const sender = {
id: 1,
isDestroyed: () => false,
send: (channel, payload) => sent.push({ channel, payload }),
};
const verifier = createHostVerifier({
sender,
sessionId: "session-1",
hostname: "switch.local",
port: 22,
knownHosts: [{
id: "kh-1",
hostname: "switch.local",
port: 22,
keyType: "unknown",
publicKey: `SHA256:${fingerprint}`,
discoveredAt: 1,
}],
});
const accepted = await new Promise((resolve) => verifier(rawKey, resolve));
assert.equal(accepted, true);
assert.deepEqual(sent, []);
});
test("createHostVerifier skips prompts when host key verification is disabled", async () => {
const rawKey = Buffer.from("untrusted server key");
const sent = [];
const sender = {
id: 1,
isDestroyed: () => false,
send: (channel, payload) => sent.push({ channel, payload }),
};
const verifier = createHostVerifier({
sender,
sessionId: "session-1",
hostname: "switch.local",
port: 22,
knownHosts: [],
verifyHostKeys: false,
});
const accepted = await new Promise((resolve) => verifier(rawKey, resolve));
assert.equal(accepted, true);
assert.deepEqual(sent, []);
});
test("createHostVerifier accepts imported full known_hosts public keys without prompting", async () => {
const rawKey = makeRawPublicKey("ssh-ed25519");
const sent = [];
const sender = {
id: 1,
isDestroyed: () => false,
send: (channel, payload) => sent.push({ channel, payload }),
};
const verifier = createHostVerifier({
sender,
sessionId: "session-1",
hostname: "switch.local",
port: 22,
knownHosts: [{
id: "kh-1",
hostname: "switch.local",
port: 22,
keyType: "ssh-ed25519",
publicKey: `ssh-ed25519 ${rawKey.toString("base64")}`,
discoveredAt: 1,
}],
});
const accepted = await new Promise((resolve) => verifier(rawKey, resolve));
assert.equal(accepted, true);
assert.deepEqual(sent, []);
});
test("createHostVerifier prompts for unknown host keys and waits for user response", async () => {
const rawKey = Buffer.from("new server key");
const sent = [];
const sender = {
id: 1,
isDestroyed: () => false,
send: (channel, payload) => sent.push({ channel, payload }),
};
const verifier = createHostVerifier({
sender,
sessionId: "session-1",
hostname: "switch.local",
port: 22,
knownHosts: [],
});
const acceptedPromise = new Promise((resolve) => verifier(rawKey, resolve));
assert.equal(sent.length, 1);
assert.equal(sent[0].channel, "netcatty:host-key:verify");
assert.equal(sent[0].payload.hostname, "switch.local");
assert.equal(sent[0].payload.status, "unknown");
handleResponse({ sender: { id: sender.id } }, {
requestId: sent[0].payload.requestId,
accept: true,
addToKnownHosts: true,
});
assert.equal(await acceptedPromise, true);
});
test("createHostVerifier forwards bootEpoch on host-key prompts", async () => {
const rawKey = Buffer.from("new server key");
const sent = [];
const sender = {
id: 1,
isDestroyed: () => false,
send: (channel, payload) => sent.push({ channel, payload }),
};
const verifier = createHostVerifier({
sender,
sessionId: "session-1",
hostname: "switch.local",
port: 22,
knownHosts: [],
bootEpoch: 7,
});
const acceptedPromise = new Promise((resolve) => verifier(rawKey, resolve));
assert.equal(sent[0].payload.bootEpoch, 7);
handleResponse({ sender: { id: sender.id } }, {
requestId: sent[0].payload.requestId,
accept: false,
});
assert.equal(await acceptedPromise, false);
});
test("createHostVerifier includes existing known host details when a key changes", async () => {
// A well-formed wire blob so `describeHostKey` can recover keyType =
// "ssh-ed25519"; that triggers the strict (host, port, type) mismatch
// branch with a stored record of the same type but different fingerprint.
const rawKey = makeRawPublicKey("ssh-ed25519", "changed server key");
const sent = [];
const sender = {
id: 1,
isDestroyed: () => false,
send: (channel, payload) => sent.push({ channel, payload }),
};
const verifier = createHostVerifier({
sender,
sessionId: "session-1",
hostname: "switch.local",
port: 22,
knownHosts: [{
id: "kh-1",
hostname: "switch.local",
port: 22,
keyType: "ssh-ed25519",
publicKey: "SHA256:old-key",
fingerprint: "old-key",
discoveredAt: 1,
}],
});
const acceptedPromise = new Promise((resolve) => verifier(rawKey, resolve));
assert.equal(sent.length, 1);
assert.equal(sent[0].channel, "netcatty:host-key:verify");
assert.equal(sent[0].payload.status, "changed");
assert.equal(sent[0].payload.knownHostId, "kh-1");
assert.equal(sent[0].payload.knownFingerprint, "old-key");
handleResponse({ sender: { id: sender.id } }, {
requestId: sent[0].payload.requestId,
accept: true,
addToKnownHosts: true,
});
assert.equal(await acceptedPromise, true);
});