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