Open History to see the last commit
1/**
2 * Because browser dev is single-origin (Vite proxies the backend — see
3 * `resolveDevProxyTarget` in apps/web/vite.config.ts), one proxy rule covering
4 * the web port is enough; the backend needs no mapping of its own.
5 */
6
7import {
8 buildTailscaleHttpsBaseUrl,
9 disableTailscaleServe,
10 ensureTailscaleServe,
11 readTailscaleStatus,
12 type TailscaleCommandError,
13 type TailscaleStderrDiagnostic,
14} from "@t3tools/tailscale";
15import * as Effect from "effect/Effect";
16import * as Schema from "effect/Schema";
17import type { ChildProcessSpawner } from "effect/process";
18
19/**
20 * Human-readable gloss for each diagnostic. Deliberately our own words rather
21 * than the CLI's: tailscale prints auth keys and node names into stderr, and
22 * this string is logged.
23 */
24const DIAGNOSTIC_EXPLANATIONS: Record<TailscaleStderrDiagnostic, string | undefined> = {
25 "no-existing-handler": "no mapping existed for that port",
26 "not-logged-in": "this machine is not logged into a tailnet — run `tailscale up`",
27 "permission-denied": "permission denied — `tailscale serve` may need elevated privileges",
28 unknown: undefined,
29};
30
31const explainCommandFailure = (error: TailscaleCommandError): string | undefined =>
32 error._tag === "TailscaleCommandExitError" && error.stderrDiagnostic !== undefined
33 ? (DIAGNOSTIC_EXPLANATIONS[error.stderrDiagnostic] ?? "run the command by hand to see why")
34 : undefined;
35
36export class TailscaleUnavailableError extends Schema.TaggedError<TailscaleUnavailableError>()(
37 "TailscaleUnavailableError",
38 { cause: Schema.Defect() },
39) {
40 override get message(): string {
41 return "could not talk to tailscale";
42 }
43
44 get hint(): string {
45 return "Is Tailscale installed and tailscaled running? Try `tailscale status` — or drop --share and open the printed localhost URL.";
46 }
47}
48
49export class TailnetNameMissingError extends Schema.TaggedError<TailnetNameMissingError>()(
50 "TailnetNameMissingError",
51 {},
52) {
53 override get message(): string {
54 return "this machine has no tailnet DNS name";
55 }
56
57 get hint(): string {
58 return "Run `tailscale up` and make sure MagicDNS is enabled.";
59 }
60}
61
62export class DevServeFailedError extends Schema.TaggedError<DevServeFailedError>()(
63 "DevServeFailedError",
64 {
65 stage: Schema.Literals(["clear-existing", "serve"]),
66 webPort: Schema.Number,
67 explanation: Schema.optional(Schema.String),
68 cause: Schema.optional(Schema.Defect()),
69 },
70) {
71 override get message(): string {
72 const port = String(this.webPort);
73 const base =
74 this.stage === "clear-existing"
75 ? `could not clear the existing mapping for port ${port}. Run \`tailscale serve --https=${port} off\` and retry`
76 : `could not serve port ${port} on the tailnet (it is no longer served; any previous mapping for it was cleared before this attempt)`;
77 return this.explanation ? `${base}: ${this.explanation}` : base;
78 }
79
80 get hint(): undefined {
81 return undefined;
82 }
83}
84
85export type DevShareError =
86 | TailscaleUnavailableError
87 | TailnetNameMissingError
88 | DevServeFailedError;
89
90/**
91 * Runs uninterruptibly: this is called from a finalizer on the way out of an
92 * interrupted program, and cancelling the cleanup subprocess would leave
93 * exactly the stale mapping it exists to remove.
94 */
95export const unshareDevServer = (
96 webPort: number,
97): Effect.Effect<
98 {
99 readonly cleared: boolean;
100 readonly explanation?: string | undefined;
101 readonly cause?: TailscaleCommandError | undefined;
102 },
103 never,
104 ChildProcessSpawner.ChildProcessSpawner
105> =>
106 disableTailscaleServe({ servePort: webPort }).pipe(
107 Effect.as({ cleared: true } as const),
108 Effect.catch((error: TailscaleCommandError) =>
109 Effect.succeed(
110 error._tag === "TailscaleCommandExitError" &&
111 error.stderrDiagnostic === "no-existing-handler"
112 ? ({ cleared: true } as const)
113 : ({
114 cleared: false,
115 ...(explainCommandFailure(error) !== undefined
116 ? { explanation: explainCommandFailure(error) }
117 : {}),
118 cause: error,
119 } as const),
120 ),
121 ),
122 Effect.uninterruptible,
123 );
124
125export interface DevShareResult {
126 readonly url: string;
127 readonly host: string;
128}
129
130/**
131 * Publishes `webPort` on the tailnet. The tailnet port always matches the web
132 * port so the URL is stable; `localTarget` points it at the backend instead
133 * when the backend serves a built client (`--built`).
134 */
135export const shareDevServer = Effect.fn("devShare.shareDevServer")(function* (input: {
136 readonly webPort: number;
137 readonly localTarget?: { readonly port: number; readonly host: string };
138}) {
139 const status = yield* readTailscaleStatus.pipe(
140 Effect.mapError((error) => new TailscaleUnavailableError({ cause: error })),
141 );
142 if (status.magicDnsName === null) {
143 return yield* new TailnetNameMissingError();
144 }
145
146 const cleared = yield* unshareDevServer(input.webPort);
147 if (!cleared.cleared) {
148 // Serving over routes we failed to remove would hand out a URL that is
149 // broken in a way the user cannot see: the page loads while /ws and /api
150 // silently resolve to a dead backend. Better to refuse and say why.
151 return yield* new DevServeFailedError({
152 stage: "clear-existing",
153 webPort: input.webPort,
154 ...(cleared.explanation !== undefined ? { explanation: cleared.explanation } : {}),
155 ...(cleared.cause !== undefined ? { cause: cleared.cause } : {}),
156 });
157 }
158
159 // Proxy to the hostname Vite binds rather than the package default of
160 // 127.0.0.1. Vite listens on `localhost`, which Node 17+ resolves to `::1`
161 // first, so it only binds the IPv6 loopback and a 127.0.0.1 target has
162 // nothing behind it (tailscale answers 502).
163 yield* ensureTailscaleServe({
164 localPort: input.localTarget?.port ?? input.webPort,
165 servePort: input.webPort,
166 localHost: input.localTarget?.host ?? "localhost",
167 }).pipe(
168 Effect.mapError((error) => {
169 const explanation = explainCommandFailure(error);
170 return new DevServeFailedError({
171 stage: "serve",
172 webPort: input.webPort,
173 ...(explanation !== undefined ? { explanation } : {}),
174 cause: error,
175 });
176 }),
177 );
178
179 return {
180 url: buildTailscaleHttpsBaseUrl({
181 magicDnsName: status.magicDnsName,
182 servePort: input.webPort,
183 }),
184 host: status.magicDnsName,
185 } satisfies DevShareResult;
186});