Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions apps/desktop/src/backend/DesktopServerExposure.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,45 @@ describe("DesktopServerExposure", () => {
),
);

it.effect("refuses a Tailscale Serve port that already serves another service", () => {
const serveStatus = JSON.stringify({
TCP: { "443": { HTTPS: true } },
Web: {
"box.tailnet.ts.net:443": {
Handlers: {
"/": { Proxy: "http://127.0.0.1:9000" },
"/mcp": { Proxy: "http://127.0.0.1:8080" },
},
},
},
});
return withHarness(
emptyNetworkInterfaces,
Effect.gen(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const settings = yield* DesktopAppSettings.DesktopAppSettings;

yield* settings.load;
yield* serverExposure.configureFromSettings({ port: 4173 });

const error = yield* serverExposure
.setTailscaleServeEnabled({ enabled: true, port: 443 })
.pipe(Effect.flip);
assert.instanceOf(error, DesktopServerExposure.DesktopTailscaleServePortInUseError);
assert.include(error.message, "port 443");
assert.isFalse((yield* settings.get).tailscaleServeEnabled);

const moved = yield* serverExposure.setTailscaleServeEnabled({
enabled: true,
port: 8443,
});
assert.equal(moved.state.tailscaleServePort, 8443);
}),
{},
layerMockSpawner(serveStatus),
);
});

it.effect("keeps a Tailscale Serve change made while a mode change is saving", () =>
Effect.gen(function* () {
const modeWriteStarted = yield* Deferred.make<void>();
Expand Down
36 changes: 34 additions & 2 deletions apps/desktop/src/backend/DesktopServerExposure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ import {
type DesktopServerExposureMode,
type DesktopServerExposureState,
} from "@t3tools/contracts";
import { isTailscaleIpv4Address, readTailscaleStatus } from "@t3tools/tailscale";
import {
isTailscaleIpv4Address,
readTailscaleServeRoutesBlocking,
readTailscaleStatus,
} from "@t3tools/tailscale";
import * as Cache from "effect/Cache";
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
Expand Down Expand Up @@ -245,6 +249,15 @@ export class DesktopTailscaleServePersistenceError extends Schema.TaggedError<De
}
}

export class DesktopTailscaleServePortInUseError extends Schema.TaggedError<DesktopTailscaleServePortInUseError>()(
"DesktopTailscaleServePortInUseError",
{ port: Schema.Number },
) {
override get message(): string {
return `HTTPS port ${this.port} on this machine already serves other Tailscale Serve routes. Choose another port.`;
}
}

export const DesktopServerExposureSetModeError = Schema.Union([
DesktopServerExposureNoNetworkAddressError,
DesktopServerExposureModePersistenceError,
Expand All @@ -255,6 +268,7 @@ export const DesktopServerExposureError = Schema.Union([
DesktopServerExposureNoNetworkAddressError,
DesktopServerExposureModePersistenceError,
DesktopTailscaleServePersistenceError,
DesktopTailscaleServePortInUseError,
]);
export type DesktopServerExposureError = typeof DesktopServerExposureError.Type;

Expand Down Expand Up @@ -285,7 +299,10 @@ export class DesktopServerExposure extends Context.Service<
readonly setTailscaleServeEnabled: (input: {
readonly enabled: boolean;
readonly port?: number;
}) => Effect.Effect<DesktopServerExposureChange, DesktopTailscaleServePersistenceError>;
}) => Effect.Effect<
DesktopServerExposureChange,
DesktopTailscaleServePersistenceError | DesktopTailscaleServePortInUseError
>;
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
}
>()("@t3tools/desktop/backend/DesktopServerExposure") {}
Expand Down Expand Up @@ -571,6 +588,21 @@ export const make = Effect.gen(function* () {
enabled: input.enabled,
...(input.port === undefined ? {} : { port: input.port }),
});
if (input.enabled) {
// The backend checks again before it serves; this names the port while another can be picked.
const current = yield* Ref.get(stateRef);
const servePort = input.port ?? current.tailscaleServePort;
const blocking = yield* readTailscaleServeRoutesBlocking({
servePort,
target: { host: "127.0.0.1", port: current.port },
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
Effect.orElseSucceed(() => []),
);
if (blocking.length > 0) {
return yield* new DesktopTailscaleServePortInUseError({ port: servePort });
}
}
const result = yield* desktopSettings
.setTailscaleServe({
enabled: input.enabled,
Expand Down
98 changes: 75 additions & 23 deletions apps/server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,8 +251,10 @@ import * as ProjectHttp from "./project/http.ts";
import * as NetService from "@t3tools/shared/Net";
import * as RelayClient from "@t3tools/shared/relayClient";
import {
blocksTailscaleServeDeadRootRecovery,
disableTailscaleServe,
ensureTailscaleServe,
readTailscaleServeRoutesBlocking,
readTailscaleServeRootHolder,
readTailscaleServeRoutesTo,
readTailscaleStatus,
Expand Down Expand Up @@ -1074,18 +1076,56 @@ const layerMakeServer = Layer.unwrap(
if (holder === "other" || holder === "unreadable") {
yield* Effect.logWarning(
holder === "other"
? "Tailscale Serve left off; its port already serves another server or app"
: "Tailscale Serve left off; its current routes could not be read",
? "T3 skipped configuring Tailscale Serve; its port already serves another server or app"
: "T3 skipped configuring Tailscale Serve; its current routes could not be read",
{ localPort, servePort: config.tailscaleServePort },
);
return route;
return { route, recover: true };
}

// The root-holder check permits reclaiming a dead stale root. Other handlers on the
// same port still belong to their current owners and must not be replaced.
const blockingResult = yield* readTailscaleServeRoutesBlocking({
servePort: config.tailscaleServePort,
target: { host: route.localHost, port: localPort },
}).pipe(
Effect.match({
onFailure: (cause) => ({ cause }) as const,
onSuccess: (routes) => ({ routes }) as const,
}),
);
if ("cause" in blockingResult) {
yield* Effect.logWarning(
"T3 skipped configuring Tailscale Serve; its current routes could not be checked",
{
causeTag: blockingResult.cause._tag,
localPort,
servePort: config.tailscaleServePort,
},
);
return holder === "ours" ? { route, recover: false } : null;
}
const blockingRoutes =
holder === "dead"
? blockingResult.routes.filter(blocksTailscaleServeDeadRootRecovery)
: blockingResult.routes;
if (blockingRoutes.length > 0) {
yield* Effect.logWarning(
"T3 skipped configuring Tailscale Serve; its port already serves other routes",
{
localPort,
routeCount: blockingRoutes.length,
servePort: config.tailscaleServePort,
},
);
return holder === "ours" ? { route, recover: false } : null;
}
return yield* ensureTailscaleServe({
localPort,
servePort: config.tailscaleServePort,
localHost,
}).pipe(
Effect.as(route),
Effect.as({ route, recover: true }),
Effect.tap(() =>
Effect.logInfo("Tailscale Serve configured", {
localPort,
Expand All @@ -1108,8 +1148,8 @@ const layerMakeServer = Layer.unwrap(
? Effect.all(
[
readTailscaleServeRoutesTo({
host: configured.localHost,
port: configured.localPort,
host: configured.route.localHost,
port: configured.route.localPort,
}),
readTailscaleStatus,
],
Expand All @@ -1120,7 +1160,7 @@ const layerMakeServer = Layer.unwrap(
Effect.map(([routes, status]) =>
routes.some(
(route) =>
route.servePort === configured.servePort &&
route.servePort === configured.route.servePort &&
route.mount === "/" &&
route.owner === undefined &&
route.ambiguous === undefined &&
Expand All @@ -1130,24 +1170,24 @@ const layerMakeServer = Layer.unwrap(
Effect.orElseSucceed(() => false),
Effect.flatMap((ours) =>
ours
? disableTailscaleServe({ servePort: configured.servePort }).pipe(
? disableTailscaleServe({ servePort: configured.route.servePort }).pipe(
Effect.tap(() =>
Effect.logInfo("Tailscale Serve disabled", {
servePort: configured.servePort,
servePort: configured.route.servePort,
}),
),
)
: Effect.logInfo(
"Tailscale Serve left on; its root route is not known to be ours",
{
servePort: configured.servePort,
servePort: configured.route.servePort,
},
),
),
Effect.catch((cause) =>
Effect.logWarning("Failed to disable Tailscale Serve", {
cause,
servePort: configured.servePort,
servePort: configured.route.servePort,
}),
),
)
Expand All @@ -1156,27 +1196,39 @@ const layerMakeServer = Layer.unwrap(
// Startup is not the only time the route can go stale, so whoever finds it on a dead
// port takes it back.
Effect.tap((configured) =>
configured === null
configured === null || !configured.recover
? Effect.void
: Effect.sleep("30 seconds").pipe(
Effect.andThen(
tailscaleServeRootHolder({
host: configured.localHost,
port: configured.localPort,
host: configured.route.localHost,
port: configured.route.localPort,
}),
),
Effect.flatMap((holder) =>
holder === "dead"
? ensureTailscaleServe({
localPort: configured.localPort,
servePort: configured.servePort,
localHost: configured.urlHost,
? readTailscaleServeRoutesBlocking({
servePort: configured.route.servePort,
target: {
host: configured.route.localHost,
port: configured.route.localPort,
},
}).pipe(
Effect.andThen(
Effect.logInfo("Tailscale Serve repaired", {
localPort: configured.localPort,
servePort: configured.servePort,
}),
Effect.flatMap((routes) =>
routes.some(blocksTailscaleServeDeadRootRecovery)
? Effect.void
: ensureTailscaleServe({
localPort: configured.route.localPort,
servePort: configured.route.servePort,
localHost: configured.route.urlHost,
}).pipe(
Effect.andThen(
Effect.logInfo("Tailscale Serve repaired", {
localPort: configured.route.localPort,
servePort: configured.route.servePort,
}),
),
),
),
)
: Effect.void,
Expand Down
64 changes: 45 additions & 19 deletions apps/web/src/components/settings/ConnectionsSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,7 @@ function ConnectionsSettingsContent({
parsedTailscaleServePort >= 1 &&
parsedTailscaleServePort <= 65_535;

const isChangingTailscaleServePort = desktopServerExposureState?.tailscaleServeEnabled === true;
const pendingTailscaleServeBaseUrl = resolveTailscaleServeBaseUrl(
pendingTailscaleServeEndpoint,
parsedTailscaleServePort,
Expand Down Expand Up @@ -629,7 +630,7 @@ function ConnectionsSettingsContent({
setIsUpdatingTailscaleServe(false);
};

const handleStartTailscaleServeDisable = (_endpoint: AdvertisedEndpoint) => {
const handleStartTailscaleServeDisable = () => {
setDisableTailscaleServeDialogOpen(true);
};

Expand Down Expand Up @@ -1154,19 +1155,32 @@ function ConnectionsSettingsContent({
: missingTailscaleEndpointDescription(desktopServerExposureState, m)
}
control={
tailscaleHttpsEndpoint ? (
<Switch
checked={tailscaleHttpsEndpoint.status === "available"}
disabled={isUpdatingTailscaleServe}
onCheckedChange={(checked) => {
if (checked) {
handleStartTailscaleServeSetup(tailscaleHttpsEndpoint);
return;
}
handleStartTailscaleServeDisable(tailscaleHttpsEndpoint);
}}
aria-label={gt("Enable Tailscale HTTPS")}
/>
tailscaleHttpsEndpoint || desktopServerExposureState?.tailscaleServeEnabled ? (
<div className="flex items-center gap-2">
{desktopServerExposureState?.tailscaleServeEnabled && tailscaleHttpsEndpoint ? (
<Button
size="xs"
variant="outline"
disabled={isUpdatingTailscaleServe}
onClick={() => handleStartTailscaleServeSetup(tailscaleHttpsEndpoint)}
>
{gt("Change port")}
</Button>
) : null}
<Switch
checked={desktopServerExposureState?.tailscaleServeEnabled === true}
disabled={isUpdatingTailscaleServe}
onCheckedChange={(checked) => {
if (checked) {
if (tailscaleHttpsEndpoint)
handleStartTailscaleServeSetup(tailscaleHttpsEndpoint);
return;
}
handleStartTailscaleServeDisable();
}}
aria-label={gt("Enable Tailscale HTTPS")}
/>
</div>
) : null
}
managed={tailscaleHttpsEndpoint?.status === "available" ? undefined : remoteClientsDenial}
Expand Down Expand Up @@ -1743,13 +1757,23 @@ function ConnectionsSettingsContent({
<DialogPopup className="max-w-md">
<DialogHeader>
<DialogTitle>
<T>Set up Tailscale HTTPS?</T>
{isChangingTailscaleServePort ? (
gt("Change the Tailscale HTTPS port?")
) : (
<T>Set up Tailscale HTTPS?</T>
)}
</DialogTitle>
<DialogDescription>
<T>
T3 Code will restart the local backend with Tailscale Serve enabled and ask
Tailscale to proxy HTTPS traffic to this backend.
</T>
{isChangingTailscaleServePort ? (
gt(
"Changing the port removes the old Serve route. Make sure saved clients have another reachable route; after the restart, add the new HTTPS route to them.",
)
) : (
<T>
T3 Code will restart the local backend with Tailscale Serve enabled and ask
Tailscale to proxy HTTPS traffic to this backend.
</T>
)}
</DialogDescription>
</DialogHeader>
<DialogPanel>
Expand Down Expand Up @@ -1808,6 +1832,8 @@ function ConnectionsSettingsContent({
<Spinner size="sm" />
<T>Restarting…</T>
</>
) : isChangingTailscaleServePort ? (
gt("Change port")
) : (
gt("Enable")
)}
Expand Down
Loading
Loading