Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Node Explorer: prompt to add nodes to SSH config file for VSCode remotes list #233

Merged
merged 3 commits into from
Sep 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,11 @@
"when": "(view == node-explorer-view && viewItem == peer-root) || (view == node-explorer-view && viewItem == peer-file-explorer-dir-root)",
"group": "2_settings@3"
},
{
"command": "tailscale.node.addToSSHConfig",
"when": "(view == node-explorer-view && viewItem == peer-root) || (view == node-explorer-view && viewItem == peer-file-explorer-dir-root)",
"group": "2_settings@3"
},
{
"command": "tailscale.node.copyIPv4",
"when": "view == node-explorer-view && viewItem == peer-root",
Expand Down Expand Up @@ -331,6 +336,10 @@
"command": "tailscale.node.setRootDir",
"title": "Change root directory"
},
{
"command": "tailscale.node.addToSSHConfig",
"title": "Add to SSH config file"
},
{
"command": "tailscale.openExternal",
"title": "Open External Link"
Expand Down Expand Up @@ -491,5 +500,8 @@
"*.{json,md,yml}": [
"prettier --write"
]
},
"dependencies": {
"ssh-config": "^4.4.0"
}
}
2 changes: 2 additions & 0 deletions src/config-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import * as path from 'path';
interface Host {
user: string;
rootDir: string;
persistToSSHConfig?: boolean;
differentUserFromSSHConfig?: boolean;
}

interface Config {
Expand Down
16 changes: 16 additions & 0 deletions src/node-explorer-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { getUsername } from './utils/host';
import { FileSystemProvider } from './filesystem-provider';
import { trimSuffix } from './utils';
import { EXTENSION_NS } from './constants';
import { addToSSHConfig, syncSSHConfig } from './utils/sshconfig';

/**
* Anatomy of the TreeView
Expand Down Expand Up @@ -52,6 +53,7 @@ export class NodeExplorerProvider
this.registerRenameCommand();
this.registerOpenNodeDetailsCommand();
this.registerOpenRemoteCodeCommand();
this.registerAddToSSHConfigCommand();
this.registerOpenTerminalCommand();
this.registerRefresh();
this.registerOpenDocsLink();
Expand Down Expand Up @@ -620,6 +622,10 @@ export class NodeExplorerProvider
async (node: PeerRoot | FileExplorer) => {
const { addr, path } = extractAddrAndPath(node);

if (addr && this.configManager.config.hosts?.[addr].persistToSSHConfig !== false) {
await syncSSHConfig(addr, this.configManager);
}

if (node instanceof PeerRoot && addr) {
vscode.commands.executeCommand('vscode.newWindow', {
remoteAuthority: `ssh-remote+${addr}`,
Expand All @@ -640,6 +646,16 @@ export class NodeExplorerProvider
);
}

registerAddToSSHConfigCommand() {
vscode.commands.registerCommand('tailscale.node.addToSSHConfig', async (node: PeerRoot) => {
addToSSHConfig(
this.configManager,
node.Address,
getUsername(this.configManager, node.Address)
);
});
}

registerOpenNodeDetailsCommand() {
vscode.commands.registerCommand('tailscale.node.openDetailsLink', async (node: PeerRoot) => {
vscode.env.openExternal(
Expand Down
122 changes: 122 additions & 0 deletions src/utils/sshconfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import * as vscode from 'vscode';
import * as SSHConfig from 'ssh-config';
import * as os from 'os';
import { ConfigManager } from '../config-manager';
import { getUsername } from './host';

function sshConfigFilePath() {
const filePath = vscode.workspace.getConfiguration('remote').get<string>('SSH.configFile');
return filePath
? vscode.Uri.file(filePath)
: vscode.Uri.joinPath(vscode.Uri.file(os.homedir()), './.ssh/config');
}

async function readSSHConfig() {
const configStr = await vscode.workspace.fs
.readFile(sshConfigFilePath())
.then((a) => Buffer.from(a).toString('utf-8'));

const config = SSHConfig.parse(configStr);

const hosts = config
// find all the hosts
.filter((line): line is SSHConfig.Directive => {
return (line as SSHConfig.Directive).param === 'Host';
})
// get all the host names
.flatMap((hostDirective) => hostDirective.value)
// get their effective computed option values
// (this is necessary because a host might have multiple matching Host blocks,
// and the effective options are computed by combining all of them)
.map((h) => config.compute(h));

return { config, hosts };
}

export async function addToSSHConfig(configManager: ConfigManager, HostName: string, User: string) {
const { config, hosts } = await readSSHConfig();
const matchingHosts = hosts.filter((h) => h.HostName === HostName);
if (matchingHosts.length === 0) {
config.append({ Host: HostName, User, HostName });
} else {
const h = matchingHosts[0];
const cfgHost = typeof h.Host === 'string' ? h.Host : h.Host[0];
const section = config.find({ Host: cfgHost });
if (section && 'config' in section) {
let added = false;
for (const line of section.config) {
if (line.type === SSHConfig.LineType.DIRECTIVE && line.param === 'User') {
line.value = User;
added = true;
break;
}
}
if (!added) {
section.config.append({ User });
}
}
}
await vscode.workspace.fs.writeFile(
sshConfigFilePath(),
Buffer.from(SSHConfig.stringify(config))
);
configManager.setForHost(HostName, 'persistToSSHConfig', true);
configManager.setForHost(HostName, 'differentUserFromSSHConfig', false);
}

export async function syncSSHConfig(addr: string, configManager: ConfigManager) {
const { config, hosts } = await readSSHConfig();

const matchingHosts = hosts.filter((h) => h.HostName === addr);
const tsUsername = getUsername(configManager, addr);
if (matchingHosts.length === 0) {
const add = await vscode.window.showInformationMessage(
`Host ${addr} not found in SSH config file, would you like to add it?`,
'Yes',
'No'
);
if (add === 'Yes') {
await addToSSHConfig(configManager, addr, tsUsername);
} else {
configManager.setForHost(addr, 'persistToSSHConfig', false);
}
} else if (!configManager.config.hosts?.[addr].differentUserFromSSHConfig) {
for (const h of matchingHosts) {
const cfgUsername = typeof h.User === 'string' ? h.User : h.User[0];
const cfgHost = typeof h.Host === 'string' ? h.Host : h.Host[0];
if (cfgUsername !== tsUsername) {
const editHost = await vscode.window.showInformationMessage(
`The SSH config file specifies a username (${cfgUsername}) for host ${addr} that
is different from the SSH user configured in the Tailscale extension (${tsUsername}). Would you
like to update one of them?`,
'Update extension',
'Update SSH config',
'Do nothing'
);
if (editHost === 'Update extension') {
configManager.setForHost(addr, 'user', cfgUsername);
configManager.setForHost(addr, 'differentUserFromSSHConfig', false);
} else if (editHost === 'Update SSH config') {
const section = config.find({ Host: cfgHost });
if (section && 'config' in section) {
for (const line of section.config) {
if (line.type === SSHConfig.LineType.DIRECTIVE && line.param === 'User') {
line.value = tsUsername;
break;
}
}
await vscode.workspace.fs.writeFile(
sshConfigFilePath(),
Buffer.from(SSHConfig.stringify(config))
);
configManager.setForHost(addr, 'differentUserFromSSHConfig', false);
}
} else {
configManager.setForHost(addr, 'differentUserFromSSHConfig', true);
}
}
// according to man ssh_config, ssh uses the first matching entry, so we can break here
break;
}
}
}
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5501,6 +5501,11 @@ sql-summary@^1.0.1:
resolved "https://registry.npmjs.org/sql-summary/-/sql-summary-1.0.1.tgz"
integrity sha512-IpCr2tpnNkP3Jera4ncexsZUp0enJBLr+pHCyTweMUBrbJsTgQeLWx1FXLhoBj/MvcnUQpkgOn2EY8FKOkUzww==

ssh-config@^4.4.0:
version "4.4.0"
resolved "https://registry.yarnpkg.com/ssh-config/-/ssh-config-4.4.0.tgz#5fcc595d941661101f0fda8113149e72fc4a4c5d"
integrity sha512-W+AAUSsBirHyXqYBUtZ4l0FBAPH/jnklA0KPBfBuBiJVD8LT4LoQST4MCGPziZJYTVvzFmrgrr7j2JWyl/rPIg==

ssh2@^1.14.0:
version "1.14.0"
resolved "https://registry.yarnpkg.com/ssh2/-/ssh2-1.14.0.tgz#8f68440e1b768b66942c9e4e4620b2725b3555bb"
Expand Down