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

RemoteOpenTargets.ts

73 lines2.6 KB

1import { type RemoteOpenTarget } from "@t3tools/contracts";
2import * as HostProcess from "@t3tools/shared/HostProcess";
3import * as NetService from "@t3tools/shared/Net";
4import { readTailscaleSshEnabled, readTailscaleStatus } from "@t3tools/tailscale";
5import * as Context from "effect/Context";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
9​
10const SSH_PORT = 22;
11​
12export class RemoteOpenTargets extends Context.Service<
13 RemoteOpenTargets,
14 {
15 readonly resolveTargets: () => Effect.Effect<ReadonlyArray<RemoteOpenTarget>>;
16 }
17>()("t3/environment/RemoteOpenTargets") {}
18​
19/** @public Service construction is part of the canonical Effect module API. */
20export const make = Effect.gen(function* () {
21 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
22 const net = yield* NetService.NetService;
23​
24 const resolveTargets = Effect.gen(function* () {
25 // Check both loopback families: sshd can be bound IPv6-only.
26 const sshdListening = yield* Effect.zipWith(
27 net.hasListenerOnHost(SSH_PORT, "127.0.0.1"),
28 net.hasListenerOnHost(SSH_PORT, "::1"),
29 (ipv4, ipv6) => ipv4 || ipv6,
30 );
31​
32 const magicDnsName = yield* readTailscaleStatus.pipe(
33 Effect.map((status) => status.magicDnsName),
34 Effect.orElseSucceed(() => null),
35 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
36 );
37​
38 const targets: Array<RemoteOpenTarget> = [];
39​
40 if (!sshdListening) {
41 // Tailscale SSH answers on the tailnet name with no local sshd, so only
42 // that name can work. A running tailscaled alone is not an SSH route.
43 if (
44 magicDnsName !== null &&
45 (yield* readTailscaleSshEnabled.pipe(
46 Effect.orElseSucceed(() => false),
47 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
48 ))
49 ) {
50 targets.push({ kind: "tailscale", host: magicDnsName });
51 }
52 return targets;
53 }
54​
55 if (magicDnsName !== null) {
56 targets.push({ kind: "tailscale", host: magicDnsName });
57 }
58​
59 // os.hostname() may already be an FQDN (macOS often reports
60 // "Name.local"); mDNS names are always `<first-label>.local`.
61 const hostname = yield* HostProcess.Hostname;
62 const shortHostname = hostname.split(".")[0]?.trim();
63 if (shortHostname !== undefined && shortHostname.length > 0) {
64 targets.push({ kind: "mdns", host: `${shortHostname}.local` });
65 }
66​
67 return targets;
68 });
69​
70 return RemoteOpenTargets.of({ resolveTargets: () => resolveTargets });
71});
72​
73export const layer = Layer.effect(RemoteOpenTargets, make);