@devries-cameron20 / t3code Mirror · read-only / commits / 76b3e3390e
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 21:00 UTC

fix(server): MCP tokens still expire after the clock steps back (#34532)

Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com>

maria committed Nov 12, 2026 at 00:26 UTC 76b3e3390e2fdb824a3afbc7e6b5300cfec7a6b3
2 files changed +76 -13
apps/server/src/mcp/McpSessionRegistry.test.ts
+38 -2
@@ -6,6 +6,7 @@ import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"
6 import * as Effect from "effect/Effect";
7 import { HttpServer } from "effect/http";
8 import * as NetAddress from "effect/net/NetAddress";
9 +import * as TestClock from "effect/testing/TestClock";
10
11 import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
12 import * as McpSessionRegistry from "./McpSessionRegistry.ts";
@@ -22,10 +23,11 @@ const fakeEnvironment = ServerEnvironment.ServerEnvironment.of({
23 getDescriptor: Effect.die("unused"),
24 });
25
25 -const makeRegistry = (now: () => number, httpServer = fakeHttpServer) =>
26 +// Without `now`, the registry reads the Effect Clock (TestClock in these tests).
27 +const makeRegistry = (now: (() => number) | undefined, httpServer = fakeHttpServer) =>
28 McpSessionRegistry.__testing
29 .make({
28 - now,
30 + ...(now ? { now } : {}),
31 livenessWindowMs: 100,
32 })
33 .pipe(
@@ -139,6 +141,40 @@ it.effect("expires credentials once their session stops showing signs of life",
141 const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, "");
142 timestamp += 101;
143 expect(yield* registry.resolve(token)).toBeUndefined();
144 + // Once a request found it expired, clocks moving back don't bring it back; a provider turn does.
145 + timestamp = 1_000;
146 + expect(yield* registry.resolve(token)).toBeUndefined();
147 + yield* registry.touch(ThreadId.make("thread-2"));
148 + expect((yield* registry.resolve(token))?.thread.threadId).toBe("thread-2");
149 + }),
150 +);
151 +
152 +it.effect("a backward wall clock step neither extends nor revives credentials", () =>
153 + Effect.gen(function* () {
154 + const registry = yield* makeRegistry(undefined);
155 + const issueToken = (threadId: string) =>
156 + registry
157 + .issue({
158 + threadId: ThreadId.make(threadId),
159 + providerInstanceId: ProviderInstanceId.make("codex"),
160 + capabilities: new Set(["preview"]),
161 + })
162 + .pipe(Effect.map((issued) => issued.config.authorizationHeader.replace(/^Bearer\s+/, "")));
163 +
164 + yield* TestClock.setTime(10_000);
165 + const extended = yield* issueToken("thread-extended");
166 + // setTime backwards moves wall time only; adjust moves both clocks.
167 + yield* TestClock.setTime(1_000);
168 + yield* TestClock.adjust(101);
169 + expect(yield* registry.resolve(extended)).toBeUndefined();
170 +
171 + const revived = yield* issueToken("thread-revived");
172 + yield* TestClock.adjust(101);
173 + expect(yield* registry.resolve(revived)).toBeUndefined();
174 + const active = yield* issueToken("thread-active");
175 + yield* TestClock.setTime(0);
176 + expect(yield* registry.resolve(revived)).toBeUndefined();
177 + expect((yield* registry.resolve(active))?.thread.threadId).toBe("thread-active");
178 }),
179 );
180
apps/server/src/mcp/McpSessionRegistry.ts
+38 -11
@@ -42,10 +42,17 @@ export class McpSessionRegistry extends Context.Service<
42 McpSessionRegistryShape
43 >()("t3/mcp/McpSessionRegistry") {}
44
45 +interface AliveMark {
46 + readonly wallMs: number;
47 + readonly monotonicMs: number;
48 +}
49 +
50 interface CredentialRecord {
51 readonly tokenHash: string;
52 readonly scope: McpInvocationContext.McpThreadInvocationScope;
48 - readonly lastAliveAt: number;
53 + readonly lastAlive: AliveMark;
54 + /** Set when a request finds the token idle; only `touch` clears it, whatever the clocks do. */
55 + readonly expired: boolean;
56 }
57
58 interface RegistryState {
@@ -54,6 +61,7 @@ interface RegistryState {
61
62 export interface McpSessionRegistryOptions {
63 readonly livenessWindowMs?: number;
64 + /** Drives both the wall and monotonic readings. */
65 readonly now?: () => number;
66 }
67
@@ -69,6 +77,11 @@ const bytesToHex = (bytes: Uint8Array): string =>
77
78 const tokenFromBytes = (bytes: Uint8Array): string => Buffer.from(bytes).toString("base64url");
79
80 +// The larger elapsed reading wins: stepping the wall clock back cannot extend a token,
81 +// and wall time that passes while the host sleeps still counts.
82 +const idleMs = (since: AliveMark, now: AliveMark): number =>
83 + Math.max(now.wallMs - since.wallMs, now.monotonicMs - since.monotonicMs);
84 +
85 const getHttpMcpEndpointHost = (address: NetAddress.IpAddress): string =>
86 NetAddress.isUnspecified(address)
87 ? "127.0.0.1"
@@ -83,7 +96,18 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
96 const environmentId = yield* environment.getEnvironmentId;
97 const httpServer = yield* HttpServer.HttpServer;
98 const state = yield* SynchronizedRef.make<RegistryState>({ records: new Map() });
86 - const currentTimeMillis = options.now ? Effect.sync(options.now) : Clock.currentTimeMillis;
99 + const { now } = options;
100 + const currentAliveMark: Effect.Effect<AliveMark> = now
101 + ? Effect.sync(() => {
102 + const timestamp = now();
103 + return { wallMs: timestamp, monotonicMs: timestamp };
104 + })
105 + : Effect.all({
106 + wallMs: Clock.currentTimeMillis,
107 + monotonicMs: Clock.monotonicTimeNanos.pipe(
108 + Effect.map((nanos) => Number(nanos / 1_000_000n)),
109 + ),
110 + });
111 const livenessWindowMs = options.livenessWindowMs ?? DEFAULT_LIVENESS_WINDOW_MS;
112 const endpoint = NetAddress.isInetAddress(httpServer.address)
113 ? `http://${getHttpMcpEndpointHost(httpServer.address.address)}:${httpServer.address.port}/mcp`
@@ -96,7 +120,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
120
121 const issue: McpSessionRegistryShape["issue"] = Effect.fn("McpSessionRegistry.issue")(
122 function* (request) {
99 - const issuedAt = yield* currentTimeMillis;
123 + const issuedAlive = yield* currentAliveMark;
124 const providerSessionId = yield* random.uuidV4();
125 const rawToken = yield* random.randomBytes(32).pipe(Effect.map(tokenFromBytes), Effect.orDie);
126 const tokenHash = yield* hashToken(rawToken);
@@ -117,11 +141,11 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
141 "pull-requests",
142 ...(request.capabilities ?? (browserToolsAvailable ? (["preview"] as const) : [])),
143 ]),
120 - issuedAt,
144 + issuedAt: issuedAlive.wallMs,
145 };
146 yield* SynchronizedRef.update(state, ({ records }) => {
147 const next = new Map(records);
124 - next.set(tokenHash, { tokenHash, scope, lastAliveAt: issuedAt });
148 + next.set(tokenHash, { tokenHash, scope, lastAlive: issuedAlive, expired: false });
149 return { records: next };
150 });
151 return {
@@ -143,14 +167,17 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
167 function* (rawToken) {
168 if (rawToken.length === 0) return undefined;
169 const tokenHash = yield* hashToken(rawToken);
146 - const timestamp = yield* currentTimeMillis;
170 + const alive = yield* currentAliveMark;
171 return yield* SynchronizedRef.modify(state, ({ records }) => {
172 const record = records.get(tokenHash);
149 - if (!record || timestamp - record.lastAliveAt > livenessWindowMs) {
150 - return [undefined, { records }] as const;
173 + if (!record || record.expired) return [undefined, { records }] as const;
174 + if (idleMs(record.lastAlive, alive) > livenessWindowMs) {
175 + const next = new Map(records);
176 + next.set(tokenHash, { ...record, expired: true });
177 + return [undefined, { records: next }] as const;
178 }
179 const next = new Map(records);
153 - next.set(tokenHash, { ...record, lastAliveAt: timestamp });
180 + next.set(tokenHash, { ...record, lastAlive: alive });
181 return [record.scope, { records: next }] as const;
182 });
183 },
@@ -158,12 +185,12 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
185
186 const touch: McpSessionRegistryShape["touch"] = Effect.fn("McpSessionRegistry.touch")(
187 function* (threadId) {
161 - const timestamp = yield* currentTimeMillis;
188 + const alive = yield* currentAliveMark;
189 yield* SynchronizedRef.update(state, ({ records }) => {
190 const next = new Map(records);
191 for (const [tokenHash, record] of records) {
192 if (record.scope.thread.threadId === threadId) {
166 - next.set(tokenHash, { ...record, lastAliveAt: timestamp });
193 + next.set(tokenHash, { ...record, lastAlive: alive, expired: false });
194 }
195 }
196 return { records: next };