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 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 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 answers on the tailnet name with no local sshd, so only
43 // that name can work. A running tailscaled alone is not an SSH route.
44 if (
45 magicDnsName !== null &&
46 (yield* readTailscaleSshEnabled.pipe(
47 Effect.orElseSucceed(() => false),
48 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
49 ))
50 ) {
51 targets.push({
52 kind: "tailscale",
53 host: magicDnsName,
54 ...(username === null ? {} : { username }),
55 });
56 }
57 return targets;
58 }
59
60 if (magicDnsName !== null) {
61 targets.push({
62 kind: "tailscale",
63 host: magicDnsName,
64 ...(username === null ? {} : { username }),
65 });
66 }
67
68 // os.hostname() may already be an FQDN (macOS often reports
69 // "Name.local"); mDNS names are always `<first-label>.local`.
70 const hostname = yield* HostProcess.Hostname;
71 const shortHostname = hostname.split(".")[0]?.trim();
72 if (shortHostname !== undefined && shortHostname.length > 0) {
73 targets.push({
74 kind: "mdns",
75 host: `${shortHostname}.local`,
76 ...(username === null ? {} : { username }),
77 });
78 }
79
80 return targets;
81 });
82
83 return RemoteOpenTargets.of({ resolveTargets: () => resolveTargets });
84});
85
86export const layer = Layer.effect(RemoteOpenTargets, make);