Files
Netcatty/electron/bridges/sshBridge/startSession.testConnection.test.cjs
T
cd7f182401 feat(ssh): host TOTP with QR scan and MFA auto-fill (#3323) (#3788)
* feat(ssh): add per-host TOTP with QR scan and MFA auto-fill

Store an optional otpauth TOTP secret on the host, encrypt and sync it
like a password, and auto-submit it once when a keyboard-interactive
prompt matches JumpServer or PAM TOTP text.

Closes #3323
Refs #3415

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

* fix(ssh): address Codex TOTP review findings

Reset authenticator editor state when the host changes, match custom
prompts with RE2, offer keyboard-interactive during connection tests
when TOTP is configured, and drop the secret when a host becomes a plugin.

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

* fix(ssh): fill TOTP from the active prompt and ship re2js

Attach the connection's otpauth URI to the keyboard-interactive dialog
so Fill current code uses that attempt, including unsaved hosts. Move
re2js into production dependencies so packaged builds can match custom prompts.

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

* fix(ssh): ship the shared TOTP runtime in packaged builds

electron-builder allowlists domain CommonJS modules individually, and
sshAuthHelper requires domain/totp.shared.cjs at load.

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

* fix(ssh): save a pasted TOTP secret and ignore stale QR imports

Host save waits for the authenticator draft to validate before writing
the host. QR import completions from the previous host no longer change
busy state or errors on the newly selected host.

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

* test(host): ignore TOTP copy in the proxy command summary check

The assertion was matching the word secret in the authenticator UI.
It now checks that the ProxyCommand token itself is not rendered.

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

* feat(ssh): simplify host TOTP setup and type codes into the terminal

Move authenticator setup into a dialog so the host form keeps a single setting row, show keyboard-interactive prompts as field labels, and add a terminal context-menu action that types the current code without Enter.

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

* fix(ssh): keep TOTP fill inside the auth dialog

Remove the terminal context-menu action. Offer the verification-code button on each non-password prompt, highlight OTP prompts, and never write the code into the password field.

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

* fix(ssh): keep MFA instructions and scan every screen

Show keyboard-interactive name and instructions as plain text when they are not already the field label, and scan each unmatched desktop source once instead of repeating the first display.

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

* fix(ssh): keep multiline MFA prompt directions

Show lines before the last keyboard-interactive prompt as plain-text guidance, and keep that last line as the field label.

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

* fix(ssh): scan TOTP QR codes at each display's full size

Request a thumbnail as wide as the widest display and as tall as the tallest, so a portrait screen is not scaled into a landscape frame.

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

* fix(ssh): keep TOTP fill off menu prompts

Judge the fill action from the last prompt line and the shared menu, SMS, and confirmation exclusion list. Use a secondary button on the label row, and simplify the host authenticator row.

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-10-20 19:22:05 +08:00

403 lines
13 KiB
JavaScript

"use strict";
const test = require("node:test");
const assert = require("node:assert/strict");
const { EventEmitter } = require("node:events");
const { createStartSessionApi, sendConnectionTestResult, cancelTestConnection } = require("./startSession.cjs");
const MUTED_CONSOLE = {
log() {},
error() {},
warn() {},
info() {},
};
function createHarness({ onConnect, chainDial, ctxOverrides } = {}) {
const sent = [];
const calls = {
connectOptions: null,
ends: 0,
destroys: 0,
defaultKeyScans: 0,
};
const sender = {
send: (channel, payload) => {
sent.push({ channel, payload });
},
isDestroyed: () => false,
};
class MockSSHClient extends EventEmitter {
connect(options) {
calls.connectOptions = options;
if (onConnect) onConnect(this);
}
end() {
calls.ends += 1;
}
destroy() {
calls.destroys += 1;
}
}
const sessions = new Map();
const ctx = {
randomUUID: () => "session-test",
SSHClient: MockSSHClient,
createSshDiagnosticLogger: () => () => {},
buildConnectionReuseEndpoint: () => "endpoint",
resolveConnectionKeepalivePolicy: () => ({ keepaliveIntervalMs: 0, keepaliveCountMax: 0 }),
buildAlgorithms: () => undefined,
attachSshDebugLogger: () => {},
logSshAlgorithms: () => {},
hostKeyVerifier: { createHostVerifier: () => (_rawKey, callback) => callback(true) },
findAllDefaultPrivateKeys: async () => {
calls.defaultKeyScans += 1;
return [];
},
isPasswordProvided: () => true,
hasUserConfiguredKey: () => false,
getCachedAuthMethod: () => null,
setCachedAuthMethod: () => {},
clearCachedAuthMethod: () => {},
createAuthPhase: () => ({}),
markAuthPhasePartialSuccess: () => {},
shouldSkipKiPasswordAutoFill: () => false,
createKeyboardInteractiveHandler: () => () => {},
createOrderedStringAuthHandler: () => () => {},
getAvailableAgentSocket: async () => null,
getAvailableForwardingAgentSocket: async () => null,
prepareSystemSshAgentForAuth: async () => null,
loadFirstIdentityFileForAuth: async () => null,
preparePrivateKeyForAuth: async () => null,
connectThroughChain: chainDial ?? (async () => {
throw new Error("unexpected chain connect");
}),
createProxySocket: async () => {
throw new Error("unexpected proxy connect");
},
enableSshNoDelay: () => {},
enableTcpNoDelay: () => {},
quoteShellArg: (value) => value,
console: MUTED_CONSOLE,
sessions,
safeSend: () => {},
electronModule: { webContents: { fromId: () => null } },
sessionLogStreamManager: { stopStream: () => {} },
closeTerminalOutputSession: () => {},
sessionEncodings: new Map(),
sessionDecoders: new Map(),
...(ctxOverrides || {}),
};
const api = createStartSessionApi(ctx);
return { api, sent, calls, sender };
}
function baseOptions() {
return {
sessionId: "session-test",
hostname: "example.test",
port: 22,
username: "alice",
authMethod: "password",
password: "secret",
testMode: true,
reuseTransport: false,
};
}
test("sendConnectionTestResult emits a one-shot success payload", () => {
const sent = [];
const sender = {
isDestroyed: () => false,
send: (channel, payload) => sent.push({ channel, payload }),
};
sendConnectionTestResult(sender, "session-1", true);
assert.deepEqual(sent, [
{ channel: "netcatty:test:result", payload: { sessionId: "session-1", ok: true } },
]);
});
test("sendConnectionTestResult ignores destroyed senders", () => {
const sent = [];
const sender = {
isDestroyed: () => true,
send: () => sent.push("should-not-fire"),
};
sendConnectionTestResult(sender, "session-1", false, "boom");
assert.deepEqual(sent, []);
});
test("test mode resolves success on authentication without opening a shell", async () => {
const { api, sent, calls, sender } = createHarness({
onConnect: (conn) => {
queueMicrotask(() => conn.emit("ready"));
},
});
const result = await api.startSSHSession({ sender }, baseOptions());
assert.equal(result.sessionId, "session-test");
assert.equal(result.testResult, "connected");
const resultEvent = sent.find((entry) => entry.channel === "netcatty:test:result");
assert.ok(resultEvent, "netcatty:test:result should be emitted");
assert.deepEqual(resultEvent.payload, { sessionId: "session-test", ok: true });
assert.equal(calls.ends, 1, "connection should be torn down after success");
});
test("test mode does not emit a terminal exit on success", async () => {
const { api, sent, sender } = createHarness({
onConnect: (conn) => {
queueMicrotask(() => conn.emit("ready"));
},
});
await api.startSSHSession({ sender }, baseOptions());
assert.equal(
sent.some((entry) => entry.channel === "netcatty:exit"),
false,
"test success must not emit a terminal session exit",
);
});
test("test mode reports failure through netcatty:test:result", async () => {
const { api, sent, sender } = createHarness({
onConnect: (conn) => {
queueMicrotask(() => conn.emit("error", new Error("boom")));
},
});
await assert.rejects(
() => api.startSSHSession({ sender }, baseOptions()),
/boom/,
);
const resultEvent = sent.find((entry) => entry.channel === "netcatty:test:result");
assert.ok(resultEvent, "netcatty:test:result should be emitted on failure");
assert.equal(resultEvent.payload.sessionId, "session-test");
assert.equal(resultEvent.payload.ok, false);
assert.equal(typeof resultEvent.payload.error, "string");
assert.ok(resultEvent.payload.error.length > 0);
});
test("test mode reports an unexpected close as failure", async () => {
const { api, sent, sender } = createHarness({
onConnect: (conn) => {
queueMicrotask(() => conn.emit("close"));
},
});
await assert.rejects(
() => api.startSSHSession({ sender }, baseOptions()),
/closed unexpectedly/,
);
const resultEvent = sent.find((entry) => entry.channel === "netcatty:test:result");
assert.ok(resultEvent);
assert.equal(resultEvent.payload.ok, false);
});
test("cancelTestConnection ends an in-flight test transport", async () => {
const { api, calls, sender } = createHarness({
onConnect: () => {
// Leave the dial pending (no ready/error/close).
},
});
void api.startSSHSession({ sender }, baseOptions());
// Let the async body reach conn.connect() + transport registration.
await new Promise((resolve) => setTimeout(resolve, 0));
const result = cancelTestConnection("session-test");
assert.equal(result.success, true);
assert.ok(calls.ends >= 1, "cancelTestConnection should end the SSH client");
});
test("cancelTestConnection reports unknown session ids", () => {
assert.deepEqual(cancelTestConnection("nope"), {
success: false,
error: "Test connection not found",
});
});
test("cancelTestConnection ends an in-flight chain hop registered before the dial", async () => {
const hopConns = [];
const { api, sender } = createHarness({
chainDial: (_event, options) => {
const conn = new EventEmitter();
conn.ended = false;
conn.destroyed = false;
conn.end = () => { conn.ended = true; };
conn.destroy = () => { conn.destroyed = true; };
hopConns.push(conn);
if (options._tunnelRef) {
options._tunnelRef.pendingConn = conn;
options._tunnelRef.chainConnections = options._connectionsRef || [];
(options._connectionsRef || []).push(conn);
}
// Never resolves — simulates a slow/unreachable bastion.
return new Promise(() => {});
},
});
void api.startSSHSession({ sender }, {
...baseOptions(),
jumpHosts: [
{ hostname: "jump.example.test", port: 22, username: "root", password: "jump-pass", authMethod: "password" },
],
});
// Let the async body reach connectThroughChain and register the hop.
await new Promise((resolve) => setTimeout(resolve, 0));
const result = cancelTestConnection("session-test");
assert.equal(result.success, true);
assert.ok(hopConns.length >= 1, "chain dial should have registered a hop conn");
assert.ok(hopConns[0].ended || hopConns[0].destroyed, "cancel should end the in-flight hop conn");
});
test("test mode pins authHandler to a minimal method list", async () => {
const { api, calls, sender } = createHarness({
onConnect: (conn) => {
queueMicrotask(() => conn.emit("ready"));
},
});
await api.startSSHSession({ sender }, baseOptions());
assert.deepEqual(calls.connectOptions.authHandler, ["password", "keyboard-interactive"]);
});
function keyOnlyHarness() {
return createHarness({
onConnect: (conn) => {
queueMicrotask(() => conn.emit("ready"));
},
ctxOverrides: {
isPasswordProvided: (value) => typeof value === "string" && value.length > 0,
preparePrivateKeyForAuth: async ({ privateKey }) => ({ privateKey }),
},
});
}
function keyOnlyOptions(extra = {}) {
const { password: _password, ...rest } = baseOptions();
return { ...rest, authMethod: "key", privateKey: "PRIVATE KEY", ...extra };
}
test("test mode includes keyboard-interactive for key-only MFA hosts", async () => {
const { api, calls, sender } = keyOnlyHarness();
await api.startSSHSession({ sender }, keyOnlyOptions({ requiresMfa: true }));
assert.deepEqual(calls.connectOptions.authHandler, ["publickey", "keyboard-interactive"]);
});
test("test mode keeps key-only non-MFA hosts on the single key credential", async () => {
const { api, calls, sender } = keyOnlyHarness();
await api.startSSHSession({ sender }, keyOnlyOptions());
assert.deepEqual(calls.connectOptions.authHandler, ["publickey"]);
});
test("test mode includes keyboard-interactive for key-only hosts with TOTP", async () => {
const { api, calls, sender } = keyOnlyHarness();
await api.startSSHSession({ sender }, keyOnlyOptions({
totp: { uri: "otpauth://totp/Example:root?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Example" },
}));
assert.deepEqual(calls.connectOptions.authHandler, ["publickey", "keyboard-interactive"]);
});
test("test mode ignores an encrypted TOTP placeholder", async () => {
const { api, calls, sender } = keyOnlyHarness();
await api.startSSHSession({ sender }, keyOnlyOptions({
totp: { uri: "enc:v1:placeholder" },
}));
assert.deepEqual(calls.connectOptions.authHandler, ["publickey"]);
});
test("test mode skips the raw password method for password MFA hosts", async () => {
const { api, calls, sender } = createHarness({
onConnect: (conn) => {
queueMicrotask(() => conn.emit("ready"));
},
});
await api.startSSHSession({ sender }, { ...baseOptions(), requiresMfa: true });
assert.deepEqual(calls.connectOptions.authHandler, ["keyboard-interactive"]);
});
function jumpOptions(extra = {}) {
return {
...baseOptions(),
jumpHosts: [
{ hostname: "jump.example.test", port: 22, username: "root", authMethod: "password" },
],
...extra,
};
}
function capturingChainDial(captured) {
return async (_event, options) => {
captured.scope = options._keyboardInteractiveScope;
return { socket: new EventEmitter(), connections: [] };
};
}
test("test mode routes jump-host keyboard-interactive prompts through the external scope", async () => {
const captured = {};
const { api, sender } = createHarness({
chainDial: capturingChainDial(captured),
onConnect: (conn) => {
queueMicrotask(() => conn.emit("ready"));
},
});
await api.startSSHSession({ sender }, jumpOptions());
assert.equal(captured.scope, "external");
});
test("terminal starts keep the default terminal scope for jump-host prompts", async () => {
const captured = {};
const { api, sender } = createHarness({
chainDial: capturingChainDial(captured),
onConnect: () => {
// Terminal path would open a shell next; the chain options are all we need.
},
});
void api.startSSHSession({ sender }, jumpOptions({ testMode: false, sessionId: "terminal-session" }));
await new Promise((resolve) => setTimeout(resolve, 0));
assert.equal(captured.scope, undefined);
});
test("monitor authentication returns a pooled transport without a shell, terminal session or test-result event", async () => {
const { api, sent, calls, sender } = createHarness({ onConnect: conn => queueMicrotask(() => conn.emit("ready")) });
const result = await api.startSSHSession({ sender }, { ...baseOptions(), testMode: false, _monitorMode: true });
assert.ok(result.transport?.conn);
assert.equal(calls.ends, 0);
assert.equal(typeof result.transport.conn.shell, "undefined", "the harness cannot open a shell");
assert.equal(sent.some(e => e.channel === "netcatty:test:result" || e.channel === "netcatty:exit"), false);
require("../sshConnectionPool.cjs").discardTransport(result.transport);
});