Skip to content

Commit 3c27d3e

Browse files
committed
Harden server bind defaults and WebSocket origin checks
- Default web mode host to `127.0.0.1` - Refuse non-loopback binds unless `--auth-token`/`T3CODE_AUTH_TOKEN` is set - Reject browser WebSocket upgrades from untrusted origins (allow same-host or configured dev origin) - Update docs, CLI help text, and tests for new security behavior
1 parent 59b0527 commit 3c27d3e

6 files changed

Lines changed: 145 additions & 15 deletions

File tree

‎REMOTE.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,11 @@ The T3 Code CLI accepts the following configuration options, available either as
2020
2121
## Security First
2222

23+
- The server now binds to `127.0.0.1` by default in `web` mode. Remote access requires an explicit `--host`.
2324
- Always set `--auth-token` before exposing the server outside localhost.
2425
- Treat the token like a password.
2526
- Prefer binding to trusted interfaces (LAN IP or Tailnet IP) instead of opening all interfaces unless needed.
27+
- Non-loopback binds without `--auth-token` are rejected at startup.
2628

2729
## 1) Build + run server for remote access
2830

‎apps/server/src/config.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ export const DEFAULT_PORT = 3773;
1212

1313
export type RuntimeMode = "web" | "desktop";
1414

15+
const LOOPBACK_HOSTS = new Set(["127.0.0.1", "::1", "[::1]", "localhost"]);
16+
1517
/**
1618
* ServerConfigShape - Process/runtime configuration required by the server.
1719
*/
@@ -59,6 +61,15 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS
5961
);
6062
}
6163

64+
export const isWildcardHost = (host: string | undefined): boolean =>
65+
host === "0.0.0.0" || host === "::" || host === "[::]";
66+
67+
export const isLoopbackHost = (host: string | undefined): boolean =>
68+
host !== undefined && LOOPBACK_HOSTS.has(host.trim().toLowerCase());
69+
70+
export const formatHostForUrl = (host: string): string =>
71+
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
72+
6273
export const resolveStaticDir = Effect.fn(function* () {
6374
const { join, resolve } = yield* Path.Path;
6475
const { exists } = yield* FileSystem.FileSystem;

‎apps/server/src/main.test.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ it.layer(testLayer)("server CLI command", (it) => {
163163
assert.equal(start.mock.calls.length, 1);
164164
assert.equal(resolvedConfig?.mode, "web");
165165
assert.equal(resolvedConfig?.port, 4666);
166-
assert.equal(resolvedConfig?.host, undefined);
166+
assert.equal(resolvedConfig?.host, "127.0.0.1");
167167
}),
168168
);
169169

@@ -209,6 +209,7 @@ it.layer(testLayer)("server CLI command", (it) => {
209209
Effect.gen(function* () {
210210
yield* runCli(["--host", "0.0.0.0"], {
211211
T3CODE_MODE: "desktop",
212+
T3CODE_AUTH_TOKEN: "desktop-token",
212213
T3CODE_NO_BROWSER: "true",
213214
});
214215

@@ -218,6 +219,17 @@ it.layer(testLayer)("server CLI command", (it) => {
218219
}),
219220
);
220221

222+
it.effect("refuses non-loopback web binds without auth", () =>
223+
Effect.gen(function* () {
224+
yield* runCli(["--host", "0.0.0.0"], {
225+
T3CODE_NO_BROWSER: "true",
226+
}).pipe(Effect.catch(() => Effect.void));
227+
228+
assert.equal(start.mock.calls.length, 0);
229+
assert.equal(stop.mock.calls.length, 0);
230+
}),
231+
);
232+
221233
it.effect("supports CLI and env for bootstrap/log websocket toggles", () =>
222234
Effect.gen(function* () {
223235
yield* runCli(["--auto-bootstrap-project-from-cwd"], {

‎apps/server/src/main.ts‎

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@ import { Command, Flag } from "effect/unstable/cli";
1111
import { NetService } from "@t3tools/shared/Net";
1212
import {
1313
DEFAULT_PORT,
14+
formatHostForUrl,
15+
isLoopbackHost,
16+
isWildcardHost,
1417
resolveStaticDir,
1518
ServerConfig,
1619
type RuntimeMode,
@@ -169,10 +172,14 @@ const ServerConfigLive = (input: CliInput) =>
169172
const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
170173
const { join } = yield* Path.Path;
171174
const keybindingsConfigPath = join(stateDir, "keybindings.json");
172-
const host =
173-
Option.getOrUndefined(input.host) ??
174-
env.host ??
175-
(mode === "desktop" ? "127.0.0.1" : undefined);
175+
const host = Option.getOrUndefined(input.host) ?? env.host ?? "127.0.0.1";
176+
177+
if (!isLoopbackHost(host) && !authToken) {
178+
return yield* new StartupError({
179+
message:
180+
"Refusing to bind a non-loopback host without WebSocket auth. Set --auth-token (or T3CODE_AUTH_TOKEN), or bind to 127.0.0.1.",
181+
});
182+
}
176183

177184
const config: ServerConfigShape = {
178185
mode,
@@ -204,12 +211,6 @@ const LayerLive = (input: CliInput) =>
204211
Layer.provideMerge(ServerConfigLive(input)),
205212
);
206213

207-
const isWildcardHost = (host: string | undefined): boolean =>
208-
host === "0.0.0.0" || host === "::" || host === "[::]";
209-
210-
const formatHostForUrl = (host: string): string =>
211-
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
212-
213214
export const recordStartupHeartbeat = Effect.gen(function* () {
214215
const analytics = yield* AnalyticsService;
215216
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
@@ -296,7 +297,9 @@ const portFlag = Flag.integer("port").pipe(
296297
Flag.optional,
297298
);
298299
const hostFlag = Flag.string("host").pipe(
299-
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
300+
Flag.withDescription(
301+
"Host/interface to bind (defaults to 127.0.0.1; use --auth-token with non-loopback hosts).",
302+
),
300303
Flag.optional,
301304
);
302305
const stateDirFlag = Flag.string("state-dir").pipe(
@@ -313,7 +316,7 @@ const noBrowserFlag = Flag.boolean("no-browser").pipe(
313316
Flag.optional,
314317
);
315318
const authTokenFlag = Flag.string("auth-token").pipe(
316-
Flag.withDescription("Auth token required for WebSocket connections."),
319+
Flag.withDescription("Auth token required for WebSocket connections on non-loopback binds."),
317320
Flag.withAlias("token"),
318321
Flag.optional,
319322
);

‎apps/server/src/wsServer.test.ts‎

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,35 @@ function connectWs(port: number, token?: string): Promise<WebSocket> {
236236
});
237237
}
238238

239+
function connectWsWithOrigin(
240+
port: number,
241+
options: { token?: string; origin: string },
242+
): Promise<WebSocket> {
243+
return new Promise((resolve, reject) => {
244+
const query = options.token ? `?token=${encodeURIComponent(options.token)}` : "";
245+
const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`, {
246+
headers: {
247+
Origin: options.origin,
248+
},
249+
});
250+
const pending: PendingMessages = { queue: [], waiters: [] };
251+
pendingBySocket.set(ws, pending);
252+
253+
ws.on("message", (raw) => {
254+
const parsed = JSON.parse(String(raw));
255+
const waiter = pending.waiters.shift();
256+
if (waiter) {
257+
waiter(parsed);
258+
return;
259+
}
260+
pending.queue.push(parsed);
261+
});
262+
263+
ws.once("open", () => resolve(ws));
264+
ws.once("error", () => reject(new Error("WebSocket connection failed")));
265+
});
266+
}
267+
239268
function waitForMessage(ws: WebSocket): Promise<unknown> {
240269
const pending = pendingBySocket.get(ws);
241270
if (!pending) {
@@ -388,6 +417,7 @@ describe("WebSocket Server", () => {
388417
logWebSocketEvents?: boolean;
389418
devUrl?: string;
390419
authToken?: string;
420+
host?: string;
391421
stateDir?: string;
392422
staticDir?: string;
393423
providerLayer?: Layer.Layer<ProviderService, never>;
@@ -414,7 +444,7 @@ describe("WebSocket Server", () => {
414444
const serverConfigLayer = Layer.succeed(ServerConfig, {
415445
mode: "web",
416446
port: 0,
417-
host: undefined,
447+
host: options.host ?? "127.0.0.1",
418448
cwd: options.cwd ?? "/test/project",
419449
keybindingsConfigPath: path.join(stateDir, "keybindings.json"),
420450
stateDir,
@@ -1704,4 +1734,33 @@ describe("WebSocket Server", () => {
17041734
const welcome = (await waitForMessage(authorizedWs)) as WsPush;
17051735
expect(welcome.channel).toBe(WS_CHANNELS.serverWelcome);
17061736
});
1737+
1738+
it("rejects browser websocket upgrades from foreign origins", async () => {
1739+
server = await createTestServer({ cwd: "/test" });
1740+
const addr = server.address();
1741+
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
1742+
1743+
await expect(
1744+
connectWsWithOrigin(port, {
1745+
origin: "https://evil.example",
1746+
}),
1747+
).rejects.toThrow("WebSocket connection failed");
1748+
});
1749+
1750+
it("accepts browser websocket upgrades from the configured dev origin", async () => {
1751+
server = await createTestServer({
1752+
cwd: "/test",
1753+
devUrl: "http://localhost:5173",
1754+
});
1755+
const addr = server.address();
1756+
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
1757+
1758+
const ws = await connectWsWithOrigin(port, {
1759+
origin: "http://localhost:5173",
1760+
});
1761+
connections.push(ws);
1762+
1763+
const welcome = (await waitForMessage(ws)) as WsPush;
1764+
expect(welcome.channel).toBe(WS_CHANNELS.serverWelcome);
1765+
});
17071766
});

‎apps/server/src/wsServer.ts‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,8 +107,14 @@ const isServerNotRunningError = (error: unknown): boolean => {
107107
};
108108

109109
function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void {
110+
const statusText =
111+
statusCode === 401
112+
? "Unauthorized"
113+
: statusCode === 403
114+
? "Forbidden"
115+
: "Bad Request";
110116
socket.end(
111-
`HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` +
117+
`HTTP/1.1 ${statusCode} ${statusText}\r\n` +
112118
"Connection: close\r\n" +
113119
"Content-Type: text/plain\r\n" +
114120
`Content-Length: ${Buffer.byteLength(message)}\r\n` +
@@ -238,6 +244,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
238244
> {
239245
const serverConfig = yield* ServerConfig;
240246
const {
247+
mode,
241248
port,
242249
cwd,
243250
keybindingsConfigPath,
@@ -943,6 +950,37 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
943950
ws.send(response);
944951
});
945952

953+
function isTrustedBrowserOrigin(request: http.IncomingMessage): boolean {
954+
if (mode !== "web") {
955+
return true;
956+
}
957+
958+
const originHeader = request.headers.origin;
959+
if (!originHeader) {
960+
// Non-browser clients typically omit Origin. Browser clients should present one.
961+
return true;
962+
}
963+
964+
let parsedOrigin: URL;
965+
try {
966+
parsedOrigin = new URL(originHeader);
967+
} catch {
968+
return false;
969+
}
970+
971+
const requestHost = request.headers.host?.trim().toLowerCase();
972+
const originHost = parsedOrigin.host.trim().toLowerCase();
973+
if (
974+
(parsedOrigin.protocol === "http:" || parsedOrigin.protocol === "https:") &&
975+
requestHost &&
976+
originHost === requestHost
977+
) {
978+
return true;
979+
}
980+
981+
return devUrl !== undefined && parsedOrigin.origin === devUrl.origin;
982+
}
983+
946984
httpServer.on("upgrade", (request, socket, head) => {
947985
socket.on("error", () => {}); // Prevent unhandled `EPIPE`/`ECONNRESET` from crashing the process if the client disconnects mid-handshake
948986

@@ -962,6 +1000,11 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
9621000
}
9631001
}
9641002

1003+
if (!isTrustedBrowserOrigin(request)) {
1004+
rejectUpgrade(socket, 403, "Forbidden WebSocket origin");
1005+
return;
1006+
}
1007+
9651008
wss.handleUpgrade(request, socket, head, (ws) => {
9661009
wss.emit("connection", ws, request);
9671010
});

0 commit comments

Comments
 (0)