-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathsshOverrides.ts
More file actions
175 lines (156 loc) · 5.15 KB
/
sshOverrides.ts
File metadata and controls
175 lines (156 loc) · 5.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import { formatDuration, intervalToDuration } from "date-fns";
import * as jsonc from "jsonc-parser";
import * as fs from "node:fs/promises";
import type { WorkspaceConfiguration } from "vscode";
import type { Logger } from "../logging/logger";
export interface SettingOverride {
key: string;
value: unknown;
}
interface RecommendedSetting {
readonly value: number | null;
readonly label: string;
}
function recommended(
shortName: string,
value: number | null,
): RecommendedSetting {
if (value === null) {
return { value, label: `${shortName}: max allowed` };
}
const humanized = formatDuration(
intervalToDuration({ start: 0, end: value * 1000 }),
);
return { value, label: `${shortName}: ${humanized}` };
}
/**
* Applied by the "Apply Recommended SSH Settings" command.
* These are more aggressive (24h) than AUTO_SETUP_DEFAULTS (8h) because the
* user is explicitly opting in via the command palette.
*/
export const RECOMMENDED_SSH_SETTINGS = {
"remote.SSH.connectTimeout": recommended("Connect Timeout", 1800),
"remote.SSH.reconnectionGraceTime": recommended(
"Reconnection Grace Time",
86400,
),
"remote.SSH.serverShutdownTimeout": recommended(
"Server Shutdown Timeout",
86400,
),
"remote.SSH.maxReconnectionAttempts": recommended(
"Max Reconnection Attempts",
null,
),
} as const satisfies Record<string, RecommendedSetting>;
type SshSettingKey = keyof typeof RECOMMENDED_SSH_SETTINGS;
/** Defaults set during connection when the user hasn't configured a value. */
const AUTO_SETUP_DEFAULTS = {
"remote.SSH.reconnectionGraceTime": 28800, // 8h
"remote.SSH.serverShutdownTimeout": 28800, // 8h
"remote.SSH.maxReconnectionAttempts": null, // max allowed
} as const satisfies Partial<Record<SshSettingKey, number | null>>;
/**
* Whether the given RemoteCommand value represents an active command
* (i.e. present, non-empty, and not the SSH default "none").
*/
function isActiveRemoteCommand(cmd: string | undefined): boolean {
return !!cmd && cmd.toLowerCase() !== "none";
}
/**
* Build the list of VS Code setting overrides needed for a remote SSH
* connection to a Coder workspace.
*/
export function buildSshOverrides(
config: Pick<WorkspaceConfiguration, "get">,
sshHost: string,
agentOS: string,
remoteCommand: string | undefined,
logger: Logger,
): SettingOverride[] {
const overrides: SettingOverride[] = [];
// When enableRemoteCommand is true and the host has an active
// RemoteCommand, we must not set remotePlatform: it causes VS Code
// to append 'bash', which conflicts with RemoteCommand. We gate on
// enableRemoteCommand so users who haven't opted in don't get an
// unexpected platform prompt.
const enableRemoteCommand = config.get<boolean>(
"remote.SSH.enableRemoteCommand",
false,
);
const skipRemotePlatform =
enableRemoteCommand && isActiveRemoteCommand(remoteCommand);
const remotePlatforms = config.get<Record<string, string>>(
"remote.SSH.remotePlatform",
{},
);
if (skipRemotePlatform) {
logger.info("RemoteCommand detected, skipping remotePlatform override");
// Remove any stale entry so it doesn't block RemoteCommand.
if (sshHost in remotePlatforms) {
const { [sshHost]: _removed, ...rest } = remotePlatforms;
overrides.push({
key: "remote.SSH.remotePlatform",
value: rest,
});
}
} else {
// Set the remote platform to bypass the platform prompt.
if (remotePlatforms[sshHost] !== agentOS) {
overrides.push({
key: "remote.SSH.remotePlatform",
value: { ...remotePlatforms, [sshHost]: agentOS },
});
}
}
// Default 15s is too short for startup scripts; enforce a minimum.
const connTimeoutKey: SshSettingKey = "remote.SSH.connectTimeout";
const { value: minConnTimeout } = RECOMMENDED_SSH_SETTINGS[connTimeoutKey];
const connTimeout = config.get<number>(connTimeoutKey);
if (minConnTimeout && (!connTimeout || connTimeout < minConnTimeout)) {
overrides.push({ key: connTimeoutKey, value: minConnTimeout });
}
// Set conservative defaults for settings the user hasn't configured.
for (const [key, value] of Object.entries(AUTO_SETUP_DEFAULTS)) {
if (config.get(key) === undefined) {
overrides.push({ key, value });
}
}
return overrides;
}
/**
* Apply setting overrides to the user's settings.json file.
*
* We munge the file directly with jsonc instead of using the VS Code API
* because the API hangs indefinitely during remote connection setup (likely
* a deadlock from trying to update config on the not-yet-connected remote).
*/
export async function applySettingOverrides(
settingsFilePath: string,
overrides: SettingOverride[],
logger: Logger,
): Promise<boolean> {
if (overrides.length === 0) {
return true;
}
let settingsContent = "{}";
try {
settingsContent = await fs.readFile(settingsFilePath, "utf8");
} catch {
// File probably doesn't exist yet.
}
for (const { key, value } of overrides) {
settingsContent = jsonc.applyEdits(
settingsContent,
jsonc.modify(settingsContent, [key], value, {}),
);
}
try {
await fs.writeFile(settingsFilePath, settingsContent);
return true;
} catch (ex) {
// Could be read-only (e.g. home-manager on NixOS). Not catastrophic.
logger.warn("Failed to configure settings", ex);
return false;
}
}