Open History to see the last commit
1/** Vite proxies the backend, so only the web port needs a share mapping. */
2
3import {
4 buildTailscaleHttpsBaseUrl,
5 disableTailscaleServe,
6 ensureTailscaleServe,
7 readTailscaleStatus,
8 type TailscaleCommandError,
9 type TailscaleStderrDiagnostic,
10} from "@t3tools/tailscale";
11import * as Effect from "effect/Effect";
12import * as Schema from "effect/Schema";
13import type { ChildProcessSpawner } from "effect/process";
14
15/** Log fixed diagnostics; tailscale stderr can contain auth keys and node names. */
16const DIAGNOSTIC_EXPLANATIONS: Record<TailscaleStderrDiagnostic, string | undefined> = {
17 "no-existing-handler": "no mapping existed for that port",
18 "not-logged-in": "this machine is not logged into a tailnet — run `tailscale up`",
19 "permission-denied": "permission denied — `tailscale serve` may need elevated privileges",
20 unknown: undefined,
21};
22
23const explainCommandFailure = (error: TailscaleCommandError): string | undefined =>
24 error._tag === "TailscaleCommandExitError" && error.stderrDiagnostic !== undefined
25 ? (DIAGNOSTIC_EXPLANATIONS[error.stderrDiagnostic] ?? "run the command by hand to see why")
26 : undefined;
27
28export class TailscaleUnavailableError extends Schema.TaggedError<TailscaleUnavailableError>()(
29 "TailscaleUnavailableError",
30 { cause: Schema.Defect() },
31) {
32 override get message(): string {
33 return "could not talk to tailscale";
34 }
35
36 get hint(): string {
37 return "Is Tailscale installed and tailscaled running? Try `tailscale status` — or drop --share and open the printed localhost URL.";
38 }
39}
40
41export class TailnetNameMissingError extends Schema.TaggedError<TailnetNameMissingError>()(
42 "TailnetNameMissingError",
43 {},
44) {
45 override get message(): string {
46 return "this machine has no tailnet DNS name";
47 }
48
49 get hint(): string {
50 return "Run `tailscale up` and make sure MagicDNS is enabled.";
51 }
52}
53
54export class DevServeFailedError extends Schema.TaggedError<DevServeFailedError>()(
55 "DevServeFailedError",
56 {
57 stage: Schema.Literals(["clear-existing", "serve"]),
58 webPort: Schema.Number,
59 explanation: Schema.optional(Schema.String),
60 cause: Schema.optional(Schema.Defect()),
61 },
62) {
63 override get message(): string {
64 const port = String(this.webPort);
65 const base =
66 this.stage === "clear-existing"
67 ? `could not clear the existing mapping for port ${port}. Run \`tailscale serve --https=${port} off\` and retry`
68 : `could not serve port ${port} on the tailnet (it is no longer served; any previous mapping for it was cleared before this attempt)`;
69 return this.explanation ? `${base}: ${this.explanation}` : base;
70 }
71
72 get hint(): undefined {
73 return undefined;
74 }
75}
76
77export type DevShareError =
78 | TailscaleUnavailableError
79 | TailnetNameMissingError
80 | DevServeFailedError;
81
82/** Finalizer cleanup must be uninterruptible or cancellation can leave stale mappings. */
83export const unshareDevServer = (
84 webPort: number,
85): Effect.Effect<
86 {
87 readonly cleared: boolean;
88 readonly explanation?: string | undefined;
89 readonly cause?: TailscaleCommandError | undefined;
90 },
91 never,
92 ChildProcessSpawner.ChildProcessSpawner
93> =>
94 disableTailscaleServe({ servePort: webPort }).pipe(
95 Effect.as({ cleared: true } as const),
96 Effect.catch((error: TailscaleCommandError) =>
97 Effect.succeed(
98 error._tag === "TailscaleCommandExitError" &&
99 error.stderrDiagnostic === "no-existing-handler"
100 ? ({ cleared: true } as const)
101 : ({
102 cleared: false,
103 ...(explainCommandFailure(error) !== undefined
104 ? { explanation: explainCommandFailure(error) }
105 : {}),
106 cause: error,
107 } as const),
108 ),
109 ),
110 Effect.uninterruptible,
111 );
112
113export interface DevShareResult {
114 readonly url: string;
115 readonly host: string;
116}
117
118/**
119 * Publishes `webPort` on the tailnet. The tailnet port always matches the web
120 * port so the URL is stable; `localTarget` points it at the backend instead
121 * when the backend serves a built client (`--built`).
122 */
123export const shareDevServer = Effect.fn("devShare.shareDevServer")(function* (input: {
124 readonly webPort: number;
125 readonly localTarget?: { readonly port: number; readonly host: string };
126}) {
127 const status = yield* readTailscaleStatus.pipe(
128 Effect.mapError((error) => new TailscaleUnavailableError({ cause: error })),
129 );
130 if (status.magicDnsName === null) {
131 return yield* new TailnetNameMissingError();
132 }
133
134 const cleared = yield* unshareDevServer(input.webPort);
135 if (!cleared.cleared) {
136 // Refuse stale routes: the page could load while /ws and /api still point at a dead backend.
137 return yield* new DevServeFailedError({
138 stage: "clear-existing",
139 webPort: input.webPort,
140 ...(cleared.explanation !== undefined ? { explanation: cleared.explanation } : {}),
141 ...(cleared.cause !== undefined ? { cause: cleared.cause } : {}),
142 });
143 }
144
145 // Vite's localhost can bind only ::1; a 127.0.0.1 proxy target would return 502.
146 yield* ensureTailscaleServe({
147 localPort: input.localTarget?.port ?? input.webPort,
148 servePort: input.webPort,
149 localHost: input.localTarget?.host ?? "localhost",
150 }).pipe(
151 Effect.mapError((error) => {
152 const explanation = explainCommandFailure(error);
153 return new DevServeFailedError({
154 stage: "serve",
155 webPort: input.webPort,
156 ...(explanation !== undefined ? { explanation } : {}),
157 cause: error,
158 });
159 }),
160 );
161
162 return {
163 url: buildTailscaleHttpsBaseUrl({
164 magicDnsName: status.magicDnsName,
165 servePort: input.webPort,
166 }),
167 host: status.magicDnsName,
168 } satisfies DevShareResult;
169});