@devries-cameron20 / t3code-1 / commits / 806b539945
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(ssh): deduplicate configured host suggestions (#15630)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

maria committed Oct 20, 2026 at 01:58 UTC 806b53994568e4d575830149d1b964afad169e5c
6 files changed +213 -56
apps/desktop/src/ssh/DesktopSshEnvironment.test.ts
+3 -3
@@ -58,7 +58,7 @@ describe("sshEnvironment", () => {
58 yield* fs.makeDirectory(path.join(sshDir, "config.d"), { recursive: true });
59 yield* fs.writeFileString(
60 path.join(sshDir, "config"),
61 - ["Host devbox", " HostName devbox.example.com", "Include config.d/*.conf", ""].join("\n"),
61 + ["Include config.d/*.conf", "Host devbox", " HostName devbox.example.com", ""].join("\n"),
62 );
63 yield* fs.writeFileString(
64 path.join(sshDir, "config.d", "team.conf"),
@@ -92,7 +92,7 @@ describe("sshEnvironment", () => {
92 },
93 {
94 alias: "devbox",
95 - hostname: "devbox",
95 + hostname: "devbox.example.com",
96 username: null,
97 port: null,
98 source: "ssh-config",
@@ -106,7 +106,7 @@ describe("sshEnvironment", () => {
106 },
107 {
108 alias: "staging",
109 - hostname: "staging",
109 + hostname: "staging.example.com",
110 username: null,
111 port: null,
112 source: "ssh-config",
apps/web/src/components/settings/ConnectionsSettings.tsx
+1 -1
@@ -2198,7 +2198,7 @@ export function ConnectionsSettings() {
2198 const address = formatDesktopSshTarget(target);
2199 return (
2200 !savedDesktopSshEnvironmentKeys.has(target.alias) &&
2201 - !savedDesktopSshEnvironmentKeys.has(address)
2201 + (target.source === "ssh-config" || !savedDesktopSshEnvironmentKeys.has(address))
2202 );
2203 });
2204 const filteredDiscoveredSshHosts = filterDiscoveredSshHosts(
apps/web/src/state/desktopSshHosts.test.ts
+2 -1
@@ -87,8 +87,9 @@ describe("filterDiscoveredSshHosts", () => {
87 ]);
88 });
89
90 - it("matches case-insensitively", () => {
90 + it("matches aliases and hostnames case-insensitively", () => {
91 expect(filterDiscoveredSshHosts(suggestions, "PINOT")).toEqual([suggestions[1]]);
92 + expect(filterDiscoveredSshHosts(hosts, "box.LOCAL")).toEqual(hosts);
93 });
94
95 it("returns an empty array when no hosts match", () => {
apps/web/src/state/desktopSshHosts.ts
+4 -1
@@ -18,7 +18,10 @@ export function filterDiscoveredSshHosts(
18 const alias = host.alias.toLowerCase();
19 if (alias.startsWith(normalizedQuery)) {
20 prefixMatches.push(host);
21 - } else if (alias.includes(normalizedQuery)) {
21 + } else if (
22 + alias.includes(normalizedQuery) ||
23 + host.hostname.toLowerCase().includes(normalizedQuery)
24 + ) {
25 substringMatches.push(host);
26 }
27 }
packages/ssh/src/config.test.ts
+104 -9
@@ -19,7 +19,7 @@ function makeTempHomeDir() {
19 }
20
21 describe("ssh config", () => {
22 - it.effect("follows quoted and escaped Include paths like OpenSSH", () =>
22 + it.effect("deduplicates hosts through quoted and escaped Include paths like OpenSSH", () =>
23 Effect.gen(function* () {
24 const fs = yield* FileSystem.FileSystem;
25 const path = yield* Path.Path;
@@ -28,8 +28,14 @@ describe("ssh config", () => {
28 const quotedDir = path.join(homeDir, "quoted dir");
29 yield* fs.makeDirectory(sshDir);
30 yield* fs.makeDirectory(quotedDir);
31 - yield* fs.writeFileString(path.join(quotedDir, "team#1=a.conf"), "Host quoted\n");
32 - yield* fs.writeFileString(path.join(homeDir, "escaped space.conf"), "Host escaped\n");
31 + yield* fs.writeFileString(
32 + path.join(quotedDir, "team#1=a.conf"),
33 + 'Host quoted\n HostName quoted".example.com"\nHost *\n',
34 + );
35 + yield* fs.writeFileString(
36 + path.join(homeDir, "escaped space.conf"),
37 + "Host escaped\n HostName escaped.example.com\nHost *\n",
38 + );
39 yield* fs.writeFileString(
40 path.join(sshDir, "config"),
41 [
@@ -39,10 +45,18 @@ describe("ssh config", () => {
45 ].join("\n"),
46 );
47
48 + yield* fs.writeFileString(
49 + path.join(sshDir, "known_hosts"),
50 + "escaped.example.com ssh-ed25519 AAAA\nquoted.example.com ssh-ed25519 AAAA\n",
51 + );
52 +
53 const hosts = yield* discoverSshHosts({ homeDir });
54 assert.deepEqual(
44 - hosts.map((host) => host.alias),
45 - ["escaped", "quoted"],
55 + hosts.map((host) => [host.alias, host.hostname, host.source]),
56 + [
57 + ["escaped", "escaped.example.com", "ssh-config"],
58 + ["quoted", "quoted.example.com", "ssh-config"],
59 + ],
60 );
61 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
62 );
@@ -57,9 +71,10 @@ describe("ssh config", () => {
71 yield* fs.writeFileString(
72 path.join(sshDir, "config"),
73 [
60 - "Host devbox",
61 - " HostName devbox.example.com",
74 + "Host devbox devbox-admin",
75 + " HostName 'devbox.example.com'",
76 "Host=equalsbox",
77 + "Host *",
78 "Include=config.d/*.conf",
79 "",
80 ].join("\n"),
@@ -77,6 +92,8 @@ describe("ssh config", () => {
92 yield* fs.writeFileString(
93 path.join(sshDir, "known_hosts"),
94 [
95 + "devbox.example.com ssh-ed25519 AAAA",
96 + "staging.example.com ssh-ed25519 AAAA",
97 "known.example.com ssh-ed25519 AAAA",
98 "|1|hashed|entry ssh-ed25519 AAAA",
99 "[bastion.example.com]:2222 ssh-ed25519 AAAA",
@@ -95,7 +112,14 @@ describe("ssh config", () => {
112 },
113 {
114 alias: "devbox",
98 - hostname: "devbox",
115 + hostname: "devbox.example.com",
116 + username: null,
117 + port: null,
118 + source: "ssh-config",
119 + },
120 + {
121 + alias: "devbox-admin",
122 + hostname: "devbox.example.com",
123 username: null,
124 port: null,
125 source: "ssh-config",
@@ -116,7 +140,7 @@ describe("ssh config", () => {
140 },
141 {
142 alias: "staging",
119 - hostname: "staging",
143 + hostname: "staging.example.com",
144 username: null,
145 port: null,
146 source: "ssh-config",
@@ -125,6 +149,77 @@ describe("ssh config", () => {
149 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
150 );
151
152 + it.effect("retains raw targets when included hostnames are inactive or uncertain", () =>
153 + Effect.gen(function* () {
154 + const fs = yield* FileSystem.FileSystem;
155 + const path = yield* Path.Path;
156 + const homeDir = yield* makeTempHomeDir();
157 + const sshDir = path.join(homeDir, ".ssh");
158 + yield* fs.makeDirectory(sshDir, { recursive: true });
159 + yield* fs.writeFileString(
160 + path.join(sshDir, "config"),
161 + [
162 + "Host WORK*",
163 + " HostName case-sensitive.example.com",
164 + "Host work",
165 + "Host dev",
166 + " Include conditional.conf",
167 + "Host prod",
168 + "Host matched",
169 + "Match originalhost matched",
170 + " Include match.conf",
171 + "Host matched",
172 + " HostName fallback.example.com",
173 + "Host bracketed",
174 + " Include bracket-[ab].conf",
175 + " HostName bracket-fallback.example.com",
176 + "",
177 + ].join("\n"),
178 + );
179 + yield* fs.writeFileString(
180 + path.join(sshDir, "conditional.conf"),
181 + "Host prod\n HostName blocked.example.com\n",
182 + );
183 + yield* fs.writeFileString(
184 + path.join(sshDir, "match.conf"),
185 + "Host matched\n HostName match.example.com\n",
186 + );
187 + yield* fs.writeFileString(
188 + path.join(sshDir, "bracket-a.conf"),
189 + "HostName bracket-real.example.com\n",
190 + );
191 + yield* fs.writeFileString(
192 + path.join(sshDir, "known_hosts"),
193 + [
194 + "bracket-real.example.com ssh-ed25519 AAAA",
195 + "bracket-fallback.example.com ssh-ed25519 AAAA",
196 + "blocked.example.com ssh-ed25519 AAAA",
197 + "case-sensitive.example.com ssh-ed25519 AAAA",
198 + "match.example.com ssh-ed25519 AAAA",
199 + "fallback.example.com ssh-ed25519 AAAA",
200 + "",
201 + ].join("\n"),
202 + );
203 +
204 + const hosts = yield* discoverSshHosts({ homeDir });
205 + assert.deepEqual(
206 + hosts.filter((host) => host.source === "known-hosts").map((host) => host.hostname),
207 + [
208 + "blocked.example.com",
209 + "bracket-fallback.example.com",
210 + "bracket-real.example.com",
211 + "case-sensitive.example.com",
212 + "fallback.example.com",
213 + "match.example.com",
214 + ],
215 + );
216 + assert.equal(hosts.find((host) => host.alias === "bracketed")?.hostname, "bracketed");
217 + assert.equal(hosts.find((host) => host.alias === "prod")?.hostname, "prod");
218 + assert.equal(hosts.find((host) => host.alias === "work")?.hostname, "work");
219 + assert.equal(hosts.find((host) => host.alias === "matched")?.hostname, "matched");
220 + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
221 + );
222 +
223 it.effect("parses known_hosts entries without returning hashed hosts", () =>
224 Effect.sync(() => {
225 assert.deepEqual(
packages/ssh/src/config.ts
+99 -41
@@ -14,14 +14,15 @@ const NO_HOSTS: ReadonlyArray<string> = [] as const;
14 // Mirrors OpenSSH readconf: the keyword may be followed by one optional "=",
15 // then the arguments are split like misc.c argv_split() with quotes, the
16 // escapes \\ \" \' and unquoted "\ ", and "#" starting a comment only at
17 -// the start of a token. A line with an unterminated quote is ignored.
18 -function splitDirectiveArgs(line: string): ReadonlyArray<string> {
17 +// the start of a token. Invalid quoting leaves hostname resolution uncertain.
18 +function parseSshConfigLine(line: string) {
19 const match = /^\s*([^\s=]+)\s*=?\s*(.*)$/u.exec(line);
20 if (!match) {
21 - return [];
21 + return null;
22 }
23
24 - const args = [match[1]!];
24 + const directive = match[1]!.toLowerCase();
25 + const args: Array<string> = [];
26 const rest = match[2]!;
27 let token: string | null = null;
28 let quote: string | null = null;
@@ -55,12 +56,12 @@ function splitDirectiveArgs(line: string): ReadonlyArray<string> {
56 }
57 }
58 if (quote !== null) {
58 - return [];
59 + return { directive, args: null };
60 }
61 if (token !== null) {
62 args.push(token);
63 }
63 - return args;
64 + return { directive, args };
65 }
66
67 function expandHomePath(input: string, homeDir: string): string {
@@ -119,68 +120,117 @@ const expandGlob = Effect.fnUntraced(function* (pattern: string) {
120 matchedPaths.push(entryPath);
121 }
122 }
122 - return matchedPaths.toSorted((left, right) => left.localeCompare(right));
123 + return matchedPaths.toSorted();
124 });
125
126 +type HostCondition = ReadonlyArray<string> | null;
127 +
128 +interface HostNameRule {
129 + readonly conditions: ReadonlyArray<HostCondition>;
130 + readonly hostname: string | null;
131 +}
132 +
133 +function matchesHostPatterns(alias: string, patterns: ReadonlyArray<string>): boolean {
134 + let matched = false;
135 + for (const pattern of patterns) {
136 + const negated = pattern.startsWith("!");
137 + const hostPattern = negated ? pattern.slice(1) : pattern;
138 + const matches =
139 + hostPattern === "*" ||
140 + (hasSshPattern(hostPattern) ? globToRegExp(hostPattern).test(alias) : hostPattern === alias);
141 + if (!matches) continue;
142 + if (negated) return false;
143 + matched = true;
144 + }
145 + return matched;
146 +}
147 +
148 +function resolveConfiguredHostname(alias: string, rules: ReadonlyArray<HostNameRule>) {
149 + for (const { conditions, hostname } of rules) {
150 + if (
151 + conditions.some((condition) => condition !== null && !matchesHostPatterns(alias, condition))
152 + ) {
153 + continue;
154 + }
155 + // SSH takes the first value; an uncertain earlier value blocks later fallbacks.
156 + if (conditions.includes(null) || hostname === null) return null;
157 + if (/%(?!h)/u.test(hostname) || hostname.includes("$")) return null;
158 + return hostname.replaceAll("%h", alias);
159 + }
160 + return null;
161 +}
162 +
163 const collectSshConfigAliasesFromFile = Effect.fnUntraced(function* (
164 filePath: string,
127 - visited = new Set<string>(),
165 + visited: Set<string>,
166 homeDir: string,
129 -): Effect.fn.Return<
130 - ReadonlyArray<string>,
131 - PlatformError.PlatformError,
132 - FileSystem.FileSystem | Path.Path
133 -> {
167 + aliases: Set<string>,
168 + hostNameRules: Array<HostNameRule>,
169 + inheritedConditions: ReadonlyArray<HostCondition>,
170 +): Effect.fn.Return<void, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> {
171 const fs = yield* FileSystem.FileSystem;
172 const path = yield* Path.Path;
173 const resolvedPath = path.resolve(filePath);
137 - if (visited.has(resolvedPath) || !(yield* fs.exists(resolvedPath))) {
138 - return NO_HOSTS;
174 + if (visited.has(resolvedPath)) {
175 + // Read each file once, but never reuse its rules under a different Include context.
176 + hostNameRules.push({ conditions: inheritedConditions, hostname: null });
177 + return;
178 }
179 + if (!(yield* fs.exists(resolvedPath))) return;
180 visited.add(resolvedPath);
181
142 - const aliases = new Set<string>();
182 const directory = path.dirname(resolvedPath);
183 const raw = yield* fs.readFileString(resolvedPath);
184 + let condition: HostCondition = ["*"];
185
186 for (const line of raw.split(/\r?\n/u)) {
147 - const [directive = "", ...rawArgs] = splitDirectiveArgs(line);
148 - const normalizedDirective = directive.toLowerCase();
149 - if (normalizedDirective === "include") {
150 - for (const includePattern of rawArgs) {
187 + const parsed = parseSshConfigLine(line);
188 + if (!parsed) continue;
189 + const { directive, args } = parsed;
190 + const conditions = [...inheritedConditions, condition];
191 +
192 + if (directive === "host") {
193 + condition = args;
194 + for (const alias of args ?? []) {
195 + if (alias.length > 0 && !hasSshPattern(alias)) aliases.add(alias);
196 + }
197 + } else if (directive === "match") {
198 + condition = null;
199 + } else if (directive === "hostname") {
200 + hostNameRules.push({ conditions, hostname: args?.length === 1 ? args[0]! : null });
201 + } else if (directive === "include") {
202 + if (args === null) {
203 + hostNameRules.push({ conditions, hostname: null });
204 + continue;
205 + }
206 + for (const includePattern of args) {
207 const resolvedPattern = yield* resolveSshConfigIncludePattern(
208 includePattern,
209 directory,
210 homeDir,
211 );
212 + if (
213 + /%|\$\{|\[/u.test(includePattern) ||
214 + (includePattern.startsWith("~") && !/^~(?=$|\/|\\)/u.test(includePattern)) ||
215 + hasSshPattern(path.dirname(resolvedPattern))
216 + ) {
217 + hostNameRules.push({ conditions, hostname: null });
218 + continue;
219 + }
220 const includedPaths = yield* expandGlob(resolvedPattern);
221 for (const includedPath of includedPaths) {
158 - const includedAliases = yield* collectSshConfigAliasesFromFile(
222 + yield* collectSshConfigAliasesFromFile(
223 includedPath,
224 visited,
225 homeDir,
226 + aliases,
227 + hostNameRules,
228 + conditions,
229 );
163 - for (const alias of includedAliases) {
164 - aliases.add(alias);
165 - }
230 }
231 }
168 - continue;
169 - }
170 -
171 - if (normalizedDirective !== "host") {
172 - continue;
173 - }
174 -
175 - for (const alias of rawArgs) {
176 - if (alias.length === 0 || hasSshPattern(alias)) {
177 - continue;
178 - }
179 - aliases.add(alias);
232 }
233 }
182 -
183 - return [...aliases].toSorted((left, right) => left.localeCompare(right));
234 });
235
236 function normalizeKnownHostsHostname(rawHost: string): string {
@@ -252,18 +302,26 @@ export const discoverSshHosts = Effect.fnUntraced(
302 }
303
304 const sshDirectory = path.join(homeDir, ".ssh");
255 - const configAliases = yield* collectSshConfigAliasesFromFile(
305 + const configAliases = new Set<string>();
306 + const hostNameRules: Array<HostNameRule> = [];
307 + yield* collectSshConfigAliasesFromFile(
308 path.join(sshDirectory, "config"),
309 new Set<string>(),
310 homeDir,
311 + configAliases,
312 + hostNameRules,
313 + [],
314 );
315 const knownHosts = yield* readKnownHostsHostnames(path.join(sshDirectory, "known_hosts"));
316 const discovered = new Map<string, DesktopDiscoveredSshHost>();
317
318 + const configuredHostnames = new Set<string>();
319 for (const alias of configAliases) {
320 + const hostname = resolveConfiguredHostname(alias, hostNameRules);
321 + if (hostname !== null) configuredHostnames.add(hostname.toLowerCase());
322 discovered.set(alias, {
323 alias,
266 - hostname: alias,
324 + hostname: hostname ?? alias,
325 username: null,
326 port: null,
327 source: "ssh-config",
@@ -271,7 +329,7 @@ export const discoverSshHosts = Effect.fnUntraced(
329 }
330
331 for (const hostname of knownHosts) {
274 - if (discovered.has(hostname)) {
332 + if (discovered.has(hostname) || configuredHostnames.has(hostname.toLowerCase())) {
333 continue;
334 }
335 discovered.set(hostname, {