fix(server): isolate remote web session cookies (#8085)

Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
Bilal BakrandJulius Marminge authored and GitHub committed 2026-08-31 20:07:42 -07:00
1 parent 9ecfc07a8b
commit c78ae50a5a
18 files changed
+484 -87

No files matched your search

@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import * as PairingGrantStore from "./PairingGrantStore.ts";
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
@@ -34,6 +35,7 @@ const makeEnvironmentAuthLayer = (overrides?: Partial<ServerConfig.ServerConfig[
EnvironmentAuth.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
Layer.provide(ServerSecretStore.layer),
Layer.provide(ServerEnvironment.identityLayer),
Layer.provide(makeServerConfigLayer(overrides)),
);
@@ -109,6 +111,20 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
}).pipe(Effect.provide(makeEnvironmentAuthLayer())),
);
it.effect("prefers a bearer token over a stale legacy cookie", () =>
Effect.gen(function* () {
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const sessions = yield* SessionStore.SessionStore;
const bearer = yield* serverAuth.issueSession();
const verified = yield* serverAuth.authenticateHttpRequest({
cookies: { [sessions.legacyCookieName ?? "t3_session"]: "stale" },
headers: { authorization: `Bearer ${bearer.token}` },
} as never);
expect(verified.sessionId).toBe(bearer.sessionId);
}).pipe(Effect.provide(makeEnvironmentAuthLayer({ mode: "web", host: "192.168.1.50" }))),
);
it.effect("does not exchange ordinary pairing grants for administrative access tokens", () =>
Effect.gen(function* () {
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
+42 -8
View File
@@ -30,6 +30,7 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as EnvironmentAuthPolicy from "./EnvironmentAuthPolicy.ts";
import * as PairingGrantStore from "./PairingGrantStore.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
@@ -562,6 +563,34 @@ function parseDpopToken(request: HttpServerRequest.HttpServerRequest): string |
return token.length > 0 ? token : null;
}
export function selectRequestCredential(
request: HttpServerRequest.HttpServerRequest,
cookieName: string,
legacyCookieName: string | undefined,
) {
const cookieToken = request.cookies[cookieName];
if (cookieToken !== undefined) {
return { token: cookieToken, source: "cookie" } as const;
}
const bearerToken = parseBearerToken(request);
if (bearerToken !== null) {
return { token: bearerToken, source: "bearer" } as const;
}
const dpopToken = parseDpopToken(request);
if (dpopToken !== null) {
return { token: dpopToken, source: "dpop" } as const;
}
const legacyToken = legacyCookieName ? request.cookies[legacyCookieName] : undefined;
if (legacyToken !== undefined) {
return { token: legacyToken, source: "legacy-cookie" } as const;
}
return undefined;
}
export const make = Effect.gen(function* () {
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
@@ -600,17 +629,19 @@ export const make = Effect.gen(function* () {
const authenticateRequest = (
request: HttpServerRequest.HttpServerRequest,
): Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError> => {
const cookieToken = request.cookies[sessions.cookieName];
const bearerToken = parseBearerToken(request);
const dpopToken = parseDpopToken(request);
const credential = cookieToken ?? bearerToken ?? dpopToken;
if (!credential) {
const credential = selectRequestCredential(
request,
sessions.cookieName,
sessions.legacyCookieName,
);
if (!credential?.token) {
return Effect.fail(new ServerAuthMissingCredentialError({}));
}
return authenticateToken(credential).pipe(
const dpopToken = parseDpopToken(request);
return authenticateToken(credential.token).pipe(
Effect.flatMap((session) => {
if (session.proofKeyThumbprint) {
if (!dpopToken || dpopToken !== credential) {
if (!dpopToken || dpopToken !== credential.token) {
return Effect.fail(
new ServerAuthInvalidCredentialError({
diagnostic: "DPoP-bound access token requires DPoP authorization.",
@@ -1003,4 +1034,7 @@ export const layer = Layer.effect(EnvironmentAuth, make).pipe(
export const storageLayer = Layer.mergeAll(ServerSecretStore.layer, SqlitePersistenceLayer);
export const runtimeLayer = layer.pipe(Layer.provideMerge(storageLayer));
export const runtimeLayer = layer.pipe(
Layer.provideMerge(storageLayer),
Layer.provideMerge(ServerEnvironment.identityLayer),
);
@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
@@ -35,6 +36,7 @@ const makeEnvironmentAuthLayer = (
EnvironmentAuth.layer.pipe(
Layer.provideMerge(ServerSecretStore.layer),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provide(ServerEnvironment.identityLayer),
Layer.provide(makeServerConfigLayer(overrides)),
);
@@ -4,12 +4,14 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as EnvironmentAuthPolicy from "./EnvironmentAuthPolicy.ts";
const makeEnvironmentAuthPolicyLayer = (
overrides?: Partial<ServerConfig.ServerConfig["Service"]>,
) =>
EnvironmentAuthPolicy.layer.pipe(
Layer.provide(ServerEnvironment.identityLayer),
Layer.provide(
Layer.effect(
ServerConfig.ServerConfig,
@@ -107,7 +109,7 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
expect(descriptor.policy).toBe("remote-reachable");
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
expect(descriptor.sessionCookieName).toBe("t3_session");
expect(descriptor.sessionCookieName).toMatch(/^t3_session_[a-f0-9]{12}$/);
}).pipe(
Effect.provide(
makeEnvironmentAuthPolicyLayer({
@@ -143,7 +145,7 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
const descriptor = yield* policy.getDescriptor();
expect(descriptor.policy).toBe("remote-reachable");
expect(descriptor.sessionCookieName).toBe("t3_session");
expect(descriptor.sessionCookieName).toMatch(/^t3_session_[a-f0-9]{12}$/);
}).pipe(
Effect.provide(
makeEnvironmentAuthPolicyLayer({
@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import { isRemoteReachableHost, resolveSessionCookieName } from "./utils.ts";
export class EnvironmentAuthPolicy extends Context.Service<
@@ -15,6 +16,7 @@ export class EnvironmentAuthPolicy extends Context.Service<
export const make = Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const serverEnvironment = yield* ServerEnvironment.ServerEnvironmentIdentity;
const isRemoteReachable = isRemoteReachableHost(config.host);
const policy =
@@ -42,6 +44,7 @@ export const make = Effect.gen(function* () {
port: config.port,
host: config.host,
instanceKey: config.stateDir,
environmentId: yield* serverEnvironment.getEnvironmentId,
development: config.devUrl !== undefined,
}),
};
+33 -4
View File
@@ -1,4 +1,5 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { EnvironmentId } from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -7,15 +8,14 @@ import * as TestClock from "effect/testing/TestClock";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import { PersistenceSqlError } from "../persistence/Errors.ts";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import * as AuthSessions from "../persistence/AuthSessions.ts";
import * as SessionStore from "./SessionStore.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
const makeServerConfigLayer = (
overrides?: Partial<Pick<ServerConfig.ServerConfig["Service"], "desktopBootstrapToken">>,
) =>
const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Service"]>) =>
Layer.effect(
ServerConfig.ServerConfig,
Effect.gen(function* () {
@@ -27,12 +27,19 @@ const makeServerConfigLayer = (
}),
).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-session-test-" })));
const makeServerEnvironmentLayer = (environmentId: EnvironmentId) =>
Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, {
getEnvironmentId: Effect.succeed(environmentId),
});
const makeSessionStoreLayer = (
overrides?: Partial<Pick<ServerConfig.ServerConfig["Service"], "desktopBootstrapToken">>,
overrides?: Partial<ServerConfig.ServerConfig["Service"]>,
environmentId = EnvironmentId.make("test-environment"),
) =>
SessionStore.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
Layer.provide(ServerSecretStore.layer),
Layer.provide(makeServerEnvironmentLayer(environmentId)),
Layer.provide(makeServerConfigLayer(overrides)),
);
@@ -58,10 +65,32 @@ const failingSessionLookupCredentialLayer = Layer.effect(
Layer.provide(failingSessionLookupRepositoryLayer),
Layer.provide(ServerSecretStore.layer),
Layer.provide(SqlitePersistenceMemory),
Layer.provide(makeServerEnvironmentLayer(EnvironmentId.make("test-environment"))),
Layer.provide(makeServerConfigLayer()),
);
it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
it.effect("keys remote cookies by environment identity instead of state directory", () =>
Effect.gen(function* () {
const cookieName = (stateDir: string, environmentId: EnvironmentId) =>
Effect.gen(function* () {
const sessions = yield* SessionStore.SessionStore;
return sessions.cookieName;
}).pipe(
Effect.provide(
makeSessionStoreLayer({ mode: "web", host: "192.168.1.50", stateDir }, environmentId),
),
);
const original = yield* cookieName("/srv/t3-one", EnvironmentId.make("environment-one"));
const moved = yield* cookieName("/srv/t3-moved", EnvironmentId.make("environment-one"));
const other = yield* cookieName("/srv/t3-one", EnvironmentId.make("environment-two"));
expect(moved).toBe(original);
expect(other).not.toBe(original);
}),
);
it.effect("issues and verifies signed browser session tokens", () =>
Effect.gen(function* () {
const sessions = yield* SessionStore.SessionStore;
+10 -2
View File
@@ -21,11 +21,13 @@ import * as Stream from "effect/Stream";
import * as Option from "effect/Option";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as AuthSessions from "../persistence/AuthSessions.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
import {
base64UrlDecodeUtf8,
base64UrlEncode,
resolveLegacySessionCookieName,
resolveSessionCookieName,
signPayload,
timingSafeEqualBase64Url,
@@ -360,6 +362,7 @@ export class SessionStore extends Context.Service<
SessionStore,
{
readonly cookieName: string;
readonly legacyCookieName: string | undefined;
readonly issue: (input?: {
readonly ttl?: Duration.Duration;
readonly subject?: string;
@@ -470,18 +473,22 @@ function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthCli
export const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const serverConfig = yield* ServerConfig.ServerConfig;
const serverEnvironment = yield* ServerEnvironment.ServerEnvironmentIdentity;
const secretStore = yield* ServerSecretStore.ServerSecretStore;
const authSessions = yield* AuthSessions.AuthSessionRepository;
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
const cookieName = resolveSessionCookieName({
const cookieInput = {
mode: serverConfig.mode,
port: serverConfig.port,
host: serverConfig.host,
instanceKey: serverConfig.stateDir,
environmentId: yield* serverEnvironment.getEnvironmentId,
development: serverConfig.devUrl !== undefined,
});
} as const;
const cookieName = resolveSessionCookieName(cookieInput);
const legacyCookieName = resolveLegacySessionCookieName(cookieInput);
const emitUpsert = (clientSession: AuthClientSession) =>
PubSub.publish(changesPubSub, {
@@ -930,6 +937,7 @@ export const make = Effect.gen(function* () {
return SessionStore.of({
cookieName,
legacyCookieName,
issue,
verify,
issueWebSocketToken,
+37 -12
View File
@@ -171,6 +171,23 @@ export function failEnvironmentInternal(reason: EnvironmentInternalErrorReason,
});
}
const appendSessionCookie = (cookieName: string, token: string, expiresAt: DateTime.DateTime) =>
Effect.fromResult(
Cookies.set(Cookies.empty, cookieName, token, {
expires: DateTime.toDate(expiresAt),
httpOnly: true,
path: "/",
sameSite: "lax",
}),
).pipe(
Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")),
Effect.flatMap((cookies) =>
HttpEffect.appendPreResponseHandler((_request, response) =>
Effect.succeed(HttpServerResponse.mergeCookies(response, cookies)),
),
),
);
export const requireEnvironmentScope = Effect.fn("environment.auth.requireScope")(function* (
scope: AuthEnvironmentScope,
) {
@@ -224,7 +241,22 @@ export const authHttpApiLayer = HttpApiBuilder.group(
function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
const request = yield* HttpServerRequest.HttpServerRequest;
return yield* serverAuth.getSessionState(request);
const result = yield* serverAuth.getSessionState(request);
const credential = EnvironmentAuth.selectRequestCredential(
request,
sessions.cookieName,
sessions.legacyCookieName,
);
if (
credential?.source === "legacy-cookie" &&
result.authenticated &&
result.sessionMethod === "browser-session-cookie" &&
result.expiresAt
) {
yield* appendSessionCookie(sessions.cookieName, credential.token, result.expiresAt);
yield* appendCredentialResponseHeaders;
}
return result;
},
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("internal_error", error),
@@ -241,17 +273,10 @@ export const authHttpApiLayer = HttpApiBuilder.group(
args.payload.credential,
deriveAuthClientMetadata({ request }),
);
const sessionCookies = yield* Effect.fromResult(
Cookies.set(Cookies.empty, sessions.cookieName, result.sessionToken, {
expires: DateTime.toDate(result.response.expiresAt),
httpOnly: true,
path: "/",
sameSite: "lax",
}),
).pipe(Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")));
yield* HttpEffect.appendPreResponseHandler((_request, response) =>
Effect.succeed(HttpServerResponse.mergeCookies(response, sessionCookies)),
yield* appendSessionCookie(
sessions.cookieName,
result.sessionToken,
result.response.expiresAt,
);
yield* appendCredentialResponseHeaders;
return result.response;
+46 -19
View File
@@ -64,6 +64,7 @@ describe("session cookie isolation", () => {
port: 5775,
host: "127.0.0.1",
instanceKey: "/tmp/t3-agent-one",
environmentId: "environment-one",
development: true,
});
const second = resolveSessionCookieName({
@@ -71,6 +72,7 @@ describe("session cookie isolation", () => {
port: 5775,
host: "127.0.0.1",
instanceKey: "/tmp/t3-agent-two",
environmentId: "environment-two",
development: true,
});
@@ -79,25 +81,48 @@ describe("session cookie isolation", () => {
expect(first).not.toBe(second);
});
it("keeps the hosted web cookie stable across server instances", () => {
expect(
resolveSessionCookieName({
mode: "web",
port: 8080,
host: "0.0.0.0",
instanceKey: "/srv/release-a",
development: false,
}),
).toBe("t3_session");
expect(
resolveSessionCookieName({
mode: "web",
port: 9090,
host: "app.example.com",
instanceKey: "/srv/release-b",
development: false,
}),
).toBe("t3_session");
it("isolates remote web servers by server state", () => {
const first = resolveSessionCookieName({
mode: "web",
port: 3773,
host: "192.168.1.50",
instanceKey: "/srv/t3-one",
environmentId: "environment-one",
development: false,
});
const second = resolveSessionCookieName({
mode: "web",
port: 5775,
host: "192.168.1.50",
instanceKey: "/srv/t3-two",
environmentId: "environment-two",
development: false,
});
expect(first).toMatch(/^t3_session_[a-f0-9]{12}$/);
expect(second).toMatch(/^t3_session_[a-f0-9]{12}$/);
expect(first).not.toBe(second);
});
it("keeps a remote web server cookie stable across port changes", () => {
const first = resolveSessionCookieName({
mode: "web",
port: 8080,
host: "0.0.0.0",
instanceKey: "/srv/t3",
environmentId: "environment-one",
development: false,
});
const second = resolveSessionCookieName({
mode: "web",
port: 9090,
host: "app.example.com",
instanceKey: "/srv/t3",
environmentId: "environment-one",
development: false,
});
expect(first).toBe(second);
});
it("retains desktop port scoping", () => {
@@ -107,6 +132,7 @@ describe("session cookie isolation", () => {
port: 3773,
host: "127.0.0.1",
instanceKey: "/tmp/desktop",
environmentId: "environment-one",
development: true,
}),
).toBe("t3_session_3773");
@@ -119,6 +145,7 @@ describe("session cookie isolation", () => {
port: 5775,
host: "0.0.0.0",
instanceKey: "/tmp/t3-wildcard-dev",
environmentId: "environment-one",
development: true,
}),
).toMatch(/^t3_session_5775_[a-f0-9]{12}$/);
+24 -11
View File
@@ -16,40 +16,53 @@ const SESSION_COOKIE_NAME = "t3_session";
* 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:
* Remote web servers use their persisted environment identity and omit the
* port, so the name survives state-directory moves and public port changes.
*
* - **Dev servers** (`devUrl` set), which run several at a time across worktrees.
* - **Desktop**, which scans upward from 3773 for a free port and binds
* Desktop 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.
*/
export function resolveSessionCookieName(input: {
readonly mode: "web" | "desktop";
readonly port: number;
readonly host: string | undefined;
readonly instanceKey: string;
readonly environmentId: string;
readonly development: boolean;
}): string {
if (input.mode === "desktop") {
return `${SESSION_COOKIE_NAME}_${input.port}`;
}
const instanceHash = NodeCrypto.createHash("sha256")
.update(
!input.development && isRemoteReachableHost(input.host)
? input.environmentId
: input.instanceKey,
)
.digest("hex")
.slice(0, 12);
if (!input.development && isRemoteReachableHost(input.host)) {
return SESSION_COOKIE_NAME;
return `${SESSION_COOKIE_NAME}_${instanceHash}`;
}
// Cookies are scoped by host, not port. Loopback development servers need an
// instance-specific name or parallel agents overwrite each other's session,
// and a server that later reuses the port receives a token signed elsewhere.
const instanceHash = NodeCrypto.createHash("sha256")
.update(input.instanceKey)
.digest("hex")
.slice(0, 12);
return `${SESSION_COOKIE_NAME}_${input.port}_${instanceHash}`;
}
export function resolveLegacySessionCookieName(input: {
readonly mode: "web" | "desktop";
readonly host: string | undefined;
readonly development: boolean;
}): string | undefined {
return input.mode === "web" && !input.development && isRemoteReachableHost(input.host)
? SESSION_COOKIE_NAME
: undefined;
}
export function isRemoteReachableHost(host: string | undefined): boolean {
if (host === "0.0.0.0" || host === "::" || host === "[::]") {
return true;
+27 -2
View File
@@ -13,6 +13,7 @@ import {
ThreadId,
} from "@t3tools/contracts";
import * as NetService from "@t3tools/shared/Net";
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as DateTime from "effect/DateTime";
@@ -26,7 +27,13 @@ import * as TestConsole from "effect/testing/TestConsole";
import { Command } from "effect/unstable/cli";
import { cli, makeCli } from "./bin.ts";
import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
import {
SERVICE_LAUNCHER_CONTEXT_ENV,
SERVICE_LAUNCHER_PROTOCOL,
} from "./cloud/serviceProtocol.ts";
import * as ServerConfig from "./config.ts";
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
@@ -42,7 +49,24 @@ import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import { environmentAuthenticatedAuthLayer } from "./auth/http.ts";
import packageJson from "../package.json" with { type: "json" };
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
const DisconnectedLauncherChildLayer = Layer.mergeAll(
Layer.succeed(HostProcessEnvironment, {
...process.env,
[SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify({
protocol: SERVICE_LAUNCHER_PROTOCOL,
childVersion: packageJson.version,
}),
}),
Layer.succeed(ServiceLauncherClient.ServiceLauncherHostProcess, {
connected: false,
send: () => false,
on: () => undefined,
off: () => undefined,
}),
);
class ProjectCliHttpApi extends HttpApi.make("environment").add(EnvironmentOrchestrationHttpApi) {}
const connectCli = makeCli({ cloudEnabled: true });
@@ -127,6 +151,7 @@ const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Ef
Layer.provideMerge(
EnvironmentAuth.layer.pipe(
Layer.provideMerge(SqlitePersistenceLayerLive),
Layer.provide(ServerEnvironment.identityLayer),
Layer.provide(ServerSecretStore.layer),
),
),
@@ -237,7 +262,7 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
assert.equal(status.linked, false);
assert.equal(status.cloudUserId, null);
assert.equal(status.relayUrl, null);
}),
}).pipe(Effect.provide(DisconnectedLauncherChildLayer)),
);
it.effect("reports actionable human-readable headless connect state", () =>
@@ -408,7 +433,7 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
"relay:write",
]);
assert.equal("token" in (listed[0] ?? {}), false);
}),
}).pipe(Effect.provide(DisconnectedLauncherChildLayer)),
);
it.effect("rejects invalid ttl values before running auth commands", () =>
+2 -3
View File
@@ -337,7 +337,7 @@ const unlinkRelayEnvironment = Effect.fn("cloud.cli.unlink_relay_environment")(f
return { status: "not-authenticated" } satisfies RelayUnlinkResult;
}
const environment = yield* ServerEnvironment.ServerEnvironment;
const environment = yield* ServerEnvironment.ServerEnvironmentIdentity;
const environmentId = yield* environment.getEnvironmentId;
const relayUrl = yield* relayUrlConfig;
const httpClient = yield* HttpClient.HttpClient;
@@ -432,7 +432,7 @@ const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E
| HttpClient.HttpClient
| Prompt.Environment
| ServerConfig.ServerConfig
| ServerEnvironment.ServerEnvironment
| ServerEnvironment.ServerEnvironmentIdentity
>,
options?: {
readonly quietLogs?: boolean;
@@ -449,7 +449,6 @@ const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E
),
RelayClient.layerCloudflared({ baseDir: config.baseDir }),
EnvironmentAuth.runtimeLayer,
ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)),
bootServiceLayer(config),
headlessRelayClientTracingLayer,
).pipe(
+24 -1
View File
@@ -6,6 +6,7 @@ import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NetService from "@t3tools/shared/Net";
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import { assert, describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -13,6 +14,11 @@ import * as TestConsole from "effect/testing/TestConsole";
import { Command } from "effect/unstable/cli";
import { cli } from "../bin.ts";
import {
SERVICE_LAUNCHER_CONTEXT_ENV,
SERVICE_LAUNCHER_PROTOCOL,
} from "../cloud/serviceProtocol.ts";
import * as ServiceLauncherClient from "../cloud/serviceLauncherClient.ts";
import {
makePersistedServerRuntimeState,
persistServerRuntimeState,
@@ -24,6 +30,8 @@ import {
resolveTailscaleLocalTarget,
} from "./pair.ts";
import packageJson from "../../package.json" with { type: "json" };
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
const baseState = {
@@ -170,7 +178,22 @@ describe("t3 pair", () => {
assert.equal(credentials.length, 1);
assert.equal(credentials[0]?.label, "t3 pair");
}),
).pipe(Effect.provide(NodeServices.layer)),
).pipe(
Effect.provide(NodeServices.layer),
Effect.provideService(HostProcessEnvironment, {
...process.env,
[SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify({
protocol: SERVICE_LAUNCHER_PROTOCOL,
childVersion: packageJson.version,
}),
}),
Effect.provideService(ServiceLauncherClient.ServiceLauncherHostProcess, {
connected: false,
send: () => false,
on: () => undefined,
off: () => undefined,
}),
),
);
it.effect("pairs through the recorded dev web URL for dev servers", () =>
@@ -1,5 +1,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Crypto from "effect/Crypto";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -71,6 +73,77 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
});
it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
it.effect.each([
{ name: "missing", content: undefined },
{ name: "empty", content: "" },
{ name: "whitespace-only", content: " \t\n" },
])("concurrent initializers recover a $name environment id file", ({ content }) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const crypto = yield* Crypto.Crypto;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-server-environment-concurrent-test-",
});
const serverConfig = yield* makeServerConfig(baseDir);
yield* fileSystem.makeDirectory(serverConfig.stateDir, { recursive: true });
if (content !== undefined) {
yield* fileSystem.writeFileString(serverConfig.environmentIdPath, content);
}
const bothGenerated = yield* Deferred.make<void>();
const bothReadEmpty = yield* Deferred.make<void>();
const firstInitialized = yield* Deferred.make<void>();
let remaining = 2;
let emptyReads = 0;
const readIdentity = Effect.gen(function* () {
const identity = yield* ServerEnvironment.ServerEnvironmentIdentity;
return yield* identity.getEnvironmentId;
}).pipe(
Effect.tap(() => Deferred.succeed(firstInitialized, undefined)),
Effect.provide(Layer.fresh(ServerEnvironment.identityLayer)),
Effect.provideService(ServerConfig.ServerConfig, serverConfig),
Effect.provideService(FileSystem.FileSystem, {
...fileSystem,
readFileString: (path) =>
fileSystem.readFileString(path).pipe(
Effect.tap(
Effect.fn(function* (value) {
if (path !== serverConfig.environmentIdPath || remaining > 0 || value.trim()) {
return;
}
// Both observe the empty file, but one repairs it after the other has finished.
if (++emptyReads === 2) {
yield* Deferred.succeed(bothReadEmpty, undefined);
yield* Deferred.await(firstInitialized);
} else {
yield* Deferred.await(bothReadEmpty);
}
}),
),
),
}),
Effect.provideService(Crypto.Crypto, {
...crypto,
randomUUIDv4: Effect.gen(function* () {
const id = yield* crypto.randomUUIDv4;
if (--remaining === 0) {
yield* Deferred.succeed(bothGenerated, undefined);
}
yield* Deferred.await(bothGenerated);
return id;
}),
}),
);
const [first, second] = yield* Effect.all([readIdentity, readIdentity], {
concurrency: "unbounded",
});
const persisted = yield* fileSystem.readFileString(serverConfig.environmentIdPath);
expect(first).toBe(second);
expect(persisted.trim()).toBe(first);
}),
);
it.effect("persists the environment id across service restarts", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -153,6 +226,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
});
const serverConfig = yield* makeServerConfig(baseDir);
const environmentIdPath = serverConfig.environmentIdPath;
const tempPath = `${environmentIdPath}.tmp`;
const methodByOperation = {
check: "exists",
read: "readFileString",
@@ -172,6 +246,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
exists: () =>
operation === "check" ? Effect.fail(cause) : Effect.succeed(operation === "read"),
readFileString: () => Effect.fail(cause),
makeTempFileScoped: () => Effect.succeed(tempPath),
writeFileString: (path) => {
writeAttempts.push(path);
return Effect.fail(cause);
@@ -201,7 +276,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
expect(error.message).toBe(
`Server environment ID ${operation} failed at '${environmentIdPath}'.`,
);
expect(writeAttempts).toEqual(operation === "write" ? [environmentIdPath] : []);
expect(writeAttempts).toEqual(operation === "write" ? [tempPath] : []);
}
}),
);
@@ -24,12 +24,15 @@ import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
export class ServerEnvironmentIdPersistenceError extends Schema.TaggedErrorClass<ServerEnvironmentIdPersistenceError>()(
"ServerEnvironmentIdPersistenceError",
{
operation: Schema.Literals(["check", "read", "write"]),
operation: Schema.Literals(["check", "read", "write", "initialize"]),
environmentIdPath: Schema.String,
cause: Schema.Defect(),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
if (this.operation === "initialize") {
return `Server environment ID file is missing or empty after initialization at '${this.environmentIdPath}'.`;
}
return `Server environment ID ${this.operation} failed at '${this.environmentIdPath}'.`;
}
}
@@ -42,6 +45,13 @@ export class ServerEnvironment extends Context.Service<
}
>()("t3/environment/ServerEnvironment") {}
export class ServerEnvironmentIdentity extends Context.Service<
ServerEnvironmentIdentity,
{
readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
}
>()("t3/environment/ServerEnvironment/ServerEnvironmentIdentity") {}
function platformOs(platform: NodeJS.Platform): ExecutionEnvironmentDescriptor["platform"]["os"] {
switch (platform) {
case "darwin":
@@ -68,14 +78,10 @@ function platformArch(
}
}
export const make = Effect.gen(function* () {
const makeIdentity = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig.ServerConfig;
const secrets = yield* ServerSecretStore.ServerSecretStore;
const crypto = yield* Crypto.Crypto;
const hostPlatform = yield* HostProcessPlatform;
const hostArchitecture = yield* HostProcessArchitecture;
const readPersistedEnvironmentId = Effect.gen(function* () {
const exists = yield* fileSystem.exists(serverConfig.environmentIdPath).pipe(
@@ -107,17 +113,42 @@ export const make = Effect.gen(function* () {
return raw.length > 0 ? raw : null;
});
const persistEnvironmentId = (value: string) =>
fileSystem.writeFileString(serverConfig.environmentIdPath, `${value}\n`).pipe(
Effect.mapError(
(cause) =>
new ServerEnvironmentIdPersistenceError({
operation: "write",
environmentIdPath: serverConfig.environmentIdPath,
cause,
}),
),
);
const persistEnvironmentId = Effect.fn("ServerEnvironmentIdentity.persistEnvironmentId")(
function* (value: string, mode: "create" | "recover") {
const destinationPath =
mode === "recover"
? `${serverConfig.environmentIdPath}.recovery`
: serverConfig.environmentIdPath;
const tempPath = yield* fileSystem.makeTempFileScoped({
directory: serverConfig.stateDir,
prefix: ".environment-id-",
});
yield* fileSystem.writeFileString(tempPath, `${value}\n`);
// Publish the completed file without replacing an ID created by another process.
yield* fileSystem
.link(tempPath, destinationPath)
.pipe(
Effect.catch((cause) =>
cause.reason._tag === "AlreadyExists" ? Effect.void : Effect.fail(cause),
),
);
if (mode === "recover") {
// Keep the recovery ID so delayed initializers also publish the same winner.
yield* fileSystem.remove(tempPath);
yield* fileSystem.copyFile(destinationPath, tempPath);
yield* fileSystem.rename(tempPath, serverConfig.environmentIdPath);
}
},
Effect.scoped,
Effect.mapError(
(cause) =>
new ServerEnvironmentIdPersistenceError({
operation: "write",
environmentIdPath: serverConfig.environmentIdPath,
cause,
}),
),
);
const environmentIdRaw = yield* Effect.gen(function* () {
const persisted = yield* readPersistedEnvironmentId;
@@ -126,11 +157,35 @@ export const make = Effect.gen(function* () {
}
const generated = yield* crypto.randomUUIDv4;
yield* persistEnvironmentId(generated);
return generated;
yield* persistEnvironmentId(generated, "create");
let winner = yield* readPersistedEnvironmentId;
if (winner === null) {
yield* persistEnvironmentId(generated, "recover");
winner = yield* readPersistedEnvironmentId;
}
if (winner === null) {
return yield* new ServerEnvironmentIdPersistenceError({
operation: "initialize",
environmentIdPath: serverConfig.environmentIdPath,
});
}
return winner;
});
const environmentId = EnvironmentId.make(environmentIdRaw);
return ServerEnvironmentIdentity.of({
getEnvironmentId: Effect.succeed(environmentId),
});
});
export const make = Effect.gen(function* () {
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig.ServerConfig;
const secrets = yield* ServerSecretStore.ServerSecretStore;
const identity = yield* ServerEnvironmentIdentity;
const hostPlatform = yield* HostProcessPlatform;
const hostArchitecture = yield* HostProcessArchitecture;
const environmentId = yield* identity.getEnvironmentId;
const cwdBaseName = path.basename(serverConfig.cwd).trim();
const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });
const launcher = yield* resolveServiceLauncherMode();
@@ -179,10 +234,15 @@ export const make = Effect.gen(function* () {
});
});
export const identityLayer = Layer.effect(ServerEnvironmentIdentity, makeIdentity);
/**
* ServerEnvironment is acquired from persisted filesystem and host-process
* state. It intentionally has no fallback Layer.succeed value: callers must
* provide the external platform services, a ServerConfig, and the
* ServerSecretStore backing the descriptor's publishing capability.
*/
export const layer = Layer.effect(ServerEnvironment, make).pipe(Layer.provide(ProcessRunner.layer));
export const layer = Layer.effect(ServerEnvironment, make).pipe(
Layer.provideMerge(identityLayer),
Layer.provide(ProcessRunner.layer),
);
+47
View File
@@ -291,6 +291,11 @@ const makeAuthTestLayer = () =>
EnvironmentAuth.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
Layer.provide(ServerSecretStore.layer),
Layer.provide(
Layer.mock(ServerEnvironment.ServerEnvironmentIdentity)({
getEnvironmentId: Effect.succeed(testEnvironmentDescriptor.environmentId),
}),
),
);
const makeBrowserOtlpPayload = (spanName: string) =>
@@ -1674,6 +1679,48 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("migrates a valid legacy remote-web session cookie", () =>
Effect.gen(function* () {
yield* buildAppUnderTest({ config: { mode: "web", host: "192.168.1.50" } });
const { cookie } = yield* bootstrapBrowserSession();
const currentCookie = cookie?.split(";")[0] ?? "";
const legacyCookie = currentCookie.replace(/^t3_session_[^=]+=/, "t3_session=");
const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
const response = yield* fetchEffect(sessionUrl, {
headers: { cookie: legacyCookie },
});
const body = yield* responseJsonEffect<{ readonly authenticated: boolean }>(response);
assert.equal(body.authenticated, true);
assert.equal(response.headers["set-cookie"], cookie);
assert.equal(response.headers["cache-control"], "no-store");
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect.each(["cookie", "bearer"])(
"does not migrate a stale legacy cookie when %s auth succeeds",
(source) =>
Effect.gen(function* () {
yield* buildAppUnderTest({ config: { mode: "web", host: "192.168.1.50" } });
const { cookie } = yield* bootstrapBrowserSession();
const sessionCookie = cookie?.split(";")[0] ?? "";
const sessionToken = extractSessionTokenFromSetCookie(cookie ?? "");
const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
const response = yield* fetchEffect(sessionUrl, {
headers:
source === "cookie"
? { cookie: `${sessionCookie}; t3_session=stale` }
: { authorization: `Bearer ${sessionToken}`, cookie: "t3_session=stale" },
});
const body = yield* responseJsonEffect<{ readonly authenticated: boolean }>(response);
assert.equal(body.authenticated, true);
assert.isUndefined(response.headers["set-cookie"]);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("exchanges a bootstrap grant for a scoped bearer access token", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
+6 -1
View File
@@ -362,8 +362,13 @@ const ProjectFaviconResolverLayerLive = ProjectFaviconResolver.layer.pipe(
Layer.provide(T3ProjectFileLoader.layer),
);
const ServerEnvironmentLayerLive = ServerEnvironment.layer.pipe(
Layer.provide(ServerSecretStore.layer),
);
const AuthLayerLive = EnvironmentAuth.layer.pipe(
Layer.provideMerge(PersistenceLayerLive),
Layer.provide(ServerEnvironmentLayerLive),
Layer.provide(ServerSecretStore.layer),
);
@@ -418,7 +423,7 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
Layer.provideMerge(WorkspaceLayerLive),
Layer.provideMerge(ProjectFaviconResolverLayerLive),
Layer.provideMerge(RepositoryIdentityResolver.layer),
Layer.provideMerge(ServerEnvironment.layer),
Layer.provideMerge(ServerEnvironmentLayerLive),
Layer.provideMerge(AuthLayerLive),
Layer.provideMerge(ServerSecretStore.layer),
Layer.provideMerge(
+4
View File
@@ -41,6 +41,10 @@ It is identified by a stable `environmentId`, persisted by the server at `<state
and generated on first start (`apps/server/src/environment/ServerEnvironment.ts`). Desktop, mobile,
and web all reason about the same concept.
Initialization publishes a complete ID atomically. Empty or whitespace-only ID files are repaired
using a retained `<stateDir>/environment-id.recovery` file so concurrent and delayed repairs choose
the same ID. Existing nonempty ID files remain authoritative.
### Known environments and connection targets
A saved client-side entry for an environment the client knows how to reach. It is not