diff --git a/apps/server/src/auth/SessionStore.ts b/apps/server/src/auth/SessionStore.ts
index 5717479a47ba9..747e1ea955dd8 100644
--- a/apps/server/src/auth/SessionStore.ts
+++ b/apps/server/src/auth/SessionStore.ts
@@ -1014,14 +1014,20 @@ const make = Effect.gen(function* () {
revokedAt,
})
.pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));
- if (revoked) {
- yield* Ref.update(connectedSessionsRef, (current) => {
- const next = new Map(current);
- next.delete(sessionId);
- return next;
- });
- yield* emitRemoved(sessionId);
+ if (!revoked) {
+ // Another process, such as the CLI's database fallback, can revoke the row
+ // without reaching this process's open connections. Signal them anyway.
+ const row = yield* authSessions
+ .getById({ sessionId })
+ .pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));
+ if (Option.isNone(row)) return false;
}
+ yield* Ref.update(connectedSessionsRef, (current) => {
+ const next = new Map(current);
+ next.delete(sessionId);
+ return next;
+ });
+ yield* emitRemoved(sessionId);
return revoked;
},
);
diff --git a/apps/server/src/cli/auth.ts b/apps/server/src/cli/auth.ts
index d57f0c2ef0c6c..2423a210af411 100644
--- a/apps/server/src/cli/auth.ts
+++ b/apps/server/src/cli/auth.ts
@@ -1,11 +1,19 @@
-import { AuthSessionId, AuthStandardClientScopes } from "@t3tools/contracts";
+import {
+ AuthAccessWriteScope,
+ AuthSessionId,
+ AuthStandardClientScopes,
+ EnvironmentHttpApi,
+} from "@t3tools/contracts";
import * as Console from "effect/Console";
+import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as References from "effect/References";
import * as Schema from "effect/Schema";
import { Argument, Command, Flag, GlobalFlag } from "effect/cli";
+import { FetchHttpClient } from "effect/http";
+import * as HttpApiClient from "effect/http-api/HttpApiClient";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
@@ -17,6 +25,13 @@ import {
formatSessionList,
} from "../cliAuthFormat.ts";
import * as ServerConfig from "../config.ts";
+import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
+import * as ProcessRunner from "../processRunner.ts";
+import {
+ isProcessAlive,
+ readPersistedServerRuntimeState,
+ recordedProcessStartMatches,
+} from "../serverRuntimeState.ts";
import { authScopesFlag } from "./authScopes.ts";
import {
authLocationFlags,
@@ -25,9 +40,9 @@ import {
resolveCliAuthConfig,
} from "./config.ts";
-const runWithEnvironmentAuth = Effect.fn("auth.runWithEnvironmentAuth")(function* (
+const runWithEnvironmentAuth = Effect.fn("auth.runWithEnvironmentAuth")(function* (
flags: CliAuthLocationFlags,
- run: (environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"]) => Effect.Effect,
+ run: (environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"]) => Effect.Effect,
options?: {
readonly quietLogs?: boolean;
},
@@ -40,8 +55,8 @@ const runWithEnvironmentAuth = Effect.fn("auth.runWithEnvironmentAuth")(function
return yield* run(environmentAuth);
}).pipe(
Effect.provide(
- Layer.mergeAll(EnvironmentAuth.layerRuntime).pipe(
- Layer.provide(ServerConfig.layer(config)),
+ Layer.mergeAll(EnvironmentAuth.layerRuntime, FetchHttpClient.layer).pipe(
+ Layer.provideMerge(ServerConfig.layer(config)),
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
),
),
@@ -298,6 +313,89 @@ const sessionListCommand = Command.make("list", {
),
);
+class OtherEnvironmentAtOriginError extends Schema.TaggedError()(
+ "OtherEnvironmentAtOriginError",
+ { origin: Schema.String },
+) {
+ override get message(): string {
+ return `The server at ${this.origin} serves another T3 home.`;
+ }
+}
+
+class RecordedServerProcessError extends Schema.TaggedError()(
+ "RecordedServerProcessError",
+ { pid: Schema.Number },
+) {
+ override get message(): string {
+ return `Process ${this.pid} may not be the server recorded in server-runtime.json.`;
+ }
+}
+
+const LIVE_SERVER_TIMEOUT = Duration.seconds(10);
+// Bounds how long the helper session outlives a CLI killed before it can revoke it.
+const LIVE_SERVER_SESSION_TTL = Duration.minutes(1);
+
+// Database-only revocation cannot signal the running server's open sockets.
+const revokeSession = Effect.fn("auth.revokeSession")(function* (
+ environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
+ sessionId: AuthSessionId,
+) {
+ const config = yield* ServerConfig.ServerConfig;
+ const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
+ if (Option.isSome(runtimeState) && isProcessAlive(runtimeState.value.pid)) {
+ const { origin, pid } = runtimeState.value;
+ const identity = yield* ServerEnvironment.ServerEnvironmentIdentity;
+ const environmentId = yield* identity.getEnvironmentId;
+ const attempted = yield* Effect.result(
+ Effect.gen(function* () {
+ // A reused PID can make a stale record look live; contact only the recorded process,
+ // and give a credential only to this home's server.
+ const matches = yield* recordedProcessStartMatches(runtimeState.value).pipe(
+ Effect.provide(ProcessRunner.layer),
+ );
+ if (!Option.getOrElse(matches, () => false)) {
+ return yield* new RecordedServerProcessError({ pid });
+ }
+ const client = yield* HttpApiClient.make(EnvironmentHttpApi, { baseUrl: origin });
+ yield* client.metadata.descriptor().pipe(
+ Effect.filterOrFail(
+ (descriptor) => descriptor.environmentId === environmentId,
+ () => new OtherEnvironmentAtOriginError({ origin }),
+ ),
+ );
+ return yield* Effect.acquireUseRelease(
+ environmentAuth.issueSession({
+ ttl: LIVE_SERVER_SESSION_TTL,
+ scopes: [AuthAccessWriteScope],
+ subject: "auth-cli",
+ label: "t3 auth cli",
+ }),
+ (issued) =>
+ client.auth.revokeClient({
+ headers: { authorization: `Bearer ${issued.token}` },
+ payload: { sessionId },
+ }),
+ (issued) =>
+ environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
+ );
+ }).pipe(Effect.timeout(LIVE_SERVER_TIMEOUT)),
+ );
+ if (attempted._tag === "Success") {
+ // Also revoke this home's record; a no-op when the server already did.
+ const revokedLocally = yield* environmentAuth.revokeSession(sessionId);
+ return attempted.success.revoked || revokedLocally;
+ }
+ yield* Effect.logDebug("Failed to revoke the session through the running server.", {
+ origin,
+ cause: attempted.failure,
+ });
+ yield* Console.error(
+ `Could not reach the T3 Code server at ${origin}. Connections already open with this session stay open until they close.`,
+ );
+ }
+ return yield* environmentAuth.revokeSession(sessionId);
+});
+
const sessionRevokeCommand = Command.make("revoke", {
...authLocationFlags,
sessionId: Argument.String("session-id").pipe(
@@ -309,7 +407,7 @@ const sessionRevokeCommand = Command.make("revoke", {
Command.withHandler((flags) =>
runWithEnvironmentAuth(flags, (environmentAuth) =>
Effect.gen(function* () {
- const revoked = yield* environmentAuth.revokeSession(flags.sessionId);
+ const revoked = yield* revokeSession(environmentAuth, flags.sessionId);
yield* Console.log(
revoked
? `Revoked session ${flags.sessionId}.\n`
diff --git a/apps/server/src/cli/pair.test.ts b/apps/server/src/cli/pair.test.ts
index 9619030be2fab..60d7b6164b370 100644
--- a/apps/server/src/cli/pair.test.ts
+++ b/apps/server/src/cli/pair.test.ts
@@ -5,25 +5,44 @@ import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
+import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as NodeServices from "@effect/platform-node/NodeServices";
-import { AuthStandardClientScopes, ORCHESTRATION_PROTOCOL_VERSION } from "@t3tools/contracts";
+import {
+ AuthStandardClientScopes,
+ EnvironmentHttpApi,
+ ExecutionEnvironmentDescriptor,
+ ORCHESTRATION_PROTOCOL_VERSION,
+} from "@t3tools/contracts";
import * as NetService from "@t3tools/shared/Net";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { assert, describe, expect, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as ConfigProvider from "effect/ConfigProvider";
+import * as Context from "effect/Context";
+import * as DateTime from "effect/DateTime";
+import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
+import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
-import { FetchHttpClient } from "effect/http";
+import { FetchHttpClient, HttpRouter, HttpServer } from "effect/http";
+import * as HttpApi from "effect/http-api/HttpApi";
+import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
import * as TestClock from "effect/testing/TestClock";
import * as TestConsole from "effect/testing/TestConsole";
import { Command, CliError } from "effect/cli";
+import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
+import * as AuthHttp from "../auth/http.ts";
+import * as SessionStore from "../auth/SessionStore.ts";
import { cli } from "../binCli.ts";
+import * as ServerConfig from "../config.ts";
+import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import {
SERVICE_LAUNCHER_CONTEXT_ENV,
SERVICE_LAUNCHER_PROTOCOL,
@@ -34,6 +53,7 @@ import {
persistServerRuntimeState,
type PersistedServerRuntimeState,
} from "../serverRuntimeState.ts";
+import { resolveCliAuthConfig } from "./config.ts";
import { resolveHostCliCommand } from "./invocation.ts";
import {
DevServerNotProxiableError,
@@ -55,6 +75,9 @@ const baseState = {
startedAt: "2026-06-20T00:00:00.000Z",
} as const satisfies PersistedServerRuntimeState;
+// Revoke tests record this test process as the running server.
+const testProcessStartedAt = DateTime.formatIso(DateTime.makeUnsafe(performance.timeOrigin));
+
describe("pair tailscale local target", () => {
it("proxies the dev web port for dev servers", () => {
expect(resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://localhost:5733/" })).toEqual(
@@ -102,19 +125,31 @@ const testDescriptor = {
capabilities: { repositoryIdentity: true },
};
+interface RecordedRequest {
+ readonly url: string | undefined;
+ readonly authorization: string | undefined;
+}
+
const withDescriptorServer = (
- run: (origin: string) => Effect.Effect,
+ run: (origin: string, requests: ReadonlyArray) => Effect.Effect,
host = "127.0.0.1",
descriptor: object = testDescriptor,
-) =>
- Effect.acquireUseRelease(
+) => {
+ const requests: Array = [];
+ return Effect.acquireUseRelease(
Effect.callback((resume) => {
const server = NodeHttp.createServer((request, response) => {
+ requests.push({ url: request.url, authorization: request.headers.authorization });
if (request.url === "/.well-known/t3/environment") {
response.writeHead(200, { "content-type": "application/json" });
response.end(JSON.stringify(descriptor));
return;
}
+ if (request.url === "/api/auth/clients/revoke") {
+ response.writeHead(200, { "content-type": "application/json" });
+ response.end(JSON.stringify({ revoked: true }));
+ return;
+ }
response.writeHead(404);
response.end();
});
@@ -125,10 +160,11 @@ const withDescriptorServer = (
if (address === null || typeof address === "string") {
return Effect.die(new Error("Expected a TCP address"));
}
- return run(`http://${host === "::1" ? "[::1]" : host}:${String(address.port)}`);
+ return run(`http://${host === "::1" ? "[::1]" : host}:${String(address.port)}`, requests);
},
(server) => Effect.sync(() => server.close()),
);
+};
describe("t3 pair", () => {
it.effect("publishes an IPv6-only server through Tailscale Serve when pairing", () =>
@@ -695,6 +731,203 @@ describe("auth scope options", () => {
);
});
+class AuthRoutesApi extends HttpApi.make("environment")
+ .add(EnvironmentHttpApi.groups.metadata)
+ .add(EnvironmentHttpApi.groups.auth) {}
+
+const decodeEnvironmentDescriptor = Schema.decodeUnknownEffect(ExecutionEnvironmentDescriptor);
+
+const layerHomeDescriptor = HttpApiBuilder.group(
+ AuthRoutesApi,
+ "metadata",
+ Effect.fnUntraced(function* (handlers) {
+ const identity = yield* ServerEnvironment.ServerEnvironmentIdentity;
+ const descriptor = yield* decodeEnvironmentDescriptor({
+ ...testDescriptor,
+ environmentId: yield* identity.getEnvironmentId,
+ });
+ return handlers.handle("descriptor", () => Effect.succeed(descriptor));
+ }),
+);
+
+// A separate store must receive the removal event; a database read alone cannot wake open sockets.
+const serveAuthRoutesWithWatchedSession = (baseDir: string) =>
+ Effect.gen(function* () {
+ const config = yield* resolveCliAuthConfig({ baseDir: Option.some(baseDir) }, Option.none());
+ const services = yield* Layer.build(
+ HttpRouter.serve(
+ HttpApiBuilder.layer(AuthRoutesApi).pipe(
+ Layer.provide(layerHomeDescriptor),
+ Layer.provide(AuthHttp.layer),
+ Layer.provide(AuthHttp.layerAuthenticatedAuth),
+ ),
+ { disableListenLog: true, disableLogger: true },
+ ).pipe(
+ Layer.provideMerge(EnvironmentAuth.layerRuntime),
+ Layer.provideMerge(ServerConfig.layer(config)),
+ Layer.provideMerge(NodeHttpServer.layerTest),
+ ),
+ );
+ const origin = HttpServer.formatAddress(Context.get(services, HttpServer.HttpServer).address);
+ const sessions = Context.get(services, SessionStore.SessionStore);
+ const session = yield* sessions.issue({
+ subject: "cli-issued-session",
+ client: { label: "revoke-test", deviceType: "bot" },
+ });
+ const removed = yield* Deferred.make();
+ yield* sessions.streamChanges.pipe(
+ Stream.filter(
+ (change) => change.type === "clientRemoved" && change.sessionId === session.sessionId,
+ ),
+ Stream.runHead,
+ Effect.andThen(Deferred.succeed(removed, undefined)),
+ Effect.forkScoped({ startImmediately: true }),
+ );
+ const persistRunningServer = Effect.gen(function* () {
+ yield* persistServerRuntimeState({
+ path: config.serverRuntimeStatePath,
+ state: {
+ ...(yield* makePersistedServerRuntimeState({
+ config: { host: "127.0.0.1", devUrl: undefined },
+ port: Number(new URL(origin).port),
+ })),
+ startedAt: testProcessStartedAt,
+ },
+ });
+ });
+ return { config, session, removed, persistRunningServer };
+ });
+
+// The recorded server process is alive at `origin`; returns what the revoke printed to stderr.
+const revokeWithRecordedServer = (
+ origin: string,
+ {
+ homeEnvironmentId,
+ startedAt = testProcessStartedAt,
+ }: { readonly homeEnvironmentId?: string; readonly startedAt?: string } = {},
+) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-auth-revoke-local-test-" });
+ const config = yield* resolveCliAuthConfig({ baseDir: Option.some(baseDir) }, Option.none());
+ if (homeEnvironmentId !== undefined) {
+ yield* fs.makeDirectory(config.stateDir, { recursive: true });
+ yield* fs.writeFileString(config.environmentIdPath, homeEnvironmentId);
+ }
+ yield* persistServerRuntimeState({
+ path: config.serverRuntimeStatePath,
+ state: { ...baseState, pid: process.pid, origin, startedAt },
+ });
+
+ const issued = JSON.parse(
+ yield* captureStdout(runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"])),
+ ) as { readonly sessionId: string };
+
+ const stderr = yield* provideCliTestLayers(
+ Effect.gen(function* () {
+ yield* runCli(["auth", "session", "revoke", issued.sessionId, "--base-dir", baseDir]);
+ return yield* TestConsole.errorLines;
+ }),
+ );
+ const listed = JSON.parse(
+ yield* captureStdout(runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"])),
+ ) as ReadonlyArray<{ readonly sessionId: string }>;
+
+ assert.notInclude(
+ listed.map((entry) => entry.sessionId),
+ issued.sessionId,
+ );
+ return stderr;
+ }).pipe(Effect.scoped, Effect.provide(layerCliRuntime));
+
+// The revoke stays in this T3 home's database and warns that open connections stay open.
+const expectDatabaseOnlyRevoke = (
+ origin: string,
+ options?: Parameters[1],
+) =>
+ revokeWithRecordedServer(origin, options).pipe(
+ Effect.map((stderr) =>
+ expect(stderr).toContain(
+ `Could not reach the T3 Code server at ${origin}. Connections already open with this session stay open until they close.`,
+ ),
+ ),
+ );
+
+describe("auth session revoke", () => {
+ it.effect("signals the running server and cleans up its helper session", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-auth-revoke-test-" });
+ const server = yield* serveAuthRoutesWithWatchedSession(baseDir);
+ yield* server.persistRunningServer;
+
+ const output = yield* captureStdout(
+ runCli(["auth", "session", "revoke", server.session.sessionId, "--base-dir", baseDir]),
+ );
+
+ assert.include(output, `Revoked session ${server.session.sessionId}.`);
+ yield* Deferred.await(server.removed);
+ const listed = yield* captureStdout(
+ runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]),
+ );
+ assert.deepEqual(JSON.parse(listed), []);
+ }).pipe(Effect.scoped, Effect.provide(layerCliRuntime)),
+ );
+
+ it.effect("signals the running server when retried after a database-only revoke", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const baseDir = yield* fs.makeTempDirectoryScoped({
+ prefix: "t3-cli-auth-revoke-retry-test-",
+ });
+ const server = yield* serveAuthRoutesWithWatchedSession(baseDir);
+ const revoke = provideCliTestLayers(
+ runCli(["auth", "session", "revoke", server.session.sessionId, "--base-dir", baseDir]),
+ );
+ yield* persistServerRuntimeState({
+ path: server.config.serverRuntimeStatePath,
+ state: {
+ ...baseState,
+ pid: process.pid,
+ origin: "http://127.0.0.1:1",
+ startedAt: testProcessStartedAt,
+ },
+ });
+ yield* revoke;
+ assert.isFalse(yield* Deferred.isDone(server.removed));
+
+ yield* server.persistRunningServer;
+ yield* revoke;
+
+ yield* Deferred.await(server.removed);
+ }).pipe(Effect.scoped, Effect.provide(layerCliRuntime)),
+ );
+
+ it.effect("sends no credential when the recorded origin serves another T3 home", () =>
+ withDescriptorServer((origin, requests) =>
+ Effect.gen(function* () {
+ yield* expectDatabaseOnlyRevoke(origin);
+ assert.deepEqual(requests, [
+ { url: "/.well-known/t3/environment", authorization: undefined },
+ ]);
+ }),
+ ),
+ );
+
+ it.effect("sends nothing when the recorded process start time does not match", () =>
+ withDescriptorServer((origin, requests) =>
+ Effect.gen(function* () {
+ // The recorded start predates this test process, so the PID belongs to a later process.
+ yield* expectDatabaseOnlyRevoke(origin, {
+ homeEnvironmentId: testDescriptor.environmentId,
+ startedAt: "2000-01-01T00:00:00.000Z",
+ });
+ assert.deepEqual(requests, []);
+ }),
+ ),
+ );
+});
+
describe("auth pairing create --base-url", () => {
it.effect.each(["192.168.1.5:3773", "localhost:3773", "ftp://localhost:3773"])(
"rejects %s before issuing a token",
diff --git a/apps/server/src/serverRuntimeState.ts b/apps/server/src/serverRuntimeState.ts
index fc5c85a2a9c1e..0e589f44e6e46 100644
--- a/apps/server/src/serverRuntimeState.ts
+++ b/apps/server/src/serverRuntimeState.ts
@@ -1,4 +1,6 @@
+import * as HostProcess from "@t3tools/shared/HostProcess";
import * as DateTime from "effect/DateTime";
+import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
@@ -8,6 +10,7 @@ import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
import { formatHostForUrl, isWildcardHost } from "@t3tools/shared/hostClassification";
import packageJson from "../package.json" with { type: "json" };
import type * as ServerConfig from "./config.ts";
+import * as ProcessRunner from "./processRunner.ts";
export const PersistedServerRuntimeState = Schema.Struct({
version: Schema.Literal(1),
@@ -139,6 +142,37 @@ export const isProcessAlive = (pid: number): boolean => {
}
};
+// Whether the process at the recorded PID started before the record was written; None when unknown.
+export const recordedProcessStartMatches = Effect.fn(
+ "serverRuntimeState.recordedProcessStartMatches",
+)(function* (state: PersistedServerRuntimeState) {
+ const recordedAt = Date.parse(state.startedAt);
+ if (!Number.isFinite(recordedAt)) return Option.none();
+ const windows = (yield* HostProcess.Platform) === "win32";
+ const runner = yield* ProcessRunner.ProcessRunner;
+ const result = yield* runner
+ .run({
+ command: windows ? "powershell.exe" : "ps",
+ args: windows
+ ? [
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ `(Get-Process -Id ${state.pid} -ErrorAction Stop).StartTime.ToUniversalTime().ToString('o')`,
+ ]
+ : ["-p", String(state.pid), "-o", "lstart="],
+ env: { LC_ALL: "C", TZ: "UTC" },
+ timeout: Duration.seconds(2),
+ maxOutputBytes: 16_384,
+ })
+ .pipe(Effect.option);
+ if (Option.isNone(result) || result.value.code !== 0) return Option.none();
+ const output = result.value.stdout.trim();
+ const startedAt = Date.parse(windows ? output : `${output} UTC`);
+ // ps reports whole seconds.
+ return Number.isFinite(startedAt) ? Option.some(startedAt <= recordedAt + 1_000) : Option.none();
+});
+
export const readPersistedServerRuntimeState = Effect.fn(
"serverRuntimeState.readPersistedServerRuntimeState",
)(