@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 294 lines 8.07 KB
Raw
1 import * as Binding from "alchemy/Binding";
2 import * as Data from "effect/Data";
3 import * as Effect from "effect/Effect";
4 import * as FileSystem from "effect/FileSystem";
5 import * as Layer from "effect/Layer";
6 import * as Path from "effect/Path";
7 import * as ChildProcess from "effect/process/ChildProcess";
8 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
9 import * as Redacted from "effect/Redacted";
10 import type * as Scope from "effect/Scope";
11 import * as Stream from "effect/Stream";
12 import type { Server } from "./Server.ts";
13
14 export class SshError extends Data.TaggedError("Hetzner.SshError")<{
15 message: string;
16 host?: string;
17 command?: string;
18 code?: number;
19 stderr?: string;
20 }> {}
21
22 export interface SshExecResult {
23 stdout: string;
24 stderr: string;
25 code: number;
26 }
27
28 export interface SshOptions {
29 /** SSH user. @default "root" */
30 user?: string;
31 /** PKCS8 PEM private key. Defaults to the Server's deploy key. */
32 privateKey?: string | Redacted.Redacted<string>;
33 }
34
35 export type SshServices =
36 | FileSystem.FileSystem
37 | Path.Path
38 | ChildProcessSpawner.ChildProcessSpawner
39 | Scope.Scope;
40
41 export interface SshClient {
42 exec: (command: string) => Effect.Effect<SshExecResult, SshError, SshServices>;
43 scp: (
44 local: string | Uint8Array<ArrayBufferLike>,
45 remote: string,
46 ) => Effect.Effect<void, SshError, SshServices>;
47 }
48
49 /**
50 * SSH exec/scp against a Hetzner Server. Uses the Server's Alchemy-managed
51 * deploy key (injected at create) unless `privateKey` is passed.
52 *
53 * ### Remote access
54 * **Example:** Exec a command
55 * ```typescript
56 * const ssh = yield* Hetzner.Ssh(server);
57 * const { stdout } = yield* ssh.exec("uname -a");
58 * ```
59 *
60 * **Example:** Copy a file
61 * ```typescript
62 * const ssh = yield* Hetzner.Ssh(server);
63 * yield* ssh.scp("/tmp/app.zip", "/opt/app/bundle.zip");
64 * ```
65 *
66 * @binding
67 * @product Server
68 */
69 export interface Ssh extends Binding.Service<
70 Ssh,
71 "Hetzner.Ssh",
72 (server: Server, options?: SshOptions) => Effect.Effect<SshClient, SshError, SshServices>
73 > {}
74
75 export const Ssh = Binding.Service<Ssh>("Hetzner.Ssh");
76
77 const unwrapKey = (value: unknown): string | undefined => {
78 if (value === undefined || value === null) return undefined;
79 if (typeof value === "string") return value;
80 if (Redacted.isRedacted(value)) {
81 const inner = Redacted.value(value);
82 return typeof inner === "string" ? inner : undefined;
83 }
84 return undefined;
85 };
86
87 const ipv4Of = (server: Server): string | undefined => {
88 const value = (server as { ipv4?: unknown }).ipv4;
89 return typeof value === "string" && value.length > 0 ? value : undefined;
90 };
91
92 const sshArgs = (keyPath: string): string[] => [
93 "-i",
94 keyPath,
95 "-o",
96 "StrictHostKeyChecking=no",
97 "-o",
98 "UserKnownHostsFile=/dev/null",
99 "-o",
100 "IdentitiesOnly=yes",
101 "-o",
102 "BatchMode=yes",
103 "-o",
104 "ConnectTimeout=10",
105 "-o",
106 "LogLevel=ERROR",
107 ];
108
109 const runCommand = Effect.fn(function* (input: {
110 bin: string;
111 args: string[];
112 host: string;
113 command?: string;
114 }) {
115 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
116 const result = yield* ChildProcess.make(input.bin, input.args, {
117 stdin: "ignore",
118 stdout: "pipe",
119 stderr: "pipe",
120 detached: false,
121 }).pipe(
122 (command) => spawner.spawn(command),
123 Effect.flatMap((child) =>
124 Effect.all(
125 {
126 exitCode: child.exitCode,
127 stdout: child.stdout.pipe(Stream.decodeText, Stream.mkString),
128 stderr: child.stderr.pipe(Stream.decodeText, Stream.mkString),
129 },
130 { concurrency: "unbounded" },
131 ),
132 ),
133 Effect.mapError(
134 (error) =>
135 new SshError({
136 message: `ssh spawn failed: ${String(error)}`,
137 host: input.host,
138 command: input.command,
139 }),
140 ),
141 );
142 return {
143 code: Number(result.exitCode),
144 stdout: result.stdout,
145 stderr: result.stderr,
146 };
147 });
148
149 /**
150 * Open an SSH session against `host` with the given private key. Writes
151 * the key to a temp file (mode 0600) for `ssh`/`scp`.
152 */
153 export const openSshClient = Effect.fn(function* (input: {
154 host: string;
155 privateKey: string;
156 user?: string;
157 }) {
158 const fs = yield* FileSystem.FileSystem;
159 const path = yield* Path.Path;
160 const user = input.user ?? "root";
161 const dest = `${user}@${input.host}`;
162 const dir = yield* fs.makeTempDirectory({ prefix: "alchemy-hetzner-ssh-" });
163 const keyPath = path.join(dir, "id");
164 yield* fs.writeFileString(keyPath, input.privateKey);
165 yield* fs.chmod(keyPath, 0o600);
166 yield* runCommand({
167 bin: "chmod",
168 args: ["600", keyPath],
169 host: input.host,
170 command: `chmod 600 ${keyPath}`,
171 }).pipe(Effect.ignore);
172
173 const close = fs.remove(dir, { recursive: true }).pipe(Effect.ignore);
174
175 const exec = (command: string) =>
176 runCommand({
177 bin: "ssh",
178 args: [...sshArgs(keyPath), dest, command],
179 host: input.host,
180 command,
181 }).pipe(
182 Effect.flatMap((result) =>
183 result.code === 0
184 ? Effect.succeed(result)
185 : Effect.fail(
186 new SshError({
187 message: `ssh exited ${result.code}: ${
188 [result.stderr, result.stdout]
189 .map((s) => s.trim())
190 .filter((s) => s.length > 0)
191 .join("\n") || "no output"
192 }`,
193 host: input.host,
194 command,
195 code: result.code,
196 stderr: result.stderr,
197 }),
198 ),
199 ),
200 );
201
202 const toSshError = (error: unknown) =>
203 error instanceof SshError
204 ? error
205 : new SshError({
206 message: `ssh failed: ${String(error)}`,
207 host: input.host,
208 });
209
210 const scp = (local: string | Uint8Array<ArrayBufferLike>, remote: string) =>
211 Effect.gen(function* () {
212 let localPath: string;
213 let staged: string | undefined;
214 if (typeof local === "string") {
215 localPath = local;
216 } else {
217 const stamp = yield* Effect.sync(() => crypto.randomUUID());
218 staged = path.join(dir, `payload-${stamp}`);
219 yield* fs.writeFile(staged, local);
220 localPath = staged;
221 }
222 const slash = remote.lastIndexOf("/");
223 if (slash > 0) {
224 const remoteDir = remote.slice(0, slash);
225 yield* exec(`mkdir -p ${JSON.stringify(remoteDir)}`);
226 }
227 const result = yield* runCommand({
228 bin: "scp",
229 args: [...sshArgs(keyPath), localPath, `${dest}:${remote}`],
230 host: input.host,
231 command: `scp ${localPath} ${remote}`,
232 });
233 if (staged !== undefined) {
234 yield* fs.remove(staged, { force: true }).pipe(Effect.ignore);
235 }
236 if (result.code !== 0) {
237 return yield* new SshError({
238 message: `scp exited ${result.code}`,
239 host: input.host,
240 command: `scp ${remote}`,
241 code: result.code,
242 stderr: result.stderr,
243 });
244 }
245 }).pipe(Effect.mapError(toSshError));
246
247 return { exec, scp, close } satisfies SshClient & {
248 close: Effect.Effect<void>;
249 };
250 });
251
252 export const sshClientForServer = Effect.fn(function* (server: Server, options?: SshOptions) {
253 const host = ipv4Of(server);
254 if (host === undefined) {
255 return yield* new SshError({
256 message: `Server '${server.LogicalId}' has no public IPv4 address`,
257 });
258 }
259 const privateKey =
260 unwrapKey(options?.privateKey) ?? unwrapKey((server as { privateKey?: unknown }).privateKey);
261 if (privateKey === undefined) {
262 return yield* new SshError({
263 message: `Server '${server.LogicalId}' has no deploy SSH private key`,
264 host,
265 });
266 }
267 return yield* openSshClient({
268 host,
269 privateKey,
270 user: options?.user,
271 }).pipe(
272 Effect.mapError((error) =>
273 error instanceof SshError
274 ? error
275 : new SshError({
276 message: `ssh failed: ${String(error)}`,
277 host,
278 }),
279 ),
280 );
281 });
282
283 export const SshLive = Layer.effect(
284 Ssh,
285 Effect.succeed(
286 Effect.fn(function* (server: Server, options?: SshOptions) {
287 const session = yield* sshClientForServer(server, options);
288 return {
289 exec: session.exec,
290 scp: session.scp,
291 };
292 }),
293 ),
294 );