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

auth.ts

210 lines6.7 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Layer from "effect/Layer";
5import * as Path from "effect/Path";
6import * as PlatformError from "effect/PlatformError";
7​
8import { SshPasswordPromptError } from "./errors.ts";
9​
10export interface SshPasswordRequest {
11 readonly destination: string;
12 readonly username: string | null;
13 readonly prompt: string;
14 readonly attempt: number;
16​
17export interface SshAskpassFile {
18 readonly path: string;
19 readonly contents: string;
20 readonly mode?: number;
22​
23export interface SshAskpassHelperDescriptor {
24 readonly launcherPath: string;
25 readonly files: ReadonlyArray<SshAskpassFile>;
27​
28export interface SshAuthOptions {
29 readonly authSecret?: string | null;
30 readonly batchMode?: "yes" | "no";
31 readonly interactiveAuth?: boolean;
33​
34export interface SshPasswordPromptShape {
35 readonly isAvailable: boolean;
36 readonly request: (
37 request: SshPasswordRequest,
38 ) => Effect.Effect<string | null, SshPasswordPromptError>;
40​
41export class SshPasswordPrompt extends Context.Service<SshPasswordPrompt, SshPasswordPromptShape>()(
42 "@t3tools/ssh/auth/SshPasswordPrompt",
43) {
44 static readonly disabledLayer = Layer.succeed(
45 SshPasswordPrompt,
46 SshPasswordPrompt.of({
47 isAvailable: false,
48 request: () => Effect.succeed(null),
49 }),
50 );
52​
53export interface SshChildEnvironmentOptions {
54 readonly interactiveAuth?: boolean;
55 readonly baseEnv?: NodeJS.ProcessEnv;
56 readonly askpassDirectory?: string;
57 readonly authSecret?: string | null;
58 readonly platform?: NodeJS.Platform;
60​
61const SSH_ASKPASS_DIR_NAME = "t3code-ssh-askpass";
62​
63function joinSshAskpassPath(
64 directory: string,
65 fileName: string,
66 platform: NodeJS.Platform,
67): string {
68 const trimmed = directory.replace(/[\\/]+$/u, "");
69 return platform === "win32" ? `${trimmed}\\${fileName}` : `${trimmed}/${fileName}`;
71​
72export const ASKPASS_POSIX_SCRIPT = `#!/bin/sh
73# Invoked by ssh via SSH_ASKPASS when T3 Code re-runs ssh with a cached password
74# from the renderer's in-app prompt. We never expose a native dialog here - if
75# T3_SSH_AUTH_SECRET is missing, that's a caller bug and we fail loudly.
76if [ "\${T3_SSH_AUTH_SECRET+x}" = "x" ]; then
77 printf "%s\\n" "$T3_SSH_AUTH_SECRET"
78 exit 0
79fi
80printf 'T3 Code ssh-askpass invoked without T3_SSH_AUTH_SECRET.\\n' >&2
81exit 1
82`;
83​
84export const ASKPASS_WINDOWS_LAUNCHER_SCRIPT = `@echo off\r
85powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0ssh-askpass.ps1" %*\r
86`;
87​
88export const ASKPASS_WINDOWS_SCRIPT = `# Invoked by ssh via SSH_ASKPASS (through ssh-askpass.cmd) when T3 Code re-runs\r
89# ssh with a cached password from the renderer's in-app prompt. We never expose\r
90# a native dialog here - if T3_SSH_AUTH_SECRET is missing, that's a caller bug\r
91# and we fail loudly.\r
92if ($null -ne $env:T3_SSH_AUTH_SECRET) {\r
93 [Console]::Out.WriteLine($env:T3_SSH_AUTH_SECRET)\r
94 exit 0\r
95}\r
96[Console]::Error.WriteLine("T3 Code ssh-askpass invoked without T3_SSH_AUTH_SECRET.")\r
97exit 1\r
98`;
99​
100export const getDefaultSshAskpassDirectory = Effect.fn("ssh/auth.getDefaultSshAskpassDirectory")(
101 function* () {
102 const fs = yield* FileSystem.FileSystem;
103 const path = yield* Path.Path;
104 const parentDirectory = yield* fs.makeTempDirectory({ prefix: "t3code-ssh-runtime-" });
105 return path.join(parentDirectory, SSH_ASKPASS_DIR_NAME);
106 },
107);
108​
109export const buildSshAskpassHelperDescriptor = Effect.fn(
110 "ssh/auth.buildSshAskpassHelperDescriptor",
111)(function* (input: {
112 readonly directory: string;
113 readonly platform?: NodeJS.Platform;
114}): Effect.fn.Return<SshAskpassHelperDescriptor, never, Path.Path> {
115 const platform = input.platform ?? process.platform;
116 const path = yield* Path.Path;
117 const directory = input.directory;
118​
119 if (platform === "win32") {
120 const powershellPath = joinSshAskpassPath(directory, "ssh-askpass.ps1", platform);
121 return {
122 launcherPath: joinSshAskpassPath(directory, "ssh-askpass.cmd", platform),
123 files: [
124 {
125 path: joinSshAskpassPath(directory, "ssh-askpass.cmd", platform),
126 contents: ASKPASS_WINDOWS_LAUNCHER_SCRIPT,
127 },
128 {
129 path: powershellPath,
130 contents: ASKPASS_WINDOWS_SCRIPT,
131 },
132 ],
133 };
134 }
135​
136 return {
137 launcherPath: path.join(directory, "ssh-askpass.sh"),
138 files: [
139 {
140 path: path.join(directory, "ssh-askpass.sh"),
141 contents: ASKPASS_POSIX_SCRIPT,
142 mode: 0o700,
143 },
144 ],
145 };
146});
147​
148export const ensureSshAskpassHelpers = Effect.fn("ssh/auth.ensureSshAskpassHelpers")(
149 function* (input: {
150 readonly directory: string;
151 readonly platform?: NodeJS.Platform;
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 = input.platform ?? process.platform;
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 ?? process.env) };
183 if (!input.interactiveAuth) {
184 return baseEnv;
185 }
186​
187 const platform = input.platform ?? process.platform;
188 const directory = input.askpassDirectory ?? (yield* getDefaultSshAskpassDirectory());
189 const sshAskpass = yield* ensureSshAskpassHelpers({ directory, platform });
190​
191 return {
192 ...baseEnv,
193 SSH_ASKPASS: sshAskpass,
194 SSH_ASKPASS_REQUIRE: "force",
195 ...(input.authSecret === undefined ? {} : { T3_SSH_AUTH_SECRET: input.authSecret ?? "" }),
196 ...(platform === "win32" || baseEnv.DISPLAY ? {} : { DISPLAY: "t3code" }),
197 };
198});
199​
200export function isSshAuthFailure(error: unknown): boolean {
201 const message = error instanceof Error ? error.message : String(error);
202 const normalized = message.toLowerCase();
203 return (
204 /permission denied \((?:publickey|password|keyboard-interactive|hostbased|gssapi-with-mic)[^)]*\)/u.test(
205 normalized,
206 ) ||
207 /authentication failed/u.test(normalized) ||
208 /too many authentication failures/u.test(normalized)
209 );