Open History to see the last commit
1/**
2 * RemoteOpenTargets - resolves the SSH hostnames this environment advertises
3 * for remote open-in-editor deep links (`vscode://vscode-remote/ssh-remote+…`).
4 *
5 * The server can only check itself: sshd listening locally, tailscaled
6 * reporting a MagicDNS name, and the machine hostname for mDNS. Whether a
7 * given name resolves from the viewer's machine is inherently client-side.
8 * Targets are ordered most-reachable first (tailnet name works from anywhere
9 * on the tailnet; `<hostname>.local` only on the same LAN).
10 */
11import { type RemoteOpenTarget } from "@t3tools/contracts";
12import { HostProcessHostname } from "@t3tools/shared/hostProcess";
13import * as NetService from "@t3tools/shared/Net";
14import { readTailscaleStatus } from "@t3tools/tailscale";
15import * as Context from "effect/Context";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
19
20const SSH_PORT = 22;
21
22export class RemoteOpenTargets extends Context.Service<
23 RemoteOpenTargets,
24 {
25 readonly resolveTargets: () => Effect.Effect<ReadonlyArray<RemoteOpenTarget>>;
26 }
27>()("t3/environment/RemoteOpenTargets") {}
28
29/** @public Service construction is part of the canonical Effect module API. */
30export const make = Effect.gen(function* () {
31 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
32 const net = yield* NetService.NetService;
33
34 const resolveTargets = Effect.gen(function* () {
35 // No local sshd means no name can work; advertise nothing so clients
36 // render a clear "no SSH route" state instead of links that hang.
37 // Check both loopback families: sshd can be bound IPv6-only.
38 const sshdListening = yield* Effect.zipWith(
39 net.hasListenerOnHost(SSH_PORT, "127.0.0.1"),
40 net.hasListenerOnHost(SSH_PORT, "::1"),
41 (ipv4, ipv6) => ipv4 || ipv6,
42 );
43 if (!sshdListening) {
44 return [];
45 }
46
47 const targets: Array<RemoteOpenTarget> = [];
48
49 // Tailscale absent or down is the common case, not an error.
50 const magicDnsName = yield* readTailscaleStatus.pipe(
51 Effect.map((status) => status.magicDnsName),
52 Effect.orElseSucceed(() => null),
53 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
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* HostProcessHostname;
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);