Open History to see the last commit
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";
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
20interface 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 "@t3tools/ssh/auth/SshPasswordPrompt",
46) {
47 static readonly disabledLayer = Layer.succeed(
48 SshPasswordPrompt,
49 SshPasswordPrompt.of({
50 isAvailable: false,
51 request: Effect.fn("SshPasswordPrompt.request")(function () {
52 return Effect.succeed(null);
53 }),
54 }),
55 );
56}
57
58export interface SshChildEnvironmentOptions {
59 readonly interactiveAuth?: boolean;
60 readonly baseEnv?: NodeJS.ProcessEnv;
61 readonly askpassDirectory?: string;
62 readonly authSecret?: string | null;
63}
64
65const SSH_ASKPASS_DIR_NAME = "t3code-ssh-askpass";
66
67function joinSshAskpassPath(
68 directory: string,
69 fileName: string,
70 platform: NodeJS.Platform,
71): string {
72 const trimmed = directory.replace(/[\\/]+$/u, "");
73 return platform === "win32" ? `${trimmed}\\${fileName}` : `${trimmed}/${fileName}`;
74}
75
76const ASKPASS_POSIX_SCRIPT = `#!/bin/sh
77# Invoked by ssh via SSH_ASKPASS when T3 Code re-runs ssh with a cached password
78# from the renderer's in-app prompt. We never expose a native dialog here - if
79# T3_SSH_AUTH_SECRET is missing, that's a caller bug and we fail loudly.
80if [ "\${T3_SSH_AUTH_SECRET+x}" = "x" ]; then
81 printf "%s\\n" "$T3_SSH_AUTH_SECRET"
82 exit 0
83fi
84printf 'T3 Code ssh-askpass invoked without T3_SSH_AUTH_SECRET.\\n' >&2
85exit 1
86`;
87
88const ASKPASS_WINDOWS_LAUNCHER_SCRIPT = `@echo off\r
89powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0ssh-askpass.ps1" %*\r
90`;
91
92const ASKPASS_WINDOWS_SCRIPT = `# Invoked by ssh via SSH_ASKPASS (through ssh-askpass.cmd) when T3 Code re-runs\r
93# ssh with a cached password from the renderer's in-app prompt. We never expose\r
94# a native dialog here - if T3_SSH_AUTH_SECRET is missing, that's a caller bug\r
95# and we fail loudly.\r
96if ($null -ne $env:T3_SSH_AUTH_SECRET) {\r
97 [Console]::Out.WriteLine($env:T3_SSH_AUTH_SECRET)\r
98 exit 0\r
99}\r
100[Console]::Error.WriteLine("T3 Code ssh-askpass invoked without T3_SSH_AUTH_SECRET.")\r
101exit 1\r
102`;
103
104const getDefaultSshAskpassDirectory = Effect.fn("ssh/auth.getDefaultSshAskpassDirectory")(
105 function* () {
106 const fs = yield* FileSystem.FileSystem;
107 const path = yield* Path.Path;
108 const parentDirectory = yield* fs.makeTempDirectory({ prefix: "t3code-ssh-runtime-" });
109 return path.join(parentDirectory, SSH_ASKPASS_DIR_NAME);
110 },
111);
112
113const buildSshAskpassHelperDescriptor = Effect.fn("ssh/auth.buildSshAskpassHelperDescriptor")(
114 function* (input: {
115 readonly directory: string;
116 }): Effect.fn.Return<SshAskpassHelperDescriptor, never, Path.Path> {
117 const platform = yield* HostProcess.Platform;
118 const path = yield* Path.Path;
119 const directory = input.directory;
120
121 if (platform === "win32") {
122 const powershellPath = joinSshAskpassPath(directory, "ssh-askpass.ps1", platform);
123 return {
124 launcherPath: joinSshAskpassPath(directory, "ssh-askpass.cmd", platform),
125 files: [
126 {
127 path: joinSshAskpassPath(directory, "ssh-askpass.cmd", platform),
128 contents: ASKPASS_WINDOWS_LAUNCHER_SCRIPT,
129 },
130 {
131 path: powershellPath,
132 contents: ASKPASS_WINDOWS_SCRIPT,
133 },
134 ],
135 };
136 }
137
138 return {
139 launcherPath: path.join(directory, "ssh-askpass.sh"),
140 files: [
141 {
142 path: path.join(directory, "ssh-askpass.sh"),
143 contents: ASKPASS_POSIX_SCRIPT,
144 mode: 0o700,
145 },
146 ],
147 };
148 },
149);
150
151const ensureSshAskpassHelpers = Effect.fn("ssh/auth.ensureSshAskpassHelpers")(function* (input: {
152 readonly directory: string;
153}): Effect.fn.Return<string, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> {
154 const fs = yield* FileSystem.FileSystem;
155 const path = yield* Path.Path;
156 const descriptor = yield* buildSshAskpassHelperDescriptor(input);
157 const platform = yield* HostProcess.Platform;
158
159 yield* fs.makeDirectory(path.dirname(descriptor.launcherPath), { recursive: true });
160
161 for (const file of descriptor.files) {
162 const existing = yield* fs.exists(file.path);
163 const current = existing ? yield* fs.readFileString(file.path) : null;
164 if (current !== file.contents) {
165 yield* fs.writeFileString(file.path, file.contents);
166 }
167 if (file.mode !== undefined && platform !== "win32") {
168 yield* fs.chmod(file.path, file.mode);
169 }
170 }
171
172 return descriptor.launcherPath;
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* HostProcess.Platform;
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 ? {} : { T3_SSH_AUTH_SECRET: input.authSecret ?? "" }),
203 ...(platform === "win32" || baseEnv.DISPLAY || hostDisplay ? {} : { DISPLAY: "t3code" }),
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}