Open History to see the last commit
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 */
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 const username = yield* HostProcess.Username;
32
33 const magicDnsName = yield* readTailscaleStatus.pipe(
34 Effect.map((status) => status.magicDnsName),
35 Effect.orElseSucceed(() => null),
36 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
37 );
38
39 const targets: Array<RemoteOpenTarget> = [];
40
41 if (!sshdListening) {
42 // Tailscale SSH needs no local sshd; tailscaled alone does not prove 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({
51 kind: "tailscale",
52 host: magicDnsName,
53 ...(username === null ? {} : { username }),
54 });
55 }
56 return targets;
57 }
58
59 if (magicDnsName !== null) {
60 targets.push({
61 kind: "tailscale",
62 host: magicDnsName,
63 ...(username === null ? {} : { username }),
64 });
65 }
66
67 // hostname() may be an FQDN; mDNS always uses <first-label>.local.
68 const hostname = yield* HostProcess.Hostname;
69 const shortHostname = hostname.split(".")[0]?.trim();
70 if (shortHostname !== undefined && shortHostname.length > 0) {
71 targets.push({
72 kind: "mdns",
73 host: `${shortHostname}.local`,
74 ...(username === null ? {} : { username }),
75 });
76 }
77
78 return targets;
79 });
80
81 return RemoteOpenTargets.of({ resolveTargets: () => resolveTargets });
82});
83
84export const layer = Layer.effect(RemoteOpenTargets, make);