-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathprompts.ts
More file actions
199 lines (173 loc) · 5.12 KB
/
prompts.ts
File metadata and controls
199 lines (173 loc) · 5.12 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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import * as childProcess from "node:child_process";
import { appendFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import * as vscode from "vscode";
import type { CancellationToken, LogOutputChannel } from "vscode";
import { pipeToLogOutputChannel, spawn, SpawnError } from "./spawn.ts";
export interface SpawnElevatedDarwinOptions {
script: string;
outputChannel: LogOutputChannel;
outputLabel?: string;
cancellationToken?: CancellationToken;
}
export async function spawnElevatedDarwin(
options: SpawnElevatedDarwinOptions,
): Promise<{ cancelled: boolean }> {
try {
await spawn(
"osascript",
[
"-e",
`'do shell script ${JSON.stringify(options.script)} with administrator privileges'`,
],
{
outputChannel: options.outputChannel,
outputLabel: options.outputLabel,
cancellationToken: options.cancellationToken,
},
);
return {
cancelled: false,
};
} catch (error) {
// osascript will terminate with code 1 if the user cancels the dialog.
if (error instanceof SpawnError && error.code === 1) {
return { cancelled: true };
}
options.outputChannel.error(error instanceof Error ? error : String(error));
throw error;
}
}
export interface SpawnElevatedLinuxOptions {
script: string;
outputChannel: LogOutputChannel;
outputLabel?: string;
cancellationToken?: CancellationToken;
}
async function tryPkexec(
options: SpawnElevatedLinuxOptions,
): Promise<{ success: boolean; cancelled: boolean }> {
const scriptArg = JSON.stringify(options.script);
try {
await spawn("pkexec", ["sh", "-c", scriptArg], {
outputChannel: options.outputChannel,
outputLabel: options.outputLabel,
cancellationToken: options.cancellationToken,
});
return { success: true, cancelled: false };
} catch (error) {
if (error instanceof SpawnError) {
// User cancelled (pkexec returns 126)
if (error.code === 126) {
return { success: true, cancelled: true };
}
// Other failures (no polkit agent, TTY error, etc.) - signal to try fallback
return { success: false, cancelled: false };
}
throw error;
}
}
async function spawnWithSudoPassword(
options: SpawnElevatedLinuxOptions,
): Promise<{ cancelled: boolean }> {
const password = await vscode.window.showInputBox({
prompt: "Enter your sudo password",
password: true,
ignoreFocusOut: true,
});
if (password === undefined) {
return { cancelled: true };
}
const outputLabel = options.outputLabel ? `[${options.outputLabel}]: ` : "";
return new Promise((resolve, reject) => {
let stderrOutput = "";
const child = childProcess.spawn(
"sudo",
["-S", "sh", "-c", options.script],
{
stdio: ["pipe", "pipe", "pipe"],
},
);
// Capture stderr to detect wrong password
child.stderr?.on("data", (data: Buffer) => {
stderrOutput += data.toString();
});
// Write password to stdin and close it
child.stdin.write(`${password}\n`);
child.stdin.end();
// Redirect the child process stdout/stderr to VSCode's output channel for visibility
pipeToLogOutputChannel(child, options.outputChannel, outputLabel);
const disposeCancel = options.cancellationToken?.onCancellationRequested(
() => {
child.kill("SIGINT");
reject(new Error("Command cancelled"));
},
);
child.on("close", (code) => {
disposeCancel?.dispose();
if (code === 0) {
resolve({ cancelled: false });
} else {
// Detect wrong password from stderr
const isWrongPassword =
stderrOutput.includes("Sorry, try again") ||
stderrOutput.includes("incorrect password") ||
stderrOutput.includes("Authentication failure");
const errorMessage = isWrongPassword
? "Incorrect sudo password"
: `sudo command failed with exit code ${code}`;
reject(new Error(errorMessage));
}
});
child.on("error", (error) => {
disposeCancel?.dispose();
reject(error);
});
});
}
export async function spawnElevatedLinux(
options: SpawnElevatedLinuxOptions,
): Promise<{ cancelled: boolean }> {
// Try pkexec first (works with graphical polkit agents)
const pkexecResult = await tryPkexec(options);
if (pkexecResult.success) {
return { cancelled: pkexecResult.cancelled };
}
// Fallback: prompt for sudo password via VS Code input
options.outputChannel.info(
"pkexec not available, falling back to sudo password prompt",
);
return spawnWithSudoPassword(options);
}
export async function spawnElevatedWindows({
script,
outputChannel,
outputLabel,
cancellationToken,
}: {
script: string;
outputChannel: LogOutputChannel;
outputLabel: string;
cancellationToken: CancellationToken;
}) {
const tempScriptPath = path.join(
tmpdir(),
`localstack-elevate-${Date.now()}.ps1`,
);
await appendFile(tempScriptPath, script);
const powershellArgs = [
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-Command",
`$process = Start-Process powershell -Verb RunAs -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File "${tempScriptPath}"' -PassThru; $process.WaitForExit();`,
];
await spawn("powershell", powershellArgs, {
outputLabel,
outputChannel,
cancellationToken,
});
await rm(tempScriptPath, { force: true });
return { cancelled: false };
}