feat(dev): Make t3 code dev instances shareable over Tailscale #4556
Mergedt3dotgg(GitHub profile, opens in a new tab)merged 24 commits into
main fromrefs/pull/4556/headmerged by t3dotgg(GitHub profile, opens in a new tab) View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
- packages/tailscale/src/tailscale.ts line 291OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -275,3 +288,4 @@275288 ...commandContext,276289 exitCode,277290 stderrLength: stderr.length,291+ ...(stderrPreviewOf(stderr) !== undefined@@ -28,4 +30,9 @@2830 const MAX_HASH_OFFSET = 3000;2931 const MAX_PORT = 65535;3032 const DESKTOP_DEV_LOOPBACK_HOST = "127.0.0.1";31-const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::1", "::"] as const;33+// Dev servers bind loopback, so loopback is the only interface whose34+// availability decides whether we can use a port. Probing wildcards too made35+// the runner walk away from a perfectly free port whenever something else held36+// the same number on another interface — `tailscale serve` does exactly that,37+// which silently moved the ports out from under a URL that had just been shared.38+const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "::1"] as const;
- @@ -544,0 +624,21 @@624+ );625+626+ if (shared) {627+ // The app is reached from the tailnet origin. Vite already allows628+ // *.ts.net hosts; the backend needs the origin for credentialed629+ // requests that bypass the proxy (desktop renderer, direct calls).630+ env.T3CODE_DEV_ALLOWED_ORIGINS = [631+ env.T3CODE_DEV_ALLOWED_ORIGINS,632+ new URL(shared.url).origin,633+ ]634+ .filter((entry) => entry && entry.length > 0)635+ .join(",");636+ // The server builds its pairing URL from this, so the URL printed at637+ // startup is already the shareable one — no rewriting by hand. An638+ // explicit --dev-url still wins.639+ if (input.devUrl === undefined) {640+ env.VITE_DEV_SERVER_URL = shared.url;641+ }642+ yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`);643+ }644+ }
- @@ -7,10 +7,13 @@77 import { defineConfig } from "vite-plus";88 import pkg from "./package.json" with { type: "json" };9910+import { DEV_PROXIED_PATH_PREFIXES } from "@t3tools/shared/devProxy";11+1012 import { loadRepoEnv } from "../../scripts/lib/public-config";11131214 const repoEnv = loadRepoEnv();1315 Object.assign(process.env, repoEnv);14161517 const port = Number(process.env.PORT ?? 5733);16-const host = process.env.HOST?.trim() || "localhost";18+const explicitHost = process.env.HOST?.trim();19+const host = explicitHost || "localhost";@@ -549,0 +637,21 @@637+ Effect.map(Option.getOrUndefined),638+ );639+640+ if (shared) {641+ // The app is reached from the tailnet origin. Vite already allows642+ // *.ts.net hosts; the backend needs the origin for credentialed643+ // requests that bypass the proxy (desktop renderer, direct calls).644+ env.T3CODE_DEV_ALLOWED_ORIGINS = [645+ env.T3CODE_DEV_ALLOWED_ORIGINS,646+ new URL(shared.url).origin,647+ ]648+ .filter((entry) => entry && entry.length > 0)649+ .join(",");650+ // The server builds its pairing URL from this, so the URL printed at651+ // startup is already the shareable one — no rewriting by hand. An652+ // explicit --dev-url still wins.653+ if (input.devUrl === undefined) {654+ env.VITE_DEV_SERVER_URL = shared.url;655+ }656+ yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`);657+ }
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- @@ -498,10 +552,19 @@498552 ),499553 );500554501- const { offset, source } = yield* resolveOffset({ portOffset, devInstance });555+ const worktreePath = yield* resolveGitWorktreePath(yield* HostProcessWorkingDirectory);556+557+ const { offset, source } = yield* resolveOffset({558+ portOffset,559+ devInstance,560+ worktreePath,561+ });502562503563 const { serverOffset, webOffset } = yield* resolveModePortOffsets({504564 mode: input.mode,505565 startOffset: offset,506566 hasExplicitServerPort: input.port !== undefined,507567 hasExplicitDevUrl: input.devUrl !== undefined,568+ // A non-loopback bind host decides whether the backend can actually take569+ // the port, so it has to be probed alongside loopback.570+ checkPortAvailability: makeDefaultCheckPortAvailability(input.host),
- apps/server/src/auth/EnvironmentAuth.test.ts lines 18 to 25Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -8,14 +8,19 @@88 import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";99 import * as PairingGrantStore from "./PairingGrantStore.ts";1010 import * as EnvironmentAuth from "./EnvironmentAuth.ts";11+import { resolveSessionCookieName } from "./utils.ts";11121213 import * as ServerSecretStore from "./ServerSecretStore.ts";131415+/** Pinned so the session cookie name (which is port-scoped) is predictable. */16+const TEST_SERVER_PORT = 13_773;17+1418 const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Service"]>) =>1519 Layer.effect(1620 ServerConfig.ServerConfig,1721 Effect.gen(function* () {1822 const config = yield* ServerConfig.ServerConfig;1923 return {2024 ...config,25+ port: TEST_SERVER_PORT,2126 ...overrides,docs/reference/scripts.md line 4OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1,3 +1,4 @@11 # Scripts2233 `vp run dev` — Starts contracts, server, and web in watch mode.4+`vp run dev --share` (or `vp run dev:share`) — Also publishes the web port over HTTPS on this machine's tailnet. The startup pairing URL is built against the shared origin, and the mapping is removed on exit.packages/tailscale/src/tailscale.test.ts lines 29 to 40OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -25,3 +25,16 @@2525 } from "./tailscale.ts";26262727 const encoder = new TextEncoder();28+29+/**30+ * Asserts no field of `error` (nor its message) contains `secret`. Walks the31+ * own enumerable values rather than serializing, so it holds for any field32+ * added later without the test needing to know the shape.33+ */34+function assertCarriesNoSecret(error: object, secret: string): void {35+ assert.notInclude(String((error as { message?: unknown }).message ?? ""), secret);36+ for (const [key, value] of Object.entries(error)) {37+ if (typeof value === "string") {38+ assert.notInclude(value, secret, `field "${key}" leaked stderr`);39+ }40+ }
t3dotgg(GitHub profile, opens in a new tab) changed the title
- scripts/dev-runner.ts line 720OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -535,0 +641,21 @@641+ if (input.mode === "dev:server") {642+ yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server).");643+ } else if (input.mode === "dev:desktop") {644+ // Desktop is not single-origin: the renderer gets VITE_HTTP_URL and645+ // VITE_WS_URL baked to loopback, so a tailnet visitor would load the UI646+ // and then watch it dial its own 127.0.0.1 for the backend. Worse,647+ // sharing would overwrite VITE_DEV_SERVER_URL, which is the origin648+ // Electron itself loads the renderer from. Refuse rather than hand out649+ // a URL that is broken in a way the user cannot see.650+ yield* Effect.logWarning(651+ "[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.",652+ );653+ } else {654+ // acquireRelease, not share-then-addFinalizer: the mapping outlives this655+ // process (and reboots), so the cleanup has to be registered atomically656+ // with creating it. An interrupt landing in between would otherwise657+ // leave a mapping pointing at a port nothing is listening on.658+ //659+ // A tailnet that isn't up shouldn't stop the dev server from starting —660+ // warn, and carry on serving locally.661+ const shared = yield* Effect.acquireRelease(
- scripts/dev-runner.ts line 668OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -549,0 +648,21 @@648+ yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server).");649+ } else if (input.mode === "dev:desktop") {650+ // Desktop is not single-origin: the renderer gets VITE_HTTP_URL and651+ // VITE_WS_URL baked to loopback, so a tailnet visitor would load the UI652+ // and then watch it dial its own 127.0.0.1 for the backend. Worse,653+ // sharing would overwrite VITE_DEV_SERVER_URL, which is the origin654+ // Electron itself loads the renderer from. Refuse rather than hand out655+ // a URL that is broken in a way the user cannot see.656+ yield* Effect.logWarning(657+ "[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.",658+ );659+ } else {660+ const path = yield* Path.Path;661+ // acquireRelease, not share-then-addFinalizer: the mapping outlives this662+ // process (and reboots), so the cleanup has to be registered atomically663+ // with creating it. An interrupt landing in between would otherwise664+ // leave a mapping pointing at a port nothing is listening on.665+ //666+ // A tailnet that isn't up shouldn't stop the dev server from starting —667+ // warn, and carry on serving locally.668+ const shared = yield* Effect.gen(function* () {
- @@ -0,0 +302,21 @@302+ return {303+ url: buildTailscaleHttpsBaseUrl({304+ magicDnsName: status.magicDnsName,305+ servePort: input.webPort,306+ }),307+ host: status.magicDnsName,308+ } satisfies DevShareResult;309+});310+311+/**312+ * Claims cleanup ownership only after the tailnet mapping exists. A failed313+ * replacement must leave the prior runner as the owner so its finalizer can314+ * still remove any mapping that survived the attempt.315+ */316+export const acquireDevShare = Effect.fn("devShare.acquireDevShare")(function* (317+ lease: DevShareLease,318+) {319+ const shared = yield* shareDevServer({ webPort: lease.webPort });320+ yield* claimDevShareLease(lease);321+ return shared;322+});
- @@ -0,0 +303,21 @@303+ url: buildTailscaleHttpsBaseUrl({304+ magicDnsName: status.magicDnsName,305+ servePort: input.webPort,306+ }),307+ host: status.magicDnsName,308+ } satisfies DevShareResult;309+});310+311+/**312+ * Claims cleanup ownership before publishing, then cleans up immediately if313+ * publishing fails. This keeps the handoff atomic from the runners' point of314+ * view: the prior runner can stop cleaning as soon as the successor claims,315+ * because that successor owns both the attempted mapping and its rollback.316+ */317+export const acquireDevShare = Effect.fn("devShare.acquireDevShare")(function* (318+ lease: DevShareLease,319+) {320+ yield* claimDevShareLease(lease);321+ return yield* shareDevServer({ webPort: lease.webPort }).pipe(322+ Effect.tapError(() => cleanupOwnedDevShare(lease)),323+ );
- scripts/lib/dev-share.ts lines 333 to 339OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +319,21 @@319+ * resulting HTTPS URL. Idempotent: re-running replaces any existing mapping.320+ */321+export const shareDevServer = Effect.fn("devShare.shareDevServer")(function* (input: {322+ readonly webPort: number;323+}) {324+ const host = yield* prepareDevShare(input);325+ return yield* publishDevShare({ ...input, host });326+});327+328+/**329+ * Transfers cleanup ownership after the old mapping is known to be gone and330+ * before the new mapping is published. Failures on either side of that331+ * boundary therefore cannot leave a surviving mapping without an owner.332+ */333+export const acquireDevShare = Effect.fn("devShare.acquireDevShare")(function* (334+ lease: DevShareLease,335+) {336+ const host = yield* prepareDevShare({ webPort: lease.webPort });337+ yield* claimDevShareLease(lease);338+ return yield* publishDevShare({ host, webPort: lease.webPort });339+});
- @@ -0,0 +318,21 @@318+ * Publishes `webPort` on the tailnet at the same port number and returns the319+ * resulting HTTPS URL. Idempotent: re-running replaces any existing mapping.320+ */321+export const shareDevServer = Effect.fn("devShare.shareDevServer")(function* (input: {322+ readonly webPort: number;323+}) {324+ const host = yield* prepareDevShare(input);325+ return yield* publishDevShare({ ...input, host });326+});327+328+/**329+ * Transfers cleanup ownership after the old mapping is known to be gone and330+ * before the new mapping is published. Failures on either side of that331+ * boundary therefore cannot leave a surviving mapping without an owner.332+ */333+export const acquireDevShare = Effect.fn("devShare.acquireDevShare")(function* (334+ lease: DevShareLease,335+) {336+ const host = yield* prepareDevShare({ webPort: lease.webPort });337+ yield* claimDevShareLease(lease);338+ return yield* publishDevShare({ host, webPort: lease.webPort });
- @@ -268,5 +295,4 @@268295269296 if (!isDesktopMode) {270297 output.T3CODE_PORT = String(serverPort);271- output.VITE_HTTP_URL = `http://localhost:${serverPort}`;272- output.VITE_WS_URL = `ws://localhost:${serverPort}`;298+ if (mode === "dev" || mode === "dev:web") {scripts/lib/dev-share.ts line 226OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +206,21 @@206+ return lease;207+});208+209+export type DevShareCleanupResult =210+ | { readonly status: "cleared" | "superseded" | "restored" }211+ | { readonly status: "failed"; readonly explanation: string };212+213+/**214+ * Clears only the mapping this runner owns. If a successor claims the lease215+ * while `tailscale serve off` is in flight, restore the same port mapping so216+ * the old finalizer cannot silently disconnect the new runner.217+ */218+export const cleanupOwnedDevShare = Effect.fn("devShare.cleanupOwnedDevShare")(function* (219+ lease: DevShareLease,220+): Effect.fn.Return<221+ DevShareCleanupResult,222+ never,223+ FileSystem.FileSystem | ChildProcessSpawner.ChildProcessSpawner224+> {225+ const fileSystem = yield* FileSystem.FileSystem;226+ const readOwner = fileSystem
- @@ -268,5 +295,10 @@268295269296 if (!isDesktopMode) {270297 output.T3CODE_PORT = String(serverPort);271- output.VITE_HTTP_URL = `http://localhost:${serverPort}`;272- output.VITE_WS_URL = `ws://localhost:${serverPort}`;298+ // HOST is Vite's own bind address, and the desktop branch below is the299+ // only place we set it. An inherited one (an exported HOST, a container,300+ // a `HOST=0.0.0.0 npm start` habit) would otherwise reach Vite and pin301+ // its HMR socket to that address — see the `explicitHost` gate in302+ // apps/web/vite.config.ts. Over a shared origin that is invisible: the303+ // page loads and only HMR quietly dials the wrong machine.304+ delete output.HOST;
- scripts/dev-runner.ts line 438OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -353,0 +418,21 @@418+ * a port free on loopback but busy on that interface would otherwise be419+ * rejected for a server that was never going to bind there.420+ */421+export function devPortProbeHosts(configuredHost: string | undefined): ReadonlyArray<string> {422+ const host = configuredHost?.trim();423+ if (!host || DEV_PORT_PROBE_HOSTS.includes(host as (typeof DEV_PORT_PROBE_HOSTS)[number])) {424+ return DEV_PORT_PROBE_HOSTS;425+ }426+ return [...DEV_PORT_PROBE_HOSTS, host];427+}428+429+/**430+ * The exact command that stops this runner and everything it spawned, printed431+ * at startup. Exists because the alternative — guessing a `pkill` pattern —432+ * has twice killed the agent running the session (its argv contains the433+ * worktree path) and can reach other worktrees' dev servers.434+ *435+ * Targets the process group: children are spawned with `detached: false`, so436+ * the whole stack (including the `node --watch` server processes, which keep437+ * the group after re-parenting to init) shares it. The pgid is resolved via438+ * `ps` rather than assumed equal to our PID — under `bun run dev` the group
- scripts/dev-runner.ts line 445Outdated@@ -353,0 +425,21 @@425+ }426+ return [...DEV_PORT_PROBE_HOSTS, host];427+}428+429+/**430+ * The exact command that stops this runner and everything it spawned, printed431+ * at startup. Exists because the alternative — guessing a `pkill` pattern —432+ * has twice killed the agent running the session (its argv contains the433+ * worktree path) and can reach other worktrees' dev servers.434+ *435+ * Targets the process group: children are spawned with `detached: false`, so436+ * the whole stack (including the `node --watch` server processes, which keep437+ * the group after re-parenting to init) shares it. The pgid is resolved via438+ * `ps` rather than assumed equal to our PID — under `bun run dev` the group439+ * leader is bun, not this runner, and `kill -- -<runnerPid>` would name a440+ * group that does not exist.441+ */442+export function resolveStopCommand(pid: number, platform: NodeJS.Platform): string {443+ return platform === "win32"444+ ? `taskkill /pid ${String(pid)} /T`445+ : `kill -TERM -"$(ps -o pgid= -p ${String(pid)} | tr -d ' ')"`;
t3dotgg(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.


🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
✨ Finishing Touches
📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share