Fix dev sharing across hosted and restarted servers

This commit is contained in:
Theo Browne committed 2026-07-26 20:39:53 -07:00
1 parent b769bb6455
commit c698e6aa5b
8 files changed
+185 -62

No files matched your search

+2 -4
View File
@@ -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<
@@ -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();
@@ -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({
-1
View File
@@ -468,7 +468,6 @@ export const make = Effect.gen(function* () {
const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
const cookieName = resolveSessionCookieName({
mode: serverConfig.mode,
port: serverConfig.port,
devUrl: serverConfig.devUrl,
});
+5 -17
View File
@@ -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 {
+20 -12
View File
@@ -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}${
+63 -2
View File
@@ -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<void>;
readonly calls?: Array<ReadonlyArray<string>>;
}) =>
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const args = "args" in command ? (command.args as ReadonlyArray<string>) : [];
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<ReadonlyArray<string>> = [];
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<ReadonlyArray<string>> = [];
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);
}),
);
});
+92
View File
@@ -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<DevServeFailedE
}
}
export class DevShareLeaseClaimError extends Schema.TaggedErrorClass<DevShareLeaseClaimError>()(
"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.