From c698e6aa5b66b69bd59140d45abe84a571a58df0 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 26 Jul 2026 15:38:56 -0700 Subject: [PATCH] Fix dev sharing across hosted and restarted servers --- apps/server/src/auth/EnvironmentAuth.test.ts | 6 +- .../src/auth/EnvironmentAuthPolicy.test.ts | 23 +---- apps/server/src/auth/EnvironmentAuthPolicy.ts | 6 +- apps/server/src/auth/SessionStore.ts | 1 - apps/server/src/auth/utils.ts | 22 +---- scripts/dev-runner.ts | 32 ++++--- scripts/lib/dev-share.test.ts | 65 ++++++++++++- scripts/lib/dev-share.ts | 92 +++++++++++++++++++ 8 files changed, 185 insertions(+), 62 deletions(-) diff --git a/apps/server/src/auth/EnvironmentAuth.test.ts b/apps/server/src/auth/EnvironmentAuth.test.ts index 8432f49695..9eaac9eda1 100644 --- a/apps/server/src/auth/EnvironmentAuth.test.ts +++ b/apps/server/src/auth/EnvironmentAuth.test.ts @@ -46,10 +46,8 @@ const makeCookieRequest = ( ({ cookies: { // Derived, not hardcoded: the name is port-scoped so concurrent servers - // on one hostname don't share a cookie. Mode and devUrl mirror - // ServerConfig.layerTest, so this resolves to whatever the server reads. - [resolveSessionCookieName({ mode: "web", port: TEST_SERVER_PORT, devUrl: undefined })]: - sessionToken, + // on one hostname don't share a cookie. + [resolveSessionCookieName({ port: TEST_SERVER_PORT, devUrl: undefined })]: sessionToken, }, headers: {}, }) as unknown as Parameters< diff --git a/apps/server/src/auth/EnvironmentAuthPolicy.test.ts b/apps/server/src/auth/EnvironmentAuthPolicy.test.ts index 0e21ef19c9..9f19f5d5f7 100644 --- a/apps/server/src/auth/EnvironmentAuthPolicy.test.ts +++ b/apps/server/src/auth/EnvironmentAuthPolicy.test.ts @@ -34,10 +34,7 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => { expect(descriptor.policy).toBe("desktop-managed-local"); expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]); - // Packaged desktop has no devUrl, but still needs the port scope: it - // scans upward from 3773 for a free port and binds 127.0.0.1, so a second - // instance shares this one's hostname on a different port. - expect(descriptor.sessionCookieName).toBe("t3_session_3773"); + expect(descriptor.sessionCookieName).toBe("t3_session"); }).pipe( Effect.provide( makeEnvironmentAuthPolicyLayer({ @@ -48,22 +45,6 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => { ), ); - it.effect("keeps desktop cookies port-scoped on the port a second instance lands on", () => - Effect.gen(function* () { - const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy; - const descriptor = yield* policy.getDescriptor(); - - expect(descriptor.sessionCookieName).toBe("t3_session_3774"); - }).pipe( - Effect.provide( - makeEnvironmentAuthPolicyLayer({ - mode: "desktop", - port: 3774, - }), - ), - ), - ); - it.effect("uses remote-reachable policy for desktop mode when bound beyond loopback", () => Effect.gen(function* () { const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy; @@ -100,7 +81,7 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => { ), ); - it.effect("scopes web session cookies by port only in development", () => + it.effect("scopes session cookies by port only in development", () => Effect.gen(function* () { const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy; const descriptor = yield* policy.getDescriptor(); diff --git a/apps/server/src/auth/EnvironmentAuthPolicy.ts b/apps/server/src/auth/EnvironmentAuthPolicy.ts index 28e4157676..d43db0d0ba 100644 --- a/apps/server/src/auth/EnvironmentAuthPolicy.ts +++ b/apps/server/src/auth/EnvironmentAuthPolicy.ts @@ -38,11 +38,7 @@ export const make = Effect.gen(function* () { policy, bootstrapMethods, sessionMethods: ["browser-session-cookie", "bearer-access-token", "dpop-access-token"], - sessionCookieName: resolveSessionCookieName({ - mode: config.mode, - port: config.port, - devUrl: config.devUrl, - }), + sessionCookieName: resolveSessionCookieName({ port: config.port, devUrl: config.devUrl }), }; return EnvironmentAuthPolicy.of({ diff --git a/apps/server/src/auth/SessionStore.ts b/apps/server/src/auth/SessionStore.ts index efa811302d..b8d3be6348 100644 --- a/apps/server/src/auth/SessionStore.ts +++ b/apps/server/src/auth/SessionStore.ts @@ -468,7 +468,6 @@ export const make = Effect.gen(function* () { const connectedSessionsRef = yield* Ref.make(new Map()); const changesPubSub = yield* PubSub.unbounded(); const cookieName = resolveSessionCookieName({ - mode: serverConfig.mode, port: serverConfig.port, devUrl: serverConfig.devUrl, }); diff --git a/apps/server/src/auth/utils.ts b/apps/server/src/auth/utils.ts index 81ef9bffc4..060f1d29f0 100644 --- a/apps/server/src/auth/utils.ts +++ b/apps/server/src/auth/utils.ts @@ -11,28 +11,16 @@ import * as Result from "effect/Result"; const SESSION_COOKIE_NAME = "t3_session"; /** - * Cookies are scoped by host but *not* by port, so any two servers that can be - * live on one hostname at once need separate names — otherwise the second - * clobbers the first's session and both sides see "Invalid session token - * signature" until someone clears cookies by hand. - * - * Two populations qualify, for the same reason but from different causes: - * - * - **Dev servers** (`devUrl` set), which run several at a time across worktrees. - * - **Desktop**, which scans upward from 3773 for a free port and binds - * 127.0.0.1, so a second instance lands on a different port and the same host. - * - * Hosted deployments keep the stable production name: their public port can - * change between releases, and scoping it would log every user out. + * Cookies are scoped by host but *not* by port, so concurrent dev servers on a + * hostname need separate names. Hosted deployments keep the stable production + * name: their public port can change between releases, and scoping it would log + * every user out. */ export function resolveSessionCookieName(input: { - readonly mode: "web" | "desktop"; readonly port: number; readonly devUrl: URL | undefined; }): string { - return input.devUrl === undefined && input.mode !== "desktop" - ? SESSION_COOKIE_NAME - : `${SESSION_COOKIE_NAME}_${input.port}`; + return input.devUrl === undefined ? SESSION_COOKIE_NAME : `${SESSION_COOKIE_NAME}_${input.port}`; } export function base64UrlEncode(input: string | Uint8Array): string { diff --git a/scripts/dev-runner.ts b/scripts/dev-runner.ts index cb4e3f74c4..d89041f93d 100644 --- a/scripts/dev-runner.ts +++ b/scripts/dev-runner.ts @@ -1,6 +1,7 @@ #!/usr/bin/env node import * as NodeOS from "node:os"; +import * as NodeCrypto from "node:crypto"; import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -19,7 +20,12 @@ import * as Schema from "effect/Schema"; import { Argument, Command, Flag } from "effect/unstable/cli"; import { ChildProcess } from "effect/unstable/process"; -import { type DevShareError, shareDevServer, unshareDevServer } from "./lib/dev-share.ts"; +import { + claimDevShareLease, + cleanupOwnedDevShare, + type DevShareError, + shareDevServer, +} from "./lib/dev-share.ts"; import { loadRepoEnv } from "./lib/public-config.ts"; Object.assign(process.env, loadRepoEnv()); @@ -723,6 +729,7 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) { "[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.", ); } else { + const path = yield* Path.Path; // acquireRelease, not share-then-addFinalizer: the mapping outlives this // process (and reboots), so the cleanup has to be registered atomically // with creating it. An interrupt landing in between would otherwise @@ -736,23 +743,24 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) { // // A tailnet that isn't up shouldn't stop the dev server from starting — // warn, and carry on serving locally. - const shared = yield* Effect.acquireRelease( - shareDevServer({ webPort: sharedWebPort }), - () => - // Serve config outlives this process, so a cleanup that did not - // take leaves a tailnet URL pointing at a port nothing serves. - unshareDevServer(sharedWebPort).pipe( + const shared = yield* Effect.gen(function* () { + const lease = yield* claimDevShareLease({ + leasePath: path.join(baseDir, "dev-share", `${String(sharedWebPort)}.owner`), + ownerId: `${String(process.pid)}:${NodeCrypto.randomUUID()}`, + webPort: sharedWebPort, + }); + return yield* Effect.acquireRelease(shareDevServer({ webPort: sharedWebPort }), () => + cleanupOwnedDevShare(lease).pipe( Effect.flatMap((result) => - result.cleared + result.status !== "failed" ? Effect.void : Effect.logWarning( - `[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${ - result.explanation ? `: ${result.explanation}` : "" - }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} off\`.`, + `[dev-runner] could not safely clean up the tailnet mapping for port ${String(sharedWebPort)}: ${result.explanation}`, ), ), ), - ).pipe( + ); + }).pipe( Effect.tapError((error: DevShareError) => Effect.logWarning( `[dev-runner] could not share on the tailnet: ${error.message}${ diff --git a/scripts/lib/dev-share.test.ts b/scripts/lib/dev-share.test.ts index b2dfba3585..a40a38d951 100644 --- a/scripts/lib/dev-share.test.ts +++ b/scripts/lib/dev-share.test.ts @@ -1,11 +1,15 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; import { ChildProcessSpawner } from "effect/unstable/process"; import { + claimDevShareLease, + cleanupOwnedDevShare, type DevShareError, DevServeFailedError, shareDevServer, @@ -27,11 +31,17 @@ const encode = (value: string) => Stream.make(new TextEncoder().encode(value)); * test set the outcome of the `off` (pre-clear) and `serve` calls separately — * they are the same subcommand and are told apart by the trailing `off`. */ -const spawnerLayer = (input: { readonly off?: CallResult; readonly serve?: CallResult }) => +const spawnerLayer = (input: { + readonly off?: CallResult; + readonly serve?: CallResult; + readonly onOff?: Effect.Effect; + readonly calls?: Array>; +}) => Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, ChildProcessSpawner.make((command) => { const args = "args" in command ? (command.args as ReadonlyArray) : []; + input.calls?.push(args); const result: CallResult = args.includes("status") ? { exitCode: 0 } : args.includes("off") @@ -41,7 +51,9 @@ const spawnerLayer = (input: { readonly off?: CallResult; readonly serve?: CallR return Effect.succeed( ChildProcessSpawner.makeHandle({ pid: ChildProcessSpawner.ProcessId(1), - exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.exitCode)), + exitCode: (args.includes("off") ? (input.onOff ?? Effect.void) : Effect.void).pipe( + Effect.as(ChildProcessSpawner.ExitCode(result.exitCode)), + ), isRunning: Effect.succeed(false), kill: () => Effect.void, unref: Effect.succeed(Effect.void), @@ -176,3 +188,52 @@ describe("shareDevServer", () => { }), ); }); + +it.layer(NodeServices.layer)("dev share cleanup ownership", (it) => { + it.effect("restores a newer runner's mapping when ownership changes during cleanup", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const directory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-dev-share-lease-", + }); + const leasePath = `${directory}/5788.owner`; + const oldLease = { leasePath, ownerId: "old-runner", webPort: 5788 }; + const calls: Array> = []; + + yield* claimDevShareLease(oldLease); + const result = yield* cleanupOwnedDevShare(oldLease).pipe( + Effect.provide( + spawnerLayer({ + calls, + onOff: fileSystem.writeFileString(leasePath, "new-runner").pipe(Effect.orDie), + }), + ), + ); + + assert.equal(result.status, "restored"); + assert.isTrue(calls.some((args) => args.includes("off"))); + assert.isTrue(calls.some((args) => args.includes("http://127.0.0.1:5788"))); + }), + ); + + it.effect("leaves the mapping alone when a newer runner already owns it", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const directory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-dev-share-lease-", + }); + const leasePath = `${directory}/5788.owner`; + const oldLease = { leasePath, ownerId: "old-runner", webPort: 5788 }; + const calls: Array> = []; + + yield* claimDevShareLease(oldLease); + yield* claimDevShareLease({ ...oldLease, ownerId: "new-runner" }); + const result = yield* cleanupOwnedDevShare(oldLease).pipe( + Effect.provide(spawnerLayer({ calls })), + ); + + assert.equal(result.status, "superseded"); + assert.isEmpty(calls); + }), + ); +}); diff --git a/scripts/lib/dev-share.ts b/scripts/lib/dev-share.ts index 0f843b3ba9..d6c87abd8c 100644 --- a/scripts/lib/dev-share.ts +++ b/scripts/lib/dev-share.ts @@ -22,6 +22,9 @@ import { type TailscaleStderrDiagnostic, } from "@t3tools/tailscale"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import type { ChildProcessSpawner } from "effect/unstable/process"; @@ -110,10 +113,24 @@ export class DevServeFailedError extends Schema.TaggedErrorClass()( + "DevShareLeaseClaimError", + { leasePath: Schema.String, cause: Schema.Defect() }, +) { + override get message(): string { + return `could not claim cleanup ownership at ${this.leasePath}`; + } + + get hint(): string { + return "Check that the dev data directory is writable."; + } +} + export const DevShareError = Schema.Union([ TailscaleUnavailableError, TailnetNameMissingError, DevServeFailedError, + DevShareLeaseClaimError, ]); export type DevShareError = typeof DevShareError.Type; export const isDevShareError = Schema.is(DevShareError); @@ -163,6 +180,81 @@ export interface DevShareResult { readonly host: string; } +export interface DevShareLease { + readonly leasePath: string; + readonly ownerId: string; + readonly webPort: number; +} + +export const claimDevShareLease = Effect.fn("devShare.claimDevShareLease")(function* ( + lease: DevShareLease, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* fileSystem.makeDirectory(path.dirname(lease.leasePath), { recursive: true }).pipe( + Effect.andThen(fileSystem.writeFileString(lease.leasePath, lease.ownerId)), + Effect.mapError((cause) => new DevShareLeaseClaimError({ leasePath: lease.leasePath, cause })), + ); + return lease; +}); + +export type DevShareCleanupResult = + | { readonly status: "cleared" | "superseded" | "restored" } + | { readonly status: "failed"; readonly explanation: string }; + +/** + * Clears only the mapping this runner owns. If a successor claims the lease + * while `tailscale serve off` is in flight, restore the same port mapping so + * the old finalizer cannot silently disconnect the new runner. + */ +export const cleanupOwnedDevShare = Effect.fn("devShare.cleanupOwnedDevShare")(function* ( + lease: DevShareLease, +): Effect.fn.Return< + DevShareCleanupResult, + never, + FileSystem.FileSystem | ChildProcessSpawner.ChildProcessSpawner +> { + const fileSystem = yield* FileSystem.FileSystem; + const readOwner = fileSystem + .readFileString(lease.leasePath) + .pipe(Effect.option, Effect.map(Option.getOrUndefined)); + const ownerBefore = yield* readOwner; + if (ownerBefore !== lease.ownerId) { + return { status: "superseded" }; + } + + const result = yield* unshareDevServer(lease.webPort); + if (!result.cleared) { + return { + status: "failed", + explanation: + result.explanation ?? + `could not remove the tailnet mapping for port ${String(lease.webPort)}`, + }; + } + + const ownerAfter = yield* readOwner; + if (ownerAfter === lease.ownerId) { + return { status: "cleared" }; + } + + return yield* ensureTailscaleServe({ + localPort: lease.webPort, + servePort: lease.webPort, + }).pipe( + Effect.as({ status: "restored" } as const), + Effect.catch((cause: TailscaleCommandError) => + Effect.succeed({ + status: "failed", + explanation: + explainCommandFailure(cause) ?? + `a newer runner claimed port ${String(lease.webPort)}, but its mapping could not be restored`, + } as const), + ), + Effect.uninterruptible, + ); +}); + /** * Publishes `webPort` on the tailnet at the same port number and returns the * resulting HTTPS URL. Idempotent: re-running replaces any existing mapping.