Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

auth.ts

296 lines10.2 KB

1import * as HostProcess from "@t3tools/shared/HostProcess";
2import * as Config from "effect/Config";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9import * as PlatformError from "effect/PlatformError";
10import * as Semaphore from "effect/Semaphore";
11import * as Stream from "effect/Stream";
12import { ChildProcess, ChildProcessSpawner } from "effect/process";
13​
14import { SshPasswordPromptError } from "./errors.ts";
15​
16export interface SshPasswordRequest {
17 readonly destination: string;
18 readonly username: string | null;
19 readonly prompt: string;
20 readonly attempt: number;
22​
23interface SshAskpassFile {
24 readonly path: string;
25 readonly contents: string;
26 readonly mode?: number;
28​
29export interface SshAskpassHelperDescriptor {
30 readonly helperPath: string;
31 readonly files: ReadonlyArray<SshAskpassFile>;
33​
34export interface SshAuthOptions {
35 readonly authSecret?: string | null;
36 readonly batchMode?: "yes" | "no";
37 readonly interactiveAuth?: boolean;
39​
40export interface SshPasswordPromptShape {
41 readonly isAvailable: boolean;
42 readonly request: (
43 request: SshPasswordRequest,
44 ) => Effect.Effect<string | null, SshPasswordPromptError>;
46​
47export class SshPasswordPrompt extends Context.Service<SshPasswordPrompt, SshPasswordPromptShape>()(
48 "@t3tools/ssh/auth/SshPasswordPrompt",
49) {
50 static readonly disabledLayer = Layer.succeed(
51 SshPasswordPrompt,
52 SshPasswordPrompt.of({
53 isAvailable: false,
54 request: Effect.fn("SshPasswordPrompt.request")(function () {
55 return Effect.succeed(null);
56 }),
57 }),
58 );
60​
61export interface SshChildEnvironmentOptions {
62 readonly interactiveAuth?: boolean;
63 readonly baseEnv?: NodeJS.ProcessEnv;
64 readonly askpassDirectory?: string;
65 readonly authSecret?: string | null;
67​
68const SSH_ASKPASS_DIR_NAME = "t3code-ssh-askpass";
69​
70function joinSshAskpassPath(
71 directory: string,
72 fileName: string,
73 platform: NodeJS.Platform,
74): string {
75 const trimmed = directory.replace(/[\\/]+$/u, "");
76 return platform === "win32" ? `${trimmed}\\${fileName}` : `${trimmed}/${fileName}`;
78​
79const ASKPASS_POSIX_SCRIPT = `#!/bin/sh
80# Invoked by ssh via SSH_ASKPASS when T3 Code re-runs ssh with a cached password
81# from the renderer's in-app prompt. We never expose a native dialog here - if
82# T3_SSH_AUTH_SECRET is missing, that's a caller bug and we fail loudly.
83if [ "\${T3_SSH_AUTH_SECRET+x}" = "x" ]; then
84 printf "%s\\n" "$T3_SSH_AUTH_SECRET"
85 exit 0
86fi
87printf 'T3 Code ssh-askpass invoked without T3_SSH_AUTH_SECRET.\\n' >&2
88exit 1
89`;
90​
91// Windows has no helper form every ssh can start. Win32-OpenSSH starts `"<node>" "<this file>"`
92// directly; Cygwin/MSYS ssh (Git for Windows) execs ssh-askpass.sh through its own sh. Either
93// way ssh appends the prompt as a plain trailing argument, which the helpers never read.
94const ASKPASS_WINDOWS_NODE_SCRIPT = `// Invoked by ssh via SSH_ASKPASS when T3 Code re-runs ssh with a cached password
95// from the renderer's in-app prompt. Answers from T3_SSH_AUTH_SECRET only and
96// never reads its arguments; if the secret is missing, that's a caller bug and
97// we fail loudly.
98if ("T3_SSH_AUTH_SECRET" in process.env) {
99 process.stdout.write((process.env.T3_SSH_AUTH_SECRET || "") + "\\n");
100 process.exit(0);
102process.stderr.write("T3 Code ssh-askpass invoked without T3_SSH_AUTH_SECRET.\\n");
103process.exit(1);
104`;
105​
106const buildSshAskpassHelperDescriptor = Effect.fn("ssh/auth.buildSshAskpassHelperDescriptor")(
107 function* (input: {
108 readonly directory: string;
109 }): Effect.fn.Return<SshAskpassHelperDescriptor, never, Path.Path> {
110 const platform = yield* HostProcess.Platform;
111 const path = yield* Path.Path;
112 const directory = input.directory;
113​
114 if (platform === "win32") {
115 const helperPath = joinSshAskpassPath(directory, "ssh-askpass.cjs", platform);
116 return {
117 helperPath,
118 files: [
119 { path: helperPath, contents: ASKPASS_WINDOWS_NODE_SCRIPT },
120 {
121 path: joinSshAskpassPath(directory, "ssh-askpass.sh", platform),
122 contents: ASKPASS_POSIX_SCRIPT,
123 },
124 ],
125 };
126 }
127​
128 return {
129 helperPath: path.join(directory, "ssh-askpass.sh"),
130 files: [
131 {
132 path: path.join(directory, "ssh-askpass.sh"),
133 contents: ASKPASS_POSIX_SCRIPT,
134 mode: 0o700,
135 },
136 ],
137 };
138 },
139);
140​
141const ensureSshAskpassHelpers = Effect.fn("ssh/auth.ensureSshAskpassHelpers")(function* (input: {
142 readonly directory: string;
143}): Effect.fn.Return<string, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> {
144 const fs = yield* FileSystem.FileSystem;
145 const path = yield* Path.Path;
146 const descriptor = yield* buildSshAskpassHelperDescriptor(input);
147 const platform = yield* HostProcess.Platform;
148​
149 yield* fs.makeDirectory(path.dirname(descriptor.helperPath), { recursive: true });
150​
151 for (const file of descriptor.files) {
152 const existing = yield* fs.exists(file.path);
153 const current = existing ? yield* fs.readFileString(file.path) : null;
154 if (current !== file.contents) {
155 yield* fs.writeFileString(file.path, file.contents);
156 }
157 if (file.mode !== undefined && platform !== "win32") {
158 yield* fs.chmod(file.path, file.mode);
159 }
160 }
161​
162 return descriptor.helperPath;
163});
164​
165// Keep setup serialized through cancellation so writes finish before another command uses the helper.
166let defaultSshAskpassRuntimeDirectory: string | undefined;
167const defaultSshAskpassLock = Semaphore.makeUnsafe(1);
168​
169const ensureDefaultSshAskpassHelpers = Effect.fn("ssh/auth.ensureDefaultSshAskpassHelpers")(
170 function* () {
171 const fs = yield* FileSystem.FileSystem;
172 const path = yield* Path.Path;
173 const userId = yield* HostProcess.UserId;
174 let runtimeDirectory = defaultSshAskpassRuntimeDirectory;
175 if (runtimeDirectory !== undefined) {
176 const cached = runtimeDirectory;
177 const reusable = yield* Effect.all([fs.realPath(cached), fs.stat(cached)]).pipe(
178 Effect.map(
179 ([resolved, info]) =>
180 resolved === cached &&
181 info.type === "Directory" &&
182 (userId === undefined || Option.getOrUndefined(info.uid) === userId),
183 ),
184 Effect.orElseSucceed(() => false),
185 );
186 if (!reusable) {
187 runtimeDirectory = undefined;
188 }
189 }
190 runtimeDirectory ??= yield* fs.realPath(
191 yield* fs.makeTempDirectory({ prefix: "t3code-ssh-runtime-" }),
192 );
193 const helperPath = yield* ensureSshAskpassHelpers({
194 directory: path.join(runtimeDirectory, SSH_ASKPASS_DIR_NAME),
195 });
196 defaultSshAskpassRuntimeDirectory = runtimeDirectory;
197 return helperPath;
198 },
199 (effect) => defaultSshAskpassLock.withPermit(Effect.uninterruptible(effect)),
200);
201​
202// Anything that does not identify as Win32-OpenSSH gets the shell helper. A client that cannot
203// start it fails to authenticate.
204const isWin32OpenSsh = Effect.fn("ssh/auth.isWin32OpenSsh")(
205 function* () {
206 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
207 const handle = yield* spawner.spawn(ChildProcess.make("ssh.exe", ["-V"]));
208 const banner = yield* handle.stderr.pipe(Stream.decodeText(), Stream.mkString);
209 return banner.includes("OpenSSH_for_Windows");
210 },
211 Effect.scoped,
212 Effect.orElseSucceed(() => false),
213);
214​
215export const buildSshChildEnvironment = Effect.fn("ssh/auth.buildSshChildEnvironment")(function* (
216 input: SshChildEnvironmentOptions = {},
217): Effect.fn.Return<
218 NodeJS.ProcessEnv,
219 PlatformError.PlatformError,
220 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
221> {
222 const baseEnv = { ...input.baseEnv };
223 if (!input.interactiveAuth) {
224 return baseEnv;
225 }
226​
227 const platform = yield* HostProcess.Platform;
228 const hostDisplay = input.baseEnv
229 ? input.baseEnv.DISPLAY
230 : yield* Config.String("DISPLAY").pipe(
231 Config.option,
232 Effect.orElseSucceed(() => Option.none<string>()),
233 Effect.map(Option.getOrUndefined),
234 );
235 const helperPath =
236 input.askpassDirectory === undefined
237 ? yield* ensureDefaultSshAskpassHelpers()
238 : yield* ensureSshAskpassHelpers({ directory: input.askpassDirectory });
239​
240 const authSecretEnv =
241 input.authSecret === undefined ? {} : { T3_SSH_AUTH_SECRET: input.authSecret ?? "" };
242​
243 if (platform === "win32") {
244 if (!(yield* isWin32OpenSsh())) {
245 return {
246 ...baseEnv,
247 SSH_ASKPASS: helperPath.replace(/\.cjs$/u, ".sh"),
248 SSH_ASKPASS_REQUIRE: "force",
249 ...authSecretEnv,
250 };
251 }
252 // Win32-OpenSSH uses a value that starts with a quote as the command line as written; an
253 // unquoted one is split after a lower-case ".exe" only. The single-executable t3.exe ignores
254 // a script argument, so it loads the helper through NODE_OPTIONS instead.
255 const execPath = yield* HostProcess.ExecutablePath;
256 const preload = (yield* HostProcess.IsExecutable)
257 ? { NODE_OPTIONS: `--require "${helperPath.replaceAll("\\", "/")}"` }
258 : {};
259 return {
260 ...baseEnv,
261 SSH_ASKPASS: `"${execPath}" "${helperPath}"`,
262 SSH_ASKPASS_REQUIRE: "force",
263 ELECTRON_RUN_AS_NODE: "1",
264 ...preload,
265 ...authSecretEnv,
266 };
267 }
268​
269 return {
270 ...baseEnv,
271 SSH_ASKPASS: helperPath,
272 SSH_ASKPASS_REQUIRE: "force",
273 ...authSecretEnv,
274 ...(baseEnv.DISPLAY || hostDisplay ? {} : { DISPLAY: "t3code" }),
275 };
276});
277​
278export function isSshAuthFailure(error: unknown): boolean {
279 const message = error instanceof Error ? error.message : String(error);
280 const normalized = message.toLowerCase();
281 return (
282 /permission denied \((?:publickey|password|keyboard-interactive|hostbased|gssapi-with-mic)[^)]*\)/u.test(
283 normalized,
284 ) ||
285 /authentication failed/u.test(normalized) ||
286 /too many authentication failures/u.test(normalized)
287 );
289​
290// A local agent signing failure cannot be remedied by the remote account password.
291export function isSshAgentSigningFailure(error: unknown): boolean {
292 const message = error instanceof Error ? error.message : String(error);
293 return /sign_and_send_pubkey: signing failed(?: for [^\n]* from agent:|: (?:agent refused operation|communication with agent failed))/u.test(
294 message,
295 );