fix: support reverse-proxied dev origins

This commit is contained in:
Ben Davis committed 2026-07-24 21:11:47 -07:00
1 parent 1fa4219b48
commit 35ddbc4ab1
13 files changed
+298 -34

No files matched your search

+2 -1
View File
@@ -128,7 +128,8 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
Effect.provide(
makeEnvironmentAuthLayer({
mode: "web",
port: 7446,
port: 13773,
authCookiePort: 7446,
}),
),
),
@@ -98,6 +98,24 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
),
);
it.effect("uses the browser-facing port when a reverse proxy changes the port", () =>
Effect.gen(function* () {
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
const descriptor = yield* policy.getDescriptor();
expect(descriptor.sessionCookieName).toBe("t3_session_7446");
}).pipe(
Effect.provide(
makeEnvironmentAuthPolicyLayer({
mode: "web",
host: "127.0.0.1",
port: 13773,
authCookiePort: 7446,
}),
),
),
);
it.effect("uses remote-reachable policy for wildcard web hosts", () =>
Effect.gen(function* () {
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
@@ -40,7 +40,7 @@ export const make = Effect.gen(function* () {
sessionMethods: ["browser-session-cookie", "bearer-access-token", "dpop-access-token"],
sessionCookieName: resolveSessionCookieName({
mode: config.mode,
port: config.port,
port: config.authCookiePort ?? config.port,
}),
};
+1 -1
View File
@@ -469,7 +469,7 @@ export const make = Effect.gen(function* () {
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
const cookieName = resolveSessionCookieName({
mode: serverConfig.mode,
port: serverConfig.port,
port: serverConfig.authCookiePort ?? serverConfig.port,
});
const emitUpsert = (clientSession: AuthClientSession) =>
+5
View File
@@ -92,6 +92,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
T3CODE_LOG_LEVEL: "Warn",
T3CODE_MODE: "desktop",
T3CODE_PORT: "4001",
T3CODE_AUTH_COOKIE_PORT: "7446",
T3CODE_HOST: "0.0.0.0",
T3CODE_HOME: baseDir,
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
@@ -111,6 +112,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
...defaultObservabilityConfig,
mode: "desktop",
port: 4001,
authCookiePort: 7446,
cwd: process.cwd(),
baseDir,
...derivedPaths,
@@ -141,6 +143,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
{
mode: Option.some("web"),
port: Option.some(8788),
authCookiePort: Option.some(9443),
host: Option.some("127.0.0.1"),
baseDir: Option.some(baseDir),
cwd: Option.none(),
@@ -162,6 +165,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
T3CODE_LOG_LEVEL: "Warn",
T3CODE_MODE: "desktop",
T3CODE_PORT: "4001",
T3CODE_AUTH_COOKIE_PORT: "7446",
T3CODE_HOST: "0.0.0.0",
T3CODE_HOME: join(NodeOS.tmpdir(), "ignored-base"),
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
@@ -181,6 +185,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
...defaultObservabilityConfig,
mode: "web",
port: 8788,
authCookiePort: 9443,
cwd: process.cwd(),
baseDir,
...derivedPaths,
+25
View File
@@ -26,6 +26,13 @@ export const portFlag = Flag.integer("port").pipe(
Flag.withDescription("Port for the HTTP/WebSocket server."),
Flag.optional,
);
export const authCookiePortFlag = Flag.integer("auth-cookie-port").pipe(
Flag.withSchema(PortSchema),
Flag.withDescription(
"Browser-facing port used to namespace auth cookies when a reverse proxy exposes a different port.",
),
Flag.optional,
);
export const hostFlag = Flag.string("host").pipe(
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
Flag.optional,
@@ -103,6 +110,10 @@ const EnvServerConfig = Config.all({
Config.map(Option.getOrUndefined),
),
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
authCookiePort: Config.port("T3CODE_AUTH_COOKIE_PORT").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
@@ -135,6 +146,7 @@ const EnvServerConfig = Config.all({
export interface CliServerFlags {
readonly mode: Option.Option<ServerConfig.RuntimeMode>;
readonly port: Option.Option<number>;
readonly authCookiePort?: Option.Option<number>;
readonly host: Option.Option<string>;
readonly baseDir: Option.Option<string>;
readonly cwd: Option.Option<string>;
@@ -164,6 +176,7 @@ export const projectLocationFlags = {
export const sharedServerCommandFlags = {
mode: modeFlag,
port: portFlag,
authCookiePort: authCookiePortFlag,
host: hostFlag,
baseDir: baseDirFlag,
cwd: Argument.string("cwd").pipe(
@@ -214,6 +227,7 @@ export const resolveServerConfig = (
const normalizedFlags = {
mode: flags.mode ?? Option.none(),
port: flags.port ?? Option.none(),
authCookiePort: flags.authCookiePort ?? Option.none(),
host: flags.host ?? Option.none(),
baseDir: flags.baseDir ?? Option.none(),
cwd: flags.cwd ?? Option.none(),
@@ -257,6 +271,12 @@ export const resolveServerConfig = (
},
},
);
const explicitlyConfiguredAuthCookiePort = Option.getOrUndefined(
resolveOptionPrecedence(
normalizedFlags.authCookiePort,
Option.fromUndefinedOr(env.authCookiePort),
),
);
const devUrl = Option.getOrElse(
resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),
() => undefined,
@@ -326,6 +346,9 @@ export const resolveServerConfig = (
),
() => 443,
);
const authCookiePort =
explicitlyConfiguredAuthCookiePort ??
(tailscaleServeEnabled ? tailscaleServePort : undefined);
const staticDir = devUrl ? undefined : yield* ServerConfig.resolveStaticDir();
const host = Option.getOrElse(
resolveOptionPrecedence(
@@ -356,6 +379,7 @@ export const resolveServerConfig = (
otlpServiceName: env.otlpServiceName,
mode,
port,
...(authCookiePort !== undefined ? { authCookiePort } : {}),
cwd,
baseDir,
...derivedPaths,
@@ -383,6 +407,7 @@ export const resolveCliAuthConfig = (
{
mode: Option.none(),
port: Option.none(),
authCookiePort: Option.none(),
host: Option.none(),
baseDir: flags.baseDir,
cwd: Option.none(),
+1
View File
@@ -67,6 +67,7 @@ export class ServerConfig extends Context.Service<
readonly otlpServiceName: string;
readonly mode: RuntimeMode;
readonly port: number;
readonly authCookiePort?: number;
readonly host: string | undefined;
readonly cwd: string;
readonly baseDir: string;
+21
View File
@@ -0,0 +1,21 @@
import { describe, expect, it } from "vite-plus/test";
import { resolveDevProxyTarget } from "./viteHelpers";
describe("resolveDevProxyTarget", () => {
it("keeps the dev proxy on the private backend when the browser URL is public", () => {
const browserWebSocketUrl = "wss://siva.example.test:7446";
const privateProxyUrl = "http://localhost:13773";
expect(resolveDevProxyTarget(privateProxyUrl)).toBe("http://localhost:13773/");
expect(resolveDevProxyTarget(privateProxyUrl)).not.toBe(
resolveDevProxyTarget(browserWebSocketUrl),
);
});
it("converts websocket schemes and strips paths", () => {
expect(resolveDevProxyTarget("ws://localhost:13773/api/hermes-gateway/ws?token=test")).toBe(
"http://localhost:13773/",
);
});
});
+20
View File
@@ -0,0 +1,20 @@
export function resolveDevProxyTarget(rawUrl: string | undefined) {
if (!rawUrl) {
return undefined;
}
try {
const url = new URL(rawUrl);
if (url.protocol === "ws:") {
url.protocol = "http:";
} else if (url.protocol === "wss:") {
url.protocol = "https:";
}
url.pathname = "";
url.search = "";
url.hash = "";
return url.toString();
} catch {
return undefined;
}
}
+29 -28
View File
@@ -8,6 +8,7 @@ import { defineConfig } from "vite-plus";
import pkg from "./package.json" with { type: "json" };
import { loadRepoEnv } from "../../scripts/lib/public-config";
import { resolveDevProxyTarget } from "./src/viteHelpers";
const repoEnv = loadRepoEnv();
Object.assign(process.env, repoEnv);
@@ -15,6 +16,18 @@ Object.assign(process.env, repoEnv);
const port = Number(process.env.PORT ?? 5733);
const host = process.env.HOST?.trim() || "localhost";
const configuredWsUrl = process.env.VITE_WS_URL?.trim();
const configuredDevProxyUrl = process.env.T3CODE_DEV_PROXY_URL?.trim();
const configuredDevServerUrl = (() => {
const rawValue = process.env.VITE_DEV_SERVER_URL?.trim();
if (!rawValue) {
return undefined;
}
try {
return new URL(rawValue);
} catch {
return undefined;
}
})();
const configuredRelayUrl = repoEnv.VITE_T3CODE_RELAY_URL?.trim() || "";
const configuredClerkPublishableKey = repoEnv.VITE_CLERK_PUBLISHABLE_KEY?.trim() || "";
const configuredClerkJwtTemplate = repoEnv.VITE_CLERK_JWT_TEMPLATE?.trim() || "";
@@ -65,28 +78,7 @@ const unitTestProject = {
},
} satisfies TestProjectInlineConfiguration;
function resolveDevProxyTarget(wsUrl: string | undefined): string | undefined {
if (!wsUrl) {
return undefined;
}
try {
const url = new URL(wsUrl);
if (url.protocol === "ws:") {
url.protocol = "http:";
} else if (url.protocol === "wss:") {
url.protocol = "https:";
}
url.pathname = "";
url.search = "";
url.hash = "";
return url.toString();
} catch {
return undefined;
}
}
const devProxyTarget = resolveDevProxyTarget(configuredWsUrl);
const devProxyTarget = resolveDevProxyTarget(configuredDevProxyUrl ?? configuredWsUrl);
export default defineConfig(() => {
return {
@@ -145,6 +137,11 @@ export default defineConfig(() => {
host,
port,
strictPort: true,
...(configuredDevServerUrl
? {
allowedHosts: [configuredDevServerUrl.hostname],
}
: {}),
...(devProxyTarget
? {
proxy: {
@@ -164,12 +161,16 @@ export default defineConfig(() => {
}
: {}),
hmr: {
// Explicit config so Vite's HMR WebSocket connects reliably
// inside Electron's BrowserWindow. Vite 8 uses console.debug for
// connection logs — enable "Verbose" in DevTools to see them.
protocol: "ws",
host,
clientPort: port,
// Follow the browser-facing dev origin when reverse-proxied, while
// preserving the explicit loopback config used by Electron.
protocol: configuredDevServerUrl?.protocol === "https:" ? "wss" : "ws",
host: configuredDevServerUrl?.hostname ?? host,
clientPort: configuredDevServerUrl
? Number(
configuredDevServerUrl.port ||
(configuredDevServerUrl.protocol === "https:" ? "443" : "80"),
)
: port,
},
},
build: {
+3
View File
@@ -7,6 +7,9 @@
- Web dev commands do not auto-open a browser. Open the one-time pairing URL printed by the server so the first browser navigation is authenticated. Set `T3CODE_NO_BROWSER=0` only when interactive auto-open is intentional.
- Pass dev-runner flags directly after the root task name, for example:
`vp run dev --home-dir /tmp/t3code-dev`
- For a reverse-proxied remote dev origin, pass `--public-url` so browser HTTP,
WebSocket, HMR, allowed-host, and port-scoped auth-cookie settings stay aligned:
`vp run dev --public-url https://siva.example.test:7446`
- `vp run start` — Runs the production server (serves built web app as static files).
- `vp run build` — Builds contracts, web app, and server.
- `vp run typecheck` — Strict TypeScript checks for all packages.
+75
View File
@@ -61,6 +61,20 @@ const devServerInput = {
runArgs: ["--inspect", "secret-token-value"],
} as const;
const defaultCreateEnvInput = {
mode: "dev",
baseEnv: {},
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
browser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
port: undefined,
devUrl: undefined,
} as const;
it.layer(NodeServices.layer)("dev-runner", (it) => {
describe("getDevRunnerModeArgs", () => {
it.effect("lets Vite+ honor the desktop dev task graph", () =>
@@ -147,6 +161,67 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
}),
);
it.effect("configures remote dev targets and cookie isolation from one public URL", () =>
Effect.gen(function* () {
const env = yield* createDevRunnerEnv({
mode: "dev",
baseEnv: {},
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
browser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
port: undefined,
devUrl: undefined,
publicUrl: new URL("https://siva.example.test:7446"),
});
assert.equal(env.VITE_DEV_SERVER_URL, "https://siva.example.test:7446");
assert.equal(env.VITE_HTTP_URL, "https://siva.example.test:7446");
assert.equal(env.VITE_WS_URL, "wss://siva.example.test:7446");
assert.equal(env.T3CODE_DEV_PROXY_URL, "http://localhost:13773");
assert.equal(env.T3CODE_AUTH_COOKIE_PORT, "7446");
}),
);
it.effect("rejects public URLs that are not HTTP origins", () =>
Effect.gen(function* () {
const unsupportedProtocol = yield* Effect.flip(
createDevRunnerEnv({
...defaultCreateEnvInput,
publicUrl: new URL("ftp://siva.example.test:7446"),
}),
);
const pathUrl = yield* Effect.flip(
createDevRunnerEnv({
...defaultCreateEnvInput,
publicUrl: new URL("https://siva.example.test:7446/app"),
}),
);
assert.equal(unsupportedProtocol._tag, "DevRunnerPublicUrlError");
assert.equal(unsupportedProtocol.reason, "unsupported-protocol");
assert.equal(pathUrl._tag, "DevRunnerPublicUrlError");
assert.equal(pathUrl.reason, "not-an-origin");
}),
);
it.effect("rejects conflicting public and explicit dev URLs", () =>
Effect.gen(function* () {
const error = yield* Effect.flip(
createDevRunnerEnv({
...defaultCreateEnvInput,
devUrl: new URL("http://localhost:7331"),
publicUrl: new URL("https://siva.example.test:7446"),
}),
);
assert.equal(error._tag, "DevRunnerConflictingUrlOptionsError");
}),
);
it.effect("allows browser auto-open to be explicitly enabled", () =>
Effect.gen(function* () {
const env = yield* createDevRunnerEnv({
+97 -3
View File
@@ -81,6 +81,29 @@ export class DevRunnerInvalidPortOffsetError extends Schema.TaggedErrorClass<Dev
}
}
export class DevRunnerPublicUrlError extends Schema.TaggedErrorClass<DevRunnerPublicUrlError>()(
"DevRunnerPublicUrlError",
{
reason: Schema.Literals(["unsupported-protocol", "not-an-origin"]),
protocol: Schema.String,
},
) {
override get message(): string {
return this.reason === "unsupported-protocol"
? `Public URL must use HTTP or HTTPS; received protocol "${this.protocol}".`
: "Public URL must be an origin without credentials, a path, query parameters, or a fragment.";
}
}
export class DevRunnerConflictingUrlOptionsError extends Schema.TaggedErrorClass<DevRunnerConflictingUrlOptionsError>()(
"DevRunnerConflictingUrlOptionsError",
{},
) {
override get message(): string {
return "Use either --public-url or --dev-url, not both.";
}
}
export class DevRunnerPortExhaustedError extends Schema.TaggedErrorClass<DevRunnerPortExhaustedError>()(
"DevRunnerPortExhaustedError",
{
@@ -131,6 +154,8 @@ export class DevRunnerProcessExitError extends Schema.TaggedErrorClass<DevRunner
export const DevRunnerError = Schema.Union([
DevRunnerConfigurationError,
DevRunnerInvalidPortOffsetError,
DevRunnerPublicUrlError,
DevRunnerConflictingUrlOptionsError,
DevRunnerPortExhaustedError,
DevRunnerProcessError,
DevRunnerProcessExitError,
@@ -153,6 +178,11 @@ const optionalPortConfig = (name: string): Config.Config<number | undefined> =>
Config.option,
Config.map((value) => Option.getOrUndefined(value)),
);
const optionalUrlConfig = (name: string): Config.Config<URL | undefined> =>
Config.url(name).pipe(
Config.option,
Config.map((value) => Option.getOrUndefined(value)),
);
const optionalIntegerConfig = (name: string): Config.Config<number | undefined> =>
Config.int(name).pipe(
Config.option,
@@ -227,6 +257,7 @@ interface CreateDevRunnerEnvInput {
readonly host: string | undefined;
readonly port: number | undefined;
readonly devUrl: URL | undefined;
readonly publicUrl?: URL | undefined;
}
export function createDevRunnerEnv({
@@ -241,18 +272,68 @@ export function createDevRunnerEnv({
host,
port,
devUrl,
}: CreateDevRunnerEnvInput): Effect.Effect<NodeJS.ProcessEnv, never, Path.Path> {
publicUrl,
}: CreateDevRunnerEnvInput): Effect.Effect<
NodeJS.ProcessEnv,
DevRunnerPublicUrlError | DevRunnerConflictingUrlOptionsError,
Path.Path
> {
return Effect.gen(function* () {
const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
const webPort = BASE_WEB_PORT + webOffset;
const configuredBaseDir = t3Home?.trim() || baseEnv.T3CODE_HOME?.trim() || undefined;
const resolvedBaseDir = yield* resolveBaseDir(configuredBaseDir);
const isDesktopMode = mode === "dev:desktop";
const configuredPublicUrl = isDesktopMode ? undefined : publicUrl;
if (configuredPublicUrl !== undefined && devUrl !== undefined) {
return yield* new DevRunnerConflictingUrlOptionsError();
}
if (
configuredPublicUrl !== undefined &&
configuredPublicUrl.protocol !== "http:" &&
configuredPublicUrl.protocol !== "https:"
) {
return yield* new DevRunnerPublicUrlError({
reason: "unsupported-protocol",
protocol: configuredPublicUrl.protocol,
});
}
if (
configuredPublicUrl !== undefined &&
(configuredPublicUrl.username !== "" ||
configuredPublicUrl.password !== "" ||
configuredPublicUrl.pathname !== "/" ||
configuredPublicUrl.search !== "" ||
configuredPublicUrl.hash !== "")
) {
return yield* new DevRunnerPublicUrlError({
reason: "not-an-origin",
protocol: configuredPublicUrl.protocol,
});
}
const publicHttpUrl = configuredPublicUrl?.origin;
const publicWsUrl =
configuredPublicUrl === undefined
? undefined
: (() => {
const url = new URL(configuredPublicUrl);
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
return url.origin;
})();
const publicPort =
configuredPublicUrl === undefined
? undefined
: Number(
configuredPublicUrl.port || (configuredPublicUrl.protocol === "https:" ? "443" : "80"),
);
const output: NodeJS.ProcessEnv = {
...baseEnv,
PORT: String(webPort),
VITE_DEV_SERVER_URL:
publicHttpUrl ??
devUrl?.toString() ??
`http://${isDesktopMode ? DESKTOP_DEV_LOOPBACK_HOST : "localhost"}:${webPort}`,
};
@@ -265,8 +346,12 @@ export function createDevRunnerEnv({
if (!isDesktopMode) {
output.T3CODE_PORT = String(serverPort);
output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
output.VITE_WS_URL = `ws://localhost:${serverPort}`;
output.T3CODE_DEV_PROXY_URL = `http://localhost:${serverPort}`;
output.VITE_HTTP_URL = publicHttpUrl ?? `http://localhost:${serverPort}`;
output.VITE_WS_URL = publicWsUrl ?? `ws://localhost:${serverPort}`;
if (publicPort !== undefined) {
output.T3CODE_AUTH_COOKIE_PORT = String(publicPort);
}
} else {
output.T3CODE_PORT = String(serverPort);
output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
@@ -479,6 +564,7 @@ interface DevRunnerCliInput {
readonly host: string | undefined;
readonly port: number | undefined;
readonly devUrl: URL | undefined;
readonly publicUrl?: URL | undefined;
readonly dryRun: boolean;
readonly runArgs: ReadonlyArray<string>;
}
@@ -517,6 +603,7 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
host: input.host,
port: input.port,
devUrl: input.devUrl,
publicUrl: input.publicUrl,
});
const selectionSuffix =
@@ -627,6 +714,13 @@ const devRunnerCli = Command.make("dev-runner", {
Flag.optional,
Flag.map(Option.getOrUndefined),
),
publicUrl: Flag.string("public-url").pipe(
Flag.withSchema(Schema.URLFromString),
Flag.withDescription(
"Browser-facing HTTP(S) origin for remote dev access; also namespaces auth cookies by its public port.",
),
Flag.withFallbackConfig(optionalUrlConfig("T3CODE_PUBLIC_URL")),
),
dryRun: Flag.boolean("dry-run").pipe(
Flag.withDescription("Resolve mode/ports/env and print, but do not spawn Vite+."),
Flag.withDefault(false),