Open History to see the last commit
1import { HostProcessPlatform } from "@v12/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";
10
11import { SshPasswordPromptError } from "./errors.ts";
12
13export interface SshPasswordRequest {
14 readonly destination: string;
15 readonly username: string | null;
16 readonly prompt: string;
17 readonly attempt: number;
18}
19
20export interface SshAskpassFile {
21 readonly path: string;
22 readonly contents: string;
23 readonly mode?: number;
24}
25
26export interface SshAskpassHelperDescriptor {
27 readonly launcherPath: string;
28 readonly files: ReadonlyArray<SshAskpassFile>;
29}
30
31export interface SshAuthOptions {
32 readonly authSecret?: string | null;
33 readonly batchMode?: "yes" | "no";
34 readonly interactiveAuth?: boolean;
35}
36
37export interface SshPasswordPromptShape {
38 readonly isAvailable: boolean;
39 readonly request: (
40 request: SshPasswordRequest,
41 ) => Effect.Effect<string | null, SshPasswordPromptError>;
42}
43
44export class SshPasswordPrompt extends Context.Service<SshPasswordPrompt, SshPasswordPromptShape>()(
45 "@v12/ssh/auth/SshPasswordPrompt",
46) {
47 static readonly disabledLayer = Layer.succeed(
48 SshPasswordPrompt,
49 SshPasswordPrompt.of({
50 isAvailable: false,
51 request: () => Effect.succeed(null),
52 }),
53 );
54}
55
56export interface SshChildEnvironmentOptions {
57 readonly interactiveAuth?: boolean;
58 readonly baseEnv?: NodeJS.ProcessEnv;
59 readonly askpassDirectory?: string;
60 readonly authSecret?: string | null;
61}
62
63const SSH_ASKPASS_DIR_NAME = "v12-ssh-askpass";
64
65function joinSshAskpassPath(
66 directory: string,
67 fileName: string,
68 platform: NodeJS.Platform,
69): string {
70 const trimmed = directory.replace(/[\\/]+$/u, "");
71 return platform === "win32" ? `${trimmed}\\${fileName}` : `${trimmed}/${fileName}`;
72}
73
74export const ASKPASS_POSIX_SCRIPT = `#!/bin/sh
75# Invoked by ssh via SSH_ASKPASS when V12 re-runs ssh with a cached password
76# from the renderer's in-app prompt. We never expose a native dialog here - if
77# V12_SSH_AUTH_SECRET is missing, that's a caller bug and we fail loudly.
78if [ "\${V12_SSH_AUTH_SECRET+x}" = "x" ]; then
79 printf "%s\\n" "$V12_SSH_AUTH_SECRET"
80 exit 0
81fi
82printf 'V12 ssh-askpass invoked without V12_SSH_AUTH_SECRET.\\n' >&2
83exit 1
84`;
85
86export const ASKPASS_WINDOWS_LAUNCHER_SCRIPT = `@echo off\r
87powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0ssh-askpass.ps1" %*\r
88`;
89
90export const ASKPASS_WINDOWS_SCRIPT = `# Invoked by ssh via SSH_ASKPASS (through ssh-askpass.cmd) when V12 re-runs\r
91# ssh with a cached password from the renderer's in-app prompt. We never expose\r
92# a native dialog here - if V12_SSH_AUTH_SECRET is missing, that's a caller bug\r
93# and we fail loudly.\r
94if ($null -ne $env:V12_SSH_AUTH_SECRET) {\r
95 [Console]::Out.WriteLine($env:V12_SSH_AUTH_SECRET)\r
96 exit 0\r
97}\r
98[Console]::Error.WriteLine("V12 ssh-askpass invoked without V12_SSH_AUTH_SECRET.")\r
99exit 1\r
100`;
101
102export const getDefaultSshAskpassDirectory = Effect.fn("ssh/auth.getDefaultSshAskpassDirectory")(
103 function* () {
104 const fs = yield* FileSystem.FileSystem;
105 const path = yield* Path.Path;
106 const parentDirectory = yield* fs.makeTempDirectory({ prefix: "v12-ssh-runtime-" });
107 return path.join(parentDirectory, SSH_ASKPASS_DIR_NAME);
108 },
109);
110
111export const buildSshAskpassHelperDescriptor = Effect.fn(
112 "ssh/auth.buildSshAskpassHelperDescriptor",
113)(function* (input: {
114 readonly directory: string;
115}): Effect.fn.Return<SshAskpassHelperDescriptor, never, Path.Path> {
116 const platform = yield* HostProcessPlatform;
117 const path = yield* Path.Path;
118 const directory = input.directory;
119
120 if (platform === "win32") {
121 const powershellPath = joinSshAskpassPath(directory, "ssh-askpass.ps1", platform);
122 return {
123 launcherPath: joinSshAskpassPath(directory, "ssh-askpass.cmd", platform),
124 files: [
125 {
126 path: joinSshAskpassPath(directory, "ssh-askpass.cmd", platform),
127 contents: ASKPASS_WINDOWS_LAUNCHER_SCRIPT,
128 },
129 {
130 path: powershellPath,
131 contents: ASKPASS_WINDOWS_SCRIPT,
132 },
133 ],
134 };
135 }
136
137 return {
138 launcherPath: path.join(directory, "ssh-askpass.sh"),
139 files: [
140 {
141 path: path.join(directory, "ssh-askpass.sh"),
142 contents: ASKPASS_POSIX_SCRIPT,
143 mode: 0o700,
144 },
145 ],
146 };
147});
148
149export const ensureSshAskpassHelpers = Effect.fn("ssh/auth.ensureSshAskpassHelpers")(
150 function* (input: {
151 readonly directory: string;
152 }): Effect.fn.Return<string, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> {
153 const fs = yield* FileSystem.FileSystem;
154 const path = yield* Path.Path;
155 const descriptor = yield* buildSshAskpassHelperDescriptor(input);
156 const platform = yield* HostProcessPlatform;
157
158 yield* fs.makeDirectory(path.dirname(descriptor.launcherPath), { recursive: true });
159
160 for (const file of descriptor.files) {
161 const existing = yield* fs.exists(file.path);
162 const current = existing ? yield* fs.readFileString(file.path) : null;
163 if (current !== file.contents) {
164 yield* fs.writeFileString(file.path, file.contents);
165 }
166 if (file.mode !== undefined && platform !== "win32") {
167 yield* fs.chmod(file.path, file.mode);
168 }
169 }
170
171 return descriptor.launcherPath;
172 },
173);
174
175export const buildSshChildEnvironment = Effect.fn("ssh/auth.buildSshChildEnvironment")(function* (
176 input: SshChildEnvironmentOptions = {},
177): Effect.fn.Return<
178 NodeJS.ProcessEnv,
179 PlatformError.PlatformError,
180 FileSystem.FileSystem | Path.Path
181> {
182 const baseEnv = { ...input.baseEnv };
183 if (!input.interactiveAuth) {
184 return baseEnv;
185 }
186
187 const platform = yield* HostProcessPlatform;
188 const hostDisplay = input.baseEnv
189 ? input.baseEnv.DISPLAY
190 : yield* Config.string("DISPLAY").pipe(
191 Config.option,
192 Effect.orElseSucceed(() => Option.none<string>()),
193 Effect.map(Option.getOrUndefined),
194 );
195 const directory = input.askpassDirectory ?? (yield* getDefaultSshAskpassDirectory());
196 const sshAskpass = yield* ensureSshAskpassHelpers({ directory });
197
198 return {
199 ...baseEnv,
200 SSH_ASKPASS: sshAskpass,
201 SSH_ASKPASS_REQUIRE: "force",
202 ...(input.authSecret === undefined ? {} : { V12_SSH_AUTH_SECRET: input.authSecret ?? "" }),
203 ...(platform === "win32" || baseEnv.DISPLAY || hostDisplay ? {} : { DISPLAY: "v12" }),
204 };
205});
206
207export function isSshAuthFailure(error: unknown): boolean {
208 const message = error instanceof Error ? error.message : String(error);
209 const normalized = message.toLowerCase();
210 return (
211 /permission denied \((?:publickey|password|keyboard-interactive|hostbased|gssapi-with-mic)[^)]*\)/u.test(
212 normalized,
213 ) ||
214 /authentication failed/u.test(normalized) ||
215 /too many authentication failures/u.test(normalized)
216 );
217}