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

localSshDeviceHost.ts

70 lines2.4 KB

1import * as NodeDnsPromises from "node:dns/promises";
2import * as NodeNet from "node:net";
3import type { SshDeviceHostConfig } from "@t3tools/contracts";
4import * as NodeOS from "node:os";
5import * as Context from "effect/Context";
6import { runSshCommand } from "@t3tools/ssh/command";
7import * as Effect from "effect/Effect";
8​
9export const LocalDeviceHostAddresses = Context.Reference<ReadonlySet<string>>(
10 "LocalDeviceHostAddresses",
11 {
12 defaultValue: () =>
13 new Set(
14 Object.values(NodeOS.networkInterfaces()).flatMap(
15 (entries) => entries?.map((entry) => entry.address) ?? [],
16 ),
17 ),
18 },
19);
20​
21export const isLocalSshDeviceHost = Effect.fn("isLocalSshDeviceHost")(function* (
22 host: SshDeviceHostConfig,
23) {
24 const result = yield* runSshCommand(
25 { alias: host.target, hostname: host.target, username: null, port: host.port ?? null },
26 {
27 preHostArgs: ["-G", ...(host.identityFile ? ["-i", host.identityFile] : [])],
28 timeoutMs: 5000,
29 },
30 ).pipe(Effect.result);
31 if (result._tag === "Failure") return false;
32 const config = new Map(
33 result.success.stdout.split("\n").map((line) => {
34 const separator = line.indexOf(" ");
35 return [line.slice(0, separator), line.slice(separator + 1).trim()];
36 }),
37 );
38 // A local forwarded port or a proxy can lead to a different machine.
39 if (
40 config.get("port") !== "22" ||
41 ["proxycommand", "proxyjump"].some((key) => config.has(key) && config.get(key) !== "none")
42 )
43 return false;
44 const hostname = config.get("hostname")?.replace(/^\[|\]$/g, "");
45 if (!hostname) return false;
46 const addresses = NodeNet.isIP(hostname)
47 ? [hostname]
48 : yield* Effect.tryPromise(() => NodeDnsPromises.lookup(hostname, { all: true })).pipe(
49 Effect.map((entries) => entries.map((entry) => entry.address)),
50 Effect.timeout("2 seconds"),
51 Effect.orElseSucceed(() => [] as string[]),
52 );
53 const localAddresses = yield* LocalDeviceHostAddresses;
54 return (
55 addresses.length > 0 &&
56 addresses.every(
57 (address) => localAddresses.has(address) || address === "::1" || address.startsWith("127."),
58 )
59 );
60});
61​
62export const remoteSshDeviceHosts = Effect.fn("remoteSshDeviceHosts")(function* (
63 hosts: ReadonlyArray<SshDeviceHostConfig>,
64) {
65 return yield* Effect.filter(
66 hosts,
67 (host) => isLocalSshDeviceHost(host).pipe(Effect.map((local) => !local)),
68 { concurrency: 4 },
69 );
70});