Files
Netcatty/electron/bridges/terminalWorkerProxyRegistration.test.cjs
T
75452055ae fix(ssh): harden macOS Local Network TCC trigger (#2673) (#2766)
* fix(ssh): harden macOS Local Network TCC trigger for LAN SSH

Replace the main-process TCP probe with Apple's TN3179 UDP discard-port
connect, resolve vault hostnames/.local before probing, hold the socket
briefly so TCC can present the alert, and annotate EHOSTUNREACH errors
that embed LAN IPs even when the host was stored as a DNS name.

Addresses recurring #2673 / #2663 / #1040 Local Network silent failures.

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

* fix(ssh): address Codex Local Network review findings

Clear the UDP connect safety timer once connected so a slow .local
resolve cannot truncate the TCC hold. Mark worker-forwarded start
payloads after the main-process probe so utilityProcess skips a second
hold. Keep the new test comments ASCII-only.

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

* fix(ssh): bound Local Network DNS lookup by probe timeout

Codex noted that hostname resolution before the UDP probe had no
deadline, so a hung DNS lookup could stall every non-literal SSH start.
Race the lookup against the existing probe timeout and skip probing when
it expires so the normal SSH dial can proceed.

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

* fix(ssh): tighten Local Network error address parsing

Ignore LAN bind addresses in Node's "- Local (ip:port)" suffix so public
SSH failures are not mislabeled as Local Network denials. Also extract
embedded IPv6 ULA/link-local remotes from unreachable errors.

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

* fix(ssh): only hint Local Network when the first hop is LAN

A .local final host reached through a public proxy or jump must not force
the macOS Local Network hint when the failing dial never touched LAN.
Annotate from the first hop and remote error address instead.

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

* fix(ssh): probe jump-level proxy as the first Local Network hop

Match sshBridge first-hop wiring: a usable jump.proxy overrides the
session proxy and the jump hostname. Otherwise a .local jump behind a
public proxy probes the wrong host, and a LAN proxy in front of a public
jump is missed.

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

* fix(ssh): retry .local Local Network probes over udp6

IPv6-only mDNS hosts never resolve on a udp4 socket, so the TCC trigger
could miss them. For unresolved hostnames try udp4 then udp6.

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

* fix(ssh): share Local Network probe timeout across UDP families

udp4 then udp6 fallbacks for .local hosts now inherit one overall
deadline instead of restarting DEFAULT_PROBE_TIMEOUT_MS per family.

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

* chore: re-request Codex review after unanswered pass

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

* fix(ssh): skip Local Network probe for ProxyCommand hops

Treat an active jump/session ProxyCommand as a terminal first hop so we
do not fall through to a LAN hostname and spuriously prompt. Also share
one wall-clock deadline across DNS resolution and UDP family attempts.

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

* test(ssh): tolerate residual Local Network probe budgets in hold test

Shared-deadline math can arm the safety timer at 499ms instead of exactly
500ms. Identify that timer by being larger than the hold, not by equality.

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

* fix(macos): preserve ProxyCommand skip during Local Network error annotation

Keep ProxyCommand's skipProbe sentinel through annotateMacLocalNetworkErrorMessage
so .local hop names do not get a false Local Network hint when TCP probing was
intentionally skipped. Split residual UDP budget evenly across remaining address
families so dual-stack and .local IPv6 attempts still get time.

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

* test(ssh): fire residual Local Network safety timers in hang probe test

Shared-deadline math arms the UDP safety timer with a residual budget
(e.g. 2999ms) rather than the exact DEFAULT_PROBE_TIMEOUT_MS constant,
so matching only the constant left the hang-socket test unable to settle.

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

* fix(macos): never hint Local Network for ProxyCommand errors

skipProbe means an external ProxyCommand owns the dial. Do not append the
Netcatty Local Network TCC hint from child-process LAN addresses in the
error text — that guidance would send users to enable Netcatty for a
connection Electron never made.

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

* fix(macos): ignore downstream LAN addresses behind public first hops

When a public proxy/jump owns the first dial, unreachable addresses embedded
in the error often name a private host the remote side tried to reach. Only
use those addresses as Local Network evidence when they identify the local
first-hop dial.

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

* fix(macos): keep LAN hints for private DNS first hops and ASCII comments

Treat common private DNS suffixes (e.g. bastion.lan) as Local Network
evidence so hostname-based first hops still get guidance when Node reports
the resolved IP. Replace em dashes and arrows in this module with ASCII.

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

* fix(macos): keep Local Network hints for unqualified first hops

Single-label jump/proxy names such as "dev-viet" resolve to LAN IPs that
appear in Node unreachable errors. Treat those hostnames as local-side
evidence so annotation still guides users to macOS Local Network settings.

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

* fix(macos): carry resolved first-hop LAN addresses into error annotation

ensureAccess remembers the LAN IP it probed for a hostname first hop and
forwards it on the worker start payload. Annotation uses that resolved
address so private split-DNS FQDNs like bastion.example.com still get
Local Network guidance without treating public proxies as LAN.

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:02:54 +08:00

363 lines
12 KiB
JavaScript

const assert = require("node:assert/strict");
const test = require("node:test");
const terminalBridge = require("./terminalBridge.cjs");
const sshBridge = require("./sshBridge.cjs");
const keyboardInteractiveHandler = require("./keyboardInteractiveHandler.cjs");
const passphraseHandler = require("./passphraseHandler.cjs");
const hostKeyVerifier = require("./hostKeyVerifier.cjs");
const sftpBridge = require("./sftpBridge.cjs");
const transferBridge = require("./transferBridge.cjs");
const compressUploadBridge = require("./compressUploadBridge.cjs");
const fileWatcherBridge = require("./fileWatcherBridge.cjs");
const { createSystemManagerBridge } = require("./systemManagerBridge.cjs");
function createFakeIpcMain() {
return {
handlers: new Map(),
listeners: new Map(),
handle(channel, handler) {
this.handlers.set(channel, handler);
},
on(channel, listener) {
this.listeners.set(channel, listener);
},
};
}
function createFakeWorkerManager() {
const requests = [];
const sends = [];
return {
requests,
sends,
request(channel, payload, options) {
requests.push({ channel, payload, options });
return Promise.resolve({ ok: true, channel });
},
send(channel, payload, options) {
sends.push({ channel, payload, options });
},
};
}
const fakeEvent = { sender: { id: 42 } };
test("terminal worker mode proxies all terminal starts and control commands", async () => {
const ipcMain = createFakeIpcMain();
const terminalWorkerManager = createFakeWorkerManager();
terminalBridge.registerHandlers(ipcMain, { terminalWorkerManager });
for (const channel of [
"netcatty:local:start",
"netcatty:telnet:start",
"netcatty:mosh:start",
"netcatty:et:start",
"netcatty:serial:start",
"netcatty:close:await",
]) {
assert.equal(ipcMain.handlers.has(channel), true, `${channel} should be proxied as a request`);
await ipcMain.handlers.get(channel)(fakeEvent, { sessionId: channel });
}
for (const channel of [
"netcatty:write",
"netcatty:interrupt",
"netcatty:resize",
"netcatty:pty:clear",
"netcatty:flow",
"netcatty:flow:ack",
"netcatty:close",
]) {
assert.equal(ipcMain.listeners.has(channel), true, `${channel} should be proxied as a send`);
ipcMain.listeners.get(channel)(fakeEvent, { sessionId: channel });
}
assert.deepEqual(
terminalWorkerManager.requests.map((entry) => entry.channel),
[
"netcatty:local:start",
"netcatty:telnet:start",
"netcatty:mosh:start",
"netcatty:et:start",
"netcatty:serial:start",
"netcatty:close:await",
],
);
assert.deepEqual(
terminalWorkerManager.sends.map((entry) => entry.channel),
[
"netcatty:write",
"netcatty:interrupt",
"netcatty:resize",
"netcatty:pty:clear",
"netcatty:flow",
"netcatty:flow:ack",
"netcatty:close",
],
);
});
test("terminal worker mode proxies SSH session and remote helper requests", async () => {
const ipcMain = createFakeIpcMain();
const terminalWorkerManager = createFakeWorkerManager();
sshBridge.registerHandlers(ipcMain, { terminalWorkerManager });
for (const channel of [
"netcatty:start",
"netcatty:ssh:exec",
"netcatty:ssh:pwd",
"netcatty:ssh:remoteInfo",
"netcatty:ssh:distroInfo",
"netcatty:ssh:readRemoteHistory",
"netcatty:ssh:listdir",
"netcatty:ssh:stats",
"netcatty:ssh:setEncoding",
]) {
assert.equal(ipcMain.handlers.has(channel), true, `${channel} should be proxied`);
await ipcMain.handlers.get(channel)(fakeEvent, { sessionId: "ssh-1" });
}
assert.deepEqual(
terminalWorkerManager.requests.map((entry) => entry.channel),
[
"netcatty:start",
"netcatty:ssh:exec",
"netcatty:ssh:pwd",
"netcatty:ssh:remoteInfo",
"netcatty:ssh:distroInfo",
"netcatty:ssh:readRemoteHistory",
"netcatty:ssh:listdir",
"netcatty:ssh:stats",
"netcatty:ssh:setEncoding",
],
);
assert.equal(
terminalWorkerManager.requests[0].payload._macLocalNetworkMainProbed,
true,
"worker start payload should skip a second Local Network probe",
);
});
test("terminal worker mode keeps main-process keyboard-interactive responses in the main process", async () => {
const ipcMain = createFakeIpcMain();
const terminalWorkerManager = createFakeWorkerManager();
const requestId = keyboardInteractiveHandler.generateRequestId("port-forward");
let receivedResponses = null;
keyboardInteractiveHandler.storeRequest(
requestId,
(responses) => {
receivedResponses = responses;
},
fakeEvent.sender.id,
"tunnel-1",
);
sshBridge.registerHandlers(ipcMain, { terminalWorkerManager });
const result = await ipcMain.handlers.get("netcatty:keyboard-interactive:respond")(
fakeEvent,
{ requestId, responses: ["123456"], cancelled: false },
);
const remainedPending = keyboardInteractiveHandler.getRequests().has(requestId);
if (remainedPending) {
keyboardInteractiveHandler.handleResponse(fakeEvent, {
requestId,
responses: [],
cancelled: true,
});
}
assert.deepEqual(result, { success: true });
assert.deepEqual(receivedResponses, ["123456"]);
assert.equal(remainedPending, false);
assert.equal(terminalWorkerManager.requests.length, 0);
});
test("terminal worker mode keeps main-process passphrase responses in the main process", async () => {
const ipcMain = createFakeIpcMain();
const terminalWorkerManager = createFakeWorkerManager();
const sent = [];
const sender = {
id: fakeEvent.sender.id,
isDestroyed: () => false,
send: (channel, payload) => sent.push({ channel, payload }),
};
const responsePromise = passphraseHandler.requestPassphrase(
sender,
"/tmp/test-key",
"test-key",
"example.com",
false,
);
const requestId = sent[0].payload.requestId;
sshBridge.registerHandlers(ipcMain, { terminalWorkerManager });
const wrongResult = await ipcMain.handlers.get("netcatty:passphrase:respond")(
{ sender: { id: fakeEvent.sender.id + 1 } },
{ requestId, passphrase: "stolen", cancelled: false },
);
assert.deepEqual(wrongResult, { success: false, error: "Wrong sender" });
assert.equal(passphraseHandler.getRequests().has(requestId), true);
const result = await ipcMain.handlers.get("netcatty:passphrase:respond")(
fakeEvent,
{ requestId, passphrase: "secret", cancelled: false },
);
assert.deepEqual(result, { success: true });
assert.deepEqual(await responsePromise, { passphrase: "secret" });
assert.equal(passphraseHandler.getRequests().has(requestId), false);
assert.equal(terminalWorkerManager.requests.length, 0);
});
test("terminal worker mode keeps main-process host-key responses in the main process", async () => {
const ipcMain = createFakeIpcMain();
const terminalWorkerManager = createFakeWorkerManager();
const sent = [];
const sender = {
id: fakeEvent.sender.id,
isDestroyed: () => false,
send: (channel, payload) => sent.push({ channel, payload }),
};
const responsePromise = hostKeyVerifier.requestHostKeyVerification(sender, {
sessionId: "tunnel-1",
hostname: "example.com",
port: 22,
status: "unknown",
});
const requestId = sent[0].payload.requestId;
sshBridge.registerHandlers(ipcMain, { terminalWorkerManager });
const wrongResult = await ipcMain.handlers.get("netcatty:host-key:respond")(
{ sender: { id: fakeEvent.sender.id + 1 } },
{ requestId, accept: true, addToKnownHosts: false },
);
assert.deepEqual(wrongResult, { success: false, error: "Wrong sender" });
assert.equal(hostKeyVerifier.getRequests().has(requestId), true);
const result = await ipcMain.handlers.get("netcatty:host-key:respond")(
fakeEvent,
{ requestId, accept: true, addToKnownHosts: false },
);
assert.deepEqual(result, { success: true });
assert.deepEqual(await responsePromise, { accept: true, addToKnownHosts: false });
assert.equal(hostKeyVerifier.getRequests().has(requestId), false);
assert.equal(terminalWorkerManager.requests.length, 0);
});
test("terminal worker mode forwards worker-owned authentication responses", async () => {
const ipcMain = createFakeIpcMain();
const terminalWorkerManager = createFakeWorkerManager();
sshBridge.registerHandlers(ipcMain, { terminalWorkerManager });
for (const channel of [
"netcatty:keyboard-interactive:respond",
"netcatty:passphrase:respond",
"netcatty:host-key:respond",
]) {
const result = await ipcMain.handlers.get(channel)(fakeEvent, { requestId: `worker-${channel}` });
assert.deepEqual(result, { ok: true, channel });
}
assert.deepEqual(
terminalWorkerManager.requests.map((entry) => entry.channel),
[
"netcatty:keyboard-interactive:respond",
"netcatty:passphrase:respond",
"netcatty:host-key:respond",
],
);
});
test("terminal worker mode proxies SFTP and surrounding file operations", async () => {
const ipcMain = createFakeIpcMain();
const terminalWorkerManager = createFakeWorkerManager();
sftpBridge.registerHandlers(ipcMain, { terminalWorkerManager });
transferBridge.registerHandlers(ipcMain, { terminalWorkerManager });
compressUploadBridge.registerHandlers(ipcMain, { terminalWorkerManager });
fileWatcherBridge.registerHandlers(ipcMain, { terminalWorkerManager });
for (const channel of [
"netcatty:sftp:openForSession",
"netcatty:sftp:list",
"netcatty:sftp:write",
"netcatty:sftp:downloadToLocal",
"netcatty:sftp:uploadLocal",
"netcatty:sftp:close",
"netcatty:transfer:start",
"netcatty:transfer:retain-sftp-session",
"netcatty:transfer:release-sftp-session",
"netcatty:transfer:cancel",
"netcatty:compress:start",
"netcatty:compress:checkSupport",
"netcatty:filewatch:start",
"netcatty:filewatch:registerTempFile",
]) {
assert.equal(ipcMain.handlers.has(channel), true, `${channel} should be proxied`);
await ipcMain.handlers.get(channel)(fakeEvent, { sessionId: "ssh-1", sftpId: "sftp-1" });
}
assert.deepEqual(
terminalWorkerManager.requests.map((entry) => entry.channel),
[
"netcatty:sftp:openForSession",
"netcatty:sftp:list",
"netcatty:sftp:write",
"netcatty:sftp:downloadToLocal",
"netcatty:sftp:uploadLocal",
"netcatty:sftp:close",
"netcatty:transfer:start",
"netcatty:transfer:retain-sftp-session",
"netcatty:transfer:release-sftp-session",
"netcatty:transfer:cancel",
"netcatty:compress:start",
"netcatty:compress:checkSupport",
"netcatty:filewatch:start",
"netcatty:filewatch:registerTempFile",
],
);
});
test("terminal worker mode proxies system management requests", async () => {
const ipcMain = createFakeIpcMain();
const terminalWorkerManager = createFakeWorkerManager();
const systemManagerBridge = createSystemManagerBridge({
getSessions: () => new Map(),
execOnEtSession: () => {},
ensureMoshStatsConnection: () => {},
process,
});
systemManagerBridge.registerHandlers(ipcMain, { terminalWorkerManager });
for (const channel of [
"netcatty:system:probeCapabilities",
"netcatty:system:listProcesses",
"netcatty:system:setupOsc7Tracking",
"netcatty:system:listTmuxSessions",
"netcatty:system:listDockerContainers",
"netcatty:system:listAccelerators",
]) {
assert.equal(ipcMain.handlers.has(channel), true, `${channel} should be proxied`);
await ipcMain.handlers.get(channel)(fakeEvent, { sessionId: "ssh-1" });
}
assert.deepEqual(
terminalWorkerManager.requests.map((entry) => entry.channel),
[
"netcatty:system:probeCapabilities",
"netcatty:system:listProcesses",
"netcatty:system:setupOsc7Tracking",
"netcatty:system:listTmuxSessions",
"netcatty:system:listDockerContainers",
"netcatty:system:listAccelerators",
],
);
});