Skip to content
Closed
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
106 changes: 92 additions & 14 deletions apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,20 +34,31 @@ const isDesktopBackendObservabilitySettingsReadError = Schema.is(
DesktopBackendConfiguration.DesktopBackendObservabilitySettingsReadError,
);

const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
getState: Effect.die("unexpected getState"),
backendConfig: Effect.succeed({
port: 4888,
bindHost: "0.0.0.0",
httpBaseUrl: new URL("http://127.0.0.1:4888"),
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
}),
configureFromSettings: () => Effect.die("unexpected configureFromSettings"),
setMode: () => Effect.die("unexpected setMode"),
setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
getAdvertisedEndpoints: Effect.succeed([]),
} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
type DesktopServerExposureModeLiteral = "local-only" | "network-accessible";

const makeServerExposureLayer = (mode: DesktopServerExposureModeLiteral) =>
Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
getState: Effect.succeed({
mode,
endpointUrl: null,
advertisedHost: null,
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
}),
backendConfig: Effect.succeed({
port: 4888,
bindHost: mode === "network-accessible" ? "0.0.0.0" : "127.0.0.1",
httpBaseUrl: new URL("http://127.0.0.1:4888"),
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
}),
configureFromSettings: () => Effect.die("unexpected configureFromSettings"),
setMode: () => Effect.die("unexpected setMode"),
setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
getAdvertisedEndpoints: Effect.succeed([]),
} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);

const serverExposureLayer = makeServerExposureLayer("network-accessible");

function makeEnvironmentLayer(
baseDir: string,
Expand Down Expand Up @@ -368,6 +379,73 @@ describe("DesktopBackendConfiguration", () => {
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);

const makeWslBindHostTest = (input: {
readonly exposureMode: DesktopServerExposureModeLiteral;
readonly distroIp: string;
}) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const entryPath = path.join(baseDir, "apps/server/dist/bin.mjs");
yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
yield* fileSystem.writeFileString(entryPath, "");

return yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
return yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(makeServerExposureLayer(input.exposureMode)),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
getDistroIp: () => Option.some(input.distroIp),
}),
),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
appPath: baseDir,
platform: "win32",
resourcesPath: baseDir,
}),
),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer));

it.effect("resolveWsl wildcards the WSL bind only when network access is enabled", () =>
makeWslBindHostTest({ exposureMode: "network-accessible", distroIp: "172.27.0.99" }).pipe(
Effect.map((config) => {
assert.equal(config.bootstrap.host, "0.0.0.0");
}),
),
);

it.effect("resolveWsl binds the advertised distro IP when exposure is local-only", () =>
makeWslBindHostTest({ exposureMode: "local-only", distroIp: "172.27.0.99" }).pipe(
Effect.map((config) => {
assert.equal(config.bootstrap.host, "172.27.0.99");
assert.equal(config.httpBaseUrl.href, "http://172.27.0.99:5000/");
}),
),
);

it.effect("resolveWsl binds loopback in mirrored mode when exposure is local-only", () =>
makeWslBindHostTest({ exposureMode: "local-only", distroIp: "127.0.0.1" }).pipe(
Effect.map((config) => {
assert.equal(config.bootstrap.host, "127.0.0.1");
}),
),
);

it.effect("resolveWsl launches a packaged backend from the WSL-local runtime cache", () => {
const observedArchives: Array<{
windowsArchivePath: string;
Expand Down
89 changes: 53 additions & 36 deletions apps/desktop/src/backend/DesktopBackendConfiguration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,9 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
input: SharedBootstrapInput & {
readonly port: number;
readonly distro: string | null;
// Mirrors the Windows primary's resolved exposure mode: a wildcard bind is
// only acceptable when the user opted into network access (see below).
readonly networkAccessible: boolean;
},
): Effect.fn.Return<
DesktopBackendManager.DesktopBackendStartConfig,
Expand All @@ -554,41 +557,6 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
const fileSystem = yield* FileSystem.FileSystem;

// Bind to 0.0.0.0 inside WSL so the backend is reachable both via
// WSL2's automatic localhost forwarding (wslhost: Windows 127.0.0.1
// -> WSL 127.0.0.1) AND via the distro's eth0 IP directly from
// Windows. wslhost forwarding is unreliable on some Windows hosts:
// the desktop's readiness probe and the renderer's saved-env-style
// fetch both saw "Failed to fetch" when the backend only bound to
// 127.0.0.1 inside WSL. Binding to 0.0.0.0 plus advertising the
// WSL IP as the renderer-visible URL avoids that dependency.
// Security-wise this is acceptable for the local-only WSL backend:
// the network it exposes on is the WSL-vEthernet network, not the
// LAN; the primary owns LAN exposure when the user opts in.
const wslBindHost = "0.0.0.0";

const bootstrap = {
mode: "desktop" as const,
noBrowser: true,
port: input.port,
// Omit t3Home so the Linux backend uses its own home dir instead of
// the Windows-side baseDir (which would be a /mnt/c path and share
// the SQLite file with the primary).
host: wslBindHost,
desktopBootstrapToken: input.bootstrapToken,
// PortSchema rejects 0, so when tailscale serve is disabled we still
// need a valid number in this slot. The backend reads tailscaleServePort
// only when tailscaleServeEnabled is true, so the actual value here is
// inert.
tailscaleServeEnabled: false,
tailscaleServePort: 443,
// The packaged sidecar is a Windows executable and cannot run inside the
// Linux WSL backend. Keep the field absent instead of passing an unusable
// `/mnt/.../*.exe` path; WSL resource telemetry is reported unavailable.
// See docs/architecture/resource-telemetry.md.
...buildObservabilityFragment(input.observabilitySettings),
};

// The archive is the primary packaged WSL path: it installs directly into
// the distro's ext4 filesystem. The server.asar extraction service is only
// consulted lazily if the archive is unavailable or cannot be staged.
Expand Down Expand Up @@ -657,6 +625,45 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
: Option.getOrElse(distroIp, () => "127.0.0.1");
const httpBaseUrl = new URL(`http://${rendererHost}:${input.port}`);

// When the user opted into network access, bind to 0.0.0.0 inside WSL so the
// backend is reachable both via WSL2's automatic localhost forwarding
// (wslhost: Windows 127.0.0.1 -> WSL 127.0.0.1) AND via the distro's eth0 IP
// directly from Windows. wslhost forwarding is unreliable on some Windows
// hosts: the desktop's readiness probe and the renderer's saved-env-style
// fetch both saw "Failed to fetch" when the backend only bound to 127.0.0.1
// inside WSL. Binding to 0.0.0.0 plus advertising the WSL IP as the
// renderer-visible URL avoids that dependency.
// In local-only mode the Connections panel promises "limited to this
// machine", so the wildcard bind is not acceptable: it also answers on every
// other distro interface — including tailscale0 when Tailscale runs inside
// the distro — which exposed local-only backends to the whole tailnet.
// Instead, bind exactly the address the renderer is told to use: the distro
// IP in NAT mode (reachable from Windows without depending on flaky wslhost
// forwarding) or loopback in mirrored mode.
const wslBindHost = input.networkAccessible ? "0.0.0.0" : rendererHost;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High backend/DesktopBackendConfiguration.ts:643

Local-only WSL backends bind to an externally reachable address when getDistroIp returns a Tailscale or other non-WSL interface first, so the backend is reachable beyond the local machine. Because wslBindHost uses rendererHost directly, select the WSL vEthernet/eth0 address or reject non-WSL private addresses before using it here.

🤖 Copy this AI Prompt to have your agent fix this:
In file @apps/desktop/src/backend/DesktopBackendConfiguration.ts around line 643:

Local-only WSL backends bind to an externally reachable address when `getDistroIp` returns a Tailscale or other non-WSL interface first, so the backend is reachable beyond the local machine. Because `wslBindHost` uses `rendererHost` directly, select the WSL vEthernet/`eth0` address or reject non-WSL private addresses before using it here.


const bootstrap = {
mode: "desktop" as const,
noBrowser: true,
port: input.port,
// Omit t3Home so the Linux backend uses its own home dir instead of
// the Windows-side baseDir (which would be a /mnt/c path and share
// the SQLite file with the primary).
host: wslBindHost,
desktopBootstrapToken: input.bootstrapToken,
// PortSchema rejects 0, so when tailscale serve is disabled we still
// need a valid number in this slot. The backend reads tailscaleServePort
// only when tailscaleServeEnabled is true, so the actual value here is
// inert.
tailscaleServeEnabled: false,
tailscaleServePort: 443,
// The packaged sidecar is a Windows executable and cannot run inside the
// Linux WSL backend. Keep the field absent instead of passing an unusable
// `/mnt/.../*.exe` path; WSL resource telemetry is reported unavailable.
// See docs/architecture/resource-telemetry.md.
...buildObservabilityFragment(input.observabilitySettings),
};

const distroArgs = distroForConfig ? ["-d", distroForConfig] : [];
const forwardedEnv: Record<string, string> = {};
const forwardedEnvNames: string[] = [];
Expand Down Expand Up @@ -806,6 +813,13 @@ export const make = Effect.gen(function* () {
return { bootstrapToken, observabilitySettings } satisfies SharedBootstrapInput;
});

// The WSL backend must mirror the primary's exposure mode: only a
// network-accessible primary justifies the wildcard WSL bind.
const readNetworkAccessible = Effect.map(
serverExposure.getState,
(state) => state.mode === "network-accessible",
);

const buildWslPrimaryConfig = Effect.gen(function* () {
// wsl-only mode pipes the WSL backend through the same port the
// Windows primary would normally take. That way the renderer
Expand All @@ -814,13 +828,15 @@ export const make = Effect.gen(function* () {
// auth, the env switcher's "primary" id) keep working without
// a parallel "secondary" registration.
const backendExposure = yield* serverExposure.backendConfig;
const networkAccessible = yield* readNetworkAccessible;
const persistedSettings = yield* settings.get;
const shared = yield* sharedInputs;
yield* wslEnvironment.preWarm(persistedSettings.wslDistro);
return yield* resolveWslStartConfig({
...shared,
port: backendExposure.port,
distro: persistedSettings.wslDistro,
networkAccessible,
}).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
Expand Down Expand Up @@ -884,7 +900,8 @@ export const make = Effect.gen(function* () {
resolveWsl: (input) =>
Effect.gen(function* () {
const shared = yield* sharedInputs;
return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
const networkAccessible = yield* readNetworkAccessible;
return yield* resolveWslStartConfig({ ...shared, networkAccessible, ...input }).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
Expand Down
Loading