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, 04:45 UTC
feat(server): links between environments renew while they are used (#39399)
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Julius Marminge committed
Nov 19, 2026 at 18:00 UTC
f6d941fa4fa41741a881b8f646c6737d845ea91c
15 files changed
+373
-26
apps/server/src/auth/EnvironmentAuth.test.ts
+62
@@ -529,6 +529,68 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))(
529
}).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))),
530
);
531
532
+ it.effect("renews a peer link's session while it is used, and no other MCP client's", () =>
533
+ Effect.gen(function* () {
534
+ const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
535
+ const day = 24 * 60 * 60 * 1000;
536
+ const issue = (peerLink: boolean) =>
537
+ serverAuth.issueMcpClientSession({
538
+ label: peerLink ? "T3 Code · A" : "ChatGPT",
539
+ access: "auto",
540
+ peerLink,
541
+ client: requestMetadata,
542
+ });
543
+ const use = (session: { readonly token: string }) =>
544
+ serverAuth.authenticateMcpClient(makeBearerRequest(session.token)).pipe(
545
+ Effect.map((client) => client.linkExpiresAt?.epochMilliseconds ?? null),
546
+ Effect.catchTags({
547
+ ServerAuthInvalidCredentialError: () => Effect.succeed("refused" as const),
548
+ }),
549
+ );
550
+ const listedExpiry = (session: { readonly sessionId: string }) =>
551
+ serverAuth
552
+ .listSessions()
553
+ .pipe(
554
+ Effect.map(
555
+ (sessions) =>
556
+ sessions.find((listed) => listed.sessionId === session.sessionId)?.expiresAt
557
+ .epochMilliseconds,
558
+ ),
559
+ );
560
+ const issuedAt = (yield* DateTime.now).epochMilliseconds;
561
+ const used = yield* issue(true);
562
+ const idle = yield* issue(true);
563
+ const revoked = yield* issue(true);
564
+ const outside = yield* issue(false);
565
+
566
+ // Within a day of its full lifetime, a call leaves the session row alone.
567
+ yield* TestClock.adjust("12 hours");
568
+ expect(yield* use(used)).toBe(issuedAt + 30 * day);
569
+ expect(yield* listedExpiry(used)).toBe(issuedAt + 30 * day);
570
+
571
+ yield* TestClock.adjust("468 hours");
572
+ expect(yield* use(used)).toBe(issuedAt + 50 * day);
573
+ expect(yield* listedExpiry(used)).toBe(issuedAt + 50 * day);
574
+ expect(yield* use(outside)).toBeNull();
575
+ expect(yield* listedExpiry(outside)).toBe(issuedAt + 30 * day);
576
+ expect(yield* serverAuth.revokeSession(revoked.sessionId)).toBe(true);
577
+ expect(yield* use(revoked)).toBe("refused");
578
+
579
+ // Day 40: past the token's own 30 days, so only the renewal keeps the used link.
580
+ yield* TestClock.adjust("20 days");
581
+ expect(yield* use(used)).toBe(issuedAt + 70 * day);
582
+ expect(yield* use(idle)).toBe("refused");
583
+ expect(yield* use(outside)).toBe("refused");
584
+ expect(yield* use(revoked)).toBe("refused");
585
+ expect(yield* listedExpiry(idle)).toBeUndefined();
586
+ expect(yield* listedExpiry(revoked)).toBeUndefined();
587
+
588
+ // Renewed links still end 30 days after their last use.
589
+ yield* TestClock.adjust("30 days");
590
+ expect(yield* use(used)).toBe("refused");
591
+ }).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))),
592
+ );
593
+
594
it.effect("preserves pairing grants after rejecting scopes they do not grant", () =>
595
Effect.gen(function* () {
596
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
apps/server/src/auth/EnvironmentAuth.ts
+50
-15
@@ -85,6 +85,9 @@ export interface IssuedBearerSession {
85
// MCP client tokens are restricted to /mcp; HTTP API and WebSocket RPC would bypass their access cap.
86
const MCP_CLIENT_SUBJECT = "mcp-client";
87
const MCP_CLIENT_SESSION_TTL = Duration.days(30);
88
+// A peer link's session moves back out to its full lifetime when a call finds it this far
89
+// short, so a used link never expires and a busy one writes at most once per step.
90
+const PEER_LINK_RENEWAL_STEP = Duration.days(1);
91
92
// A device pairing with its DPoP key renews the session itself, so the token can be short and
93
// the device stays signed in while used. One idle for the whole window pairs again.
@@ -98,6 +101,8 @@ export interface McpClientSession {
101
readonly access: AuthMcpClientAccess;
102
/** Another T3 Code environment's link, whose work here stays within it. */
103
readonly peerLink: boolean;
104
+ /** When a peer link's session ends unless it is used again; the linking side keeps this. */
105
+ readonly linkExpiresAt?: DateTime.Utc;
106
}
107
108
export interface AuthenticatedSession {
@@ -1577,26 +1582,56 @@ export const make = Effect.gen(function* () {
1582
return yield* authenticateRequest(request);
1583
});
1584
1585
+ /** The expiry of a verified peer link session, moved out when this use finds it a step short. */
1586
+ const renewPeerLinkSession = Effect.fnUntraced(function* (
1587
+ sessionId: AuthSessionId,
1588
+ expiresAt: DateTime.DateTime,
1589
+ ) {
1590
+ const now = yield* DateTime.now;
1591
+ const renewed = DateTime.add(now, {
1592
+ milliseconds: Duration.toMillis(MCP_CLIENT_SESSION_TTL),
1593
+ });
1594
+ if (DateTime.distance(expiresAt, renewed).pipe(Duration.isLessThan(PEER_LINK_RENEWAL_STEP))) {
1595
+ return DateTime.toUtc(expiresAt);
1596
+ }
1597
+ const current = yield* sessions
1598
+ .extend(sessionId, renewed, PEER_LINK_RENEWAL_STEP)
1599
+ .pipe(mapSessionVerificationErrors);
1600
+ // A revoke can land between the verification and the update.
1601
+ if (Option.isNone(current)) {
1602
+ return yield* new ServerAuthInvalidCredentialError({
1603
+ diagnostic: "The peer link session ended before it could be renewed.",
1604
+ });
1605
+ }
1606
+ return current.value;
1607
+ });
1608
+
1609
const authenticateMcpClient: EnvironmentAuth["Service"]["authenticateMcpClient"] = (request) => {
1610
const token = parseBearerToken(request);
1611
if (token === null) return Effect.fail(new ServerAuthMissingCredentialError({}));
1612
return sessions.verify(token).pipe(
1613
mapSessionVerificationErrors,
1585
- Effect.flatMap((session) =>
1586
- session.subject === MCP_CLIENT_SUBJECT && session.method === "bearer-access-token"
1587
- ? Effect.succeed({
1588
- sessionId: session.sessionId,
1589
- label: session.client.label ?? "MCP client",
1590
- access: session.scopes.includes(AuthOrchestrationOperateScope)
1591
- ? (session.runtimeModeCeiling ?? "approval-required")
1592
- : "read-only",
1593
- peerLink: session.peerLink === true,
1594
- } satisfies McpClientSession)
1595
- : Effect.fail(
1596
- new ServerAuthInvalidCredentialError({
1597
- diagnostic: "Only MCP client sessions are accepted here.",
1598
- }),
1599
- ),
1614
+ Effect.flatMap(
1615
+ Effect.fnUntraced(function* (session) {
1616
+ if (session.subject !== MCP_CLIENT_SUBJECT || session.method !== "bearer-access-token") {
1617
+ return yield* new ServerAuthInvalidCredentialError({
1618
+ diagnostic: "Only MCP client sessions are accepted here.",
1619
+ });
1620
+ }
1621
+ const client = {
1622
+ sessionId: session.sessionId,
1623
+ label: session.client.label ?? "MCP client",
1624
+ access: session.scopes.includes(AuthOrchestrationOperateScope)
1625
+ ? (session.runtimeModeCeiling ?? "approval-required")
1626
+ : "read-only",
1627
+ peerLink: session.peerLink === true,
1628
+ } satisfies McpClientSession;
1629
+ if (session.peerLink !== true || session.expiresAt === undefined) return client;
1630
+ return {
1631
+ ...client,
1632
+ linkExpiresAt: yield* renewPeerLinkSession(session.sessionId, session.expiresAt),
1633
+ } satisfies McpClientSession;
1634
+ }),
1635
),
1636
Effect.withSpan("EnvironmentAuth.authenticateMcpClient"),
1637
);
apps/server/src/auth/McpOAuth.ts
+1
@@ -631,6 +631,7 @@ export const layerMcpClientAuthenticator = Layer.effect(
631
label: client.label,
632
access: client.access,
633
linked: client.peerLink,
634
+ linkExpiresAt: client.linkExpiresAt,
635
...(client.peerLink ? {} : { hostedAppUrl }),
636
},
637
capabilities: new Set<McpInvocationContext.McpCapability>([
apps/server/src/auth/SessionStore.test.ts
+46
@@ -2,6 +2,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2
import * as NodeServices from "@effect/platform-node/NodeServices";
3
import { EnvironmentId } from "@t3tools/contracts";
4
import { expect, it } from "@effect/vitest";
5
+import * as DateTime from "effect/DateTime";
6
import * as Duration from "effect/Duration";
7
import * as Effect from "effect/Effect";
8
import * as Fiber from "effect/Fiber";
@@ -573,6 +574,51 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("SessionStore.lay
574
}).pipe(Effect.provide(Layer.merge(layerSessionStore(), TestClock.layer()))),
575
);
576
577
+ it.effect("extends a session once per step and refuses one that has ended", () =>
578
+ Effect.gen(function* () {
579
+ const sessions = yield* SessionStore.SessionStore;
580
+ const step = Duration.days(1);
581
+ const issued = yield* sessions.issue({ subject: "owner" });
582
+ const idle = yield* sessions.issue({ subject: "owner" });
583
+ const millis = (expiresAt: Option.Option<DateTime.Utc>) =>
584
+ Option.getOrNull(Option.map(expiresAt, (value) => value.epochMilliseconds));
585
+ const stored = sessions
586
+ .listActive()
587
+ .pipe(
588
+ Effect.map(
589
+ (active) =>
590
+ active.find((entry) => entry.sessionId === issued.sessionId)?.expiresAt
591
+ .epochMilliseconds,
592
+ ),
593
+ );
594
+
595
+ // Less than a step short: the row keeps its expiry.
596
+ const near = DateTime.toUtc(DateTime.add(issued.expiresAt, { hours: 12 }));
597
+ expect(millis(yield* sessions.extend(issued.sessionId, near, step))).toBe(
598
+ issued.expiresAt.epochMilliseconds,
599
+ );
600
+ expect(yield* stored).toBe(issued.expiresAt.epochMilliseconds);
601
+
602
+ const renewed = DateTime.toUtc(DateTime.add(issued.expiresAt, { days: 20 }));
603
+ expect(millis(yield* sessions.extend(issued.sessionId, renewed, step))).toBe(
604
+ renewed.epochMilliseconds,
605
+ );
606
+ // A second use that read the old expiry finds the row renewed and takes its deadline.
607
+ const overlapping = DateTime.add(renewed, { minutes: 1 });
608
+ expect(millis(yield* sessions.extend(issued.sessionId, overlapping, step))).toBe(
609
+ renewed.epochMilliseconds,
610
+ );
611
+ expect(yield* stored).toBe(renewed.epochMilliseconds);
612
+
613
+ yield* sessions.revoke(issued.sessionId);
614
+ expect(millis(yield* sessions.extend(issued.sessionId, overlapping, step))).toBeNull();
615
+
616
+ yield* TestClock.setTime(idle.expiresAt.epochMilliseconds);
617
+ const afterExpiry = DateTime.toUtc(DateTime.add(idle.expiresAt, { days: 30 }));
618
+ expect(millis(yield* sessions.extend(idle.sessionId, afterExpiry, step))).toBeNull();
619
+ }).pipe(Effect.provide(Layer.merge(layerSessionStore(), TestClock.layer()))),
620
+ );
621
+
622
it.effect("lists active sessions, tracks connectivity, and revokes other sessions", () =>
623
Effect.gen(function* () {
624
const sessions = yield* SessionStore.SessionStore;
apps/server/src/auth/SessionStore.ts
+55
-2
@@ -434,6 +434,15 @@ export class SessionStore extends Context.Service<
434
SessionCredentialError | ServerAuthInvalidCredentialError | ServerAuthInternalError
435
>;
436
readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;
437
+ /**
438
+ * Moves a live session's expiry to `expiresAt` unless it is already within `step` of it, and
439
+ * returns the expiry it now has. None when it is revoked, expired or missing.
440
+ */
441
+ readonly extend: (
442
+ sessionId: AuthSessionId,
443
+ expiresAt: DateTime.Utc,
444
+ step: Duration.Duration,
445
+ ) => Effect.Effect<Option.Option<DateTime.Utc>, SessionCredentialInternalError>;
446
readonly issueWebSocketToken: (
447
sessionId: AuthSessionId,
448
input?: {
@@ -873,7 +882,10 @@ const make = Effect.gen(function* () {
882
expirationClaim: claims.exp,
883
});
884
}
876
- if (claims.exp <= observedAt.epochMilliseconds) {
885
+ // A peer link's session renews while it is used and its token is never
886
+ // reissued, so the session row holds its deadline, not the token.
887
+ const rowHoldsDeadline = claims.plk === 1;
888
+ if (!rowHoldsDeadline && claims.exp <= observedAt.epochMilliseconds) {
889
return yield* new SessionTokenExpiredError({
890
sessionId: claims.sid,
891
expiresAt: expiresAt.value,
@@ -897,13 +909,23 @@ const make = Effect.gen(function* () {
909
revokedAt: row.value.revokedAt,
910
});
911
}
912
+ if (
913
+ rowHoldsDeadline &&
914
+ row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds
915
+ ) {
916
+ return yield* new SessionTokenExpiredError({
917
+ sessionId: claims.sid,
918
+ expiresAt: row.value.expiresAt,
919
+ observedAt,
920
+ });
921
+ }
922
923
return {
924
sessionId: claims.sid,
925
token,
926
method: claims.method,
927
client: toClientMetadata(row.value.client),
906
- expiresAt: expiresAt.value,
928
+ expiresAt: rowHoldsDeadline ? row.value.expiresAt : expiresAt.value,
929
subject: claims.sub,
930
scopes: row.value.scopes,
931
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
@@ -913,6 +935,36 @@ const make = Effect.gen(function* () {
935
},
936
);
937
938
+ const extend: SessionStore["Service"]["extend"] = Effect.fn("SessionStore.extend")(
939
+ function* (sessionId, expiresAt, step) {
940
+ const now = yield* DateTime.now;
941
+ // The step is checked in the update, so of two uses that read the same expiry one writes.
942
+ const extended = yield* authSessions.extend({
943
+ sessionId,
944
+ expiresAt,
945
+ now,
946
+ onlyIfExpiresBy: DateTime.subtract(expiresAt, { milliseconds: Duration.toMillis(step) }),
947
+ });
948
+ if (!extended) {
949
+ const row = yield* authSessions.getById({ sessionId });
950
+ return Option.filter(
951
+ Option.map(row, (current) => current.expiresAt),
952
+ (current) =>
953
+ Option.exists(row, (session) => session.revokedAt === null) &&
954
+ DateTime.isGreaterThan(current, now),
955
+ );
956
+ }
957
+ const session = yield* loadActiveSession(sessionId);
958
+ if (Option.isSome(session)) yield* emitUpsert(session.value);
959
+ return Option.some(expiresAt);
960
+ },
961
+ (effect, sessionId) =>
962
+ Effect.mapError(
963
+ effect,
964
+ (cause) => new SessionCredentialVerificationError({ sessionId, cause }),
965
+ ),
966
+ );
967
+
968
const renew: SessionStore["Service"]["renew"] = Effect.fn("SessionStore.renew")(
969
function* (token, input) {
970
const [encodedPayload, signature] = token.split(".");
@@ -1291,6 +1343,7 @@ const make = Effect.gen(function* () {
1343
legacyCookieName,
1344
issue,
1345
renew,
1346
+ extend,
1347
verify,
1348
issueWebSocketToken,
1349
verifyWebSocketToken,
apps/server/src/mcp/McpHttpServer.ts
+11
@@ -2,6 +2,7 @@ import * as Cache from "effect/Cache";
2
import * as Cause from "effect/Cause";
3
import * as Clock from "effect/Clock";
4
import * as Context from "effect/Context";
5
+import * as DateTime from "effect/DateTime";
6
import * as Duration from "effect/Duration";
7
import * as SecureRandom from "effect/crypto/SecureRandom";
8
import * as Effect from "effect/Effect";
@@ -346,9 +347,19 @@ const makeMcpAuthMiddleware = Effect.gen(function* () {
347
const admitted = yield* authenticateRequest(request);
348
if (HttpServerResponse.isHttpServerResponse(admitted)) return admitted;
349
if (yield* isUndefinedNotification(request)) return HttpServerResponse.empty({ status: 202 });
350
+ const linkExpiresAt = admitted.client?.linkExpiresAt;
351
return yield* httpEffect.pipe(
352
Effect.provideService(McpInvocationContext.McpInvocationContext, admitted),
353
Effect.map(normalizeMcpHttpResponse),
354
+ Effect.map((response) =>
355
+ linkExpiresAt === undefined
356
+ ? response
357
+ : HttpServerResponse.setHeader(
358
+ response,
359
+ McpInvocationContext.LINK_EXPIRES_AT_HEADER,
360
+ DateTime.formatIso(linkExpiresAt),
361
+ ),
362
+ ),
363
);
364
}) satisfies McpAuthMiddleware;
365
}).pipe(Effect.withSpan("McpHttpServer.makeAuthMiddleware"));
apps/server/src/mcp/McpInvocationContext.ts
+9
@@ -11,6 +11,7 @@ import {
11
type ThreadId,
12
} from "@t3tools/contracts";
13
import * as Context from "effect/Context";
14
+import type * as DateTime from "effect/DateTime";
15
import * as Effect from "effect/Effect";
16
import * as Fiber from "effect/Fiber";
17
import { formatThreadLink, hostedThreadLink } from "@t3tools/shared/threadLinks";
@@ -42,6 +43,8 @@ export interface McpClientCaller {
43
* session as `linkOrigin`, and it changes only that work (`linkOrigin.ts`).
44
*/
45
readonly linked?: boolean | undefined;
46
+ /** When a peer link's session ends unless it is used again, answered as `T3-Link-Expires-At`. */
47
+ readonly linkExpiresAt?: DateTime.Utc | undefined;
48
/**
49
* Narrower modes the client asked for on this request (`T3-Mode-Limit`):
50
* another environment passing on the limits of the agent it calls for.
@@ -61,6 +64,12 @@ export interface McpClientCaller {
64
*/
65
export const MODE_LIMIT_HEADER = "t3-mode-limit";
66
67
+/**
68
+ * `T3-Link-Expires-At: <ISO time>` answers a peer link's request with when its
69
+ * session now ends. Using a link renews it, so the linking side keeps this.
70
+ */
71
+export const LINK_EXPIRES_AT_HEADER = "t3-link-expires-at";
72
+
73
/**
74
* `T3-Sender-Thread: <environmentId>/<threadId>/<title>`, each URI-encoded: the
75
* thread another environment makes a request for, so what it sends here can name
apps/server/src/peer/PeerLinks.test.ts
+12
@@ -6,6 +6,7 @@ import { NodeHttpServer } from "@effect/platform-node";
6
import { type ExecutionEnvironmentDescriptor, OrchestratorMcpFailure } from "@t3tools/contracts";
7
import { expect, it } from "@effect/vitest";
8
import * as Context from "effect/Context";
9
+import * as DateTime from "effect/DateTime";
10
import * as Deferred from "effect/Deferred";
11
import * as Duration from "effect/Duration";
12
import * as Effect from "effect/Effect";
@@ -575,6 +576,17 @@ it.effect("reads one stored link without asking the peer", () =>
576
expect(Option.map(stored, (link) => link.label)).toEqual(Option.some("Box"));
577
expect(Option.isNone(yield* a.links.get(laptop.environmentId))).toBe(true);
578
expect(yield* Ref.get(b.probes)).toBe(0);
579
+
580
+ // An older answer that lands after a newer one never moves the expiry back.
581
+ const expiresAt = Option.getOrThrow(stored).expiresAt;
582
+ const later = DateTime.add(expiresAt, { days: 20 });
583
+ yield* a.links.recordExpiry(box.environmentId, later);
584
+ yield* a.links.recordExpiry(box.environmentId, DateTime.add(expiresAt, { days: 10 }));
585
+ expect(
586
+ Option.map(yield* a.links.get(box.environmentId), (link) =>
587
+ DateTime.formatIso(link.expiresAt),
588
+ ),
589
+ ).toEqual(Option.some(DateTime.formatIso(later)));
590
}),
591
).pipe(Effect.provide(NodeHttpServer.layerTest)),
592
);
apps/server/src/peer/PeerLinks.ts
+12
@@ -112,6 +112,11 @@ export class PeerLinks extends Context.Service<
112
environmentId: EnvironmentId,
113
outcome: { readonly error: string | null },
114
) => Effect.Effect<void>;
115
+ /** Records a later end the peer gives the link's session: using a link renews it there. */
116
+ readonly recordExpiry: (
117
+ environmentId: EnvironmentId,
118
+ expiresAt: DateTime.Utc,
119
+ ) => Effect.Effect<void>;
120
}
121
>()("t3/peer/PeerLinks") {}
122
@@ -712,6 +717,12 @@ const make = Effect.gen(function* () {
717
Effect.ignoreCause({ log: true }),
718
);
719
720
+ const recordExpiry: PeerLinks["Service"]["recordExpiry"] = (environmentId, expiresAt) =>
721
+ sql`
722
+ UPDATE peer_environment_links SET expires_at = ${DateTime.formatIso(expiresAt)}
723
+ WHERE environment_id = ${environmentId} AND expires_at < ${DateTime.formatIso(expiresAt)}
724
+ `.pipe(Effect.asVoid, Effect.ignoreCause({ log: true }));
725
+
726
return PeerLinks.of({
727
enabled,
728
link,
@@ -720,6 +731,7 @@ const make = Effect.gen(function* () {
731
unlink,
732
resolve,
733
recordOutcome,
734
+ recordExpiry,
735
});
736
});
737
apps/server/src/peer/PeerMcpClient.test.ts
+63
-1
@@ -13,6 +13,7 @@ import * as Duration from "effect/Duration";
13
import * as Effect from "effect/Effect";
14
import * as Fiber from "effect/Fiber";
15
import * as Layer from "effect/Layer";
16
+import * as Option from "effect/Option";
17
import * as Queue from "effect/Queue";
18
import * as Ref from "effect/Ref";
19
import * as Schema from "effect/Schema";
@@ -242,11 +243,65 @@ it.effect("keeps a link healthy when the peer refuses a call", () =>
243
).pipe(Effect.provide(NodeHttpServer.layerTest)),
244
);
245
246
+it.effect("keeps the expiry the peer answers with, so a used link outlives its first 30 days", () =>
247
+ Effect.scoped(
248
+ Effect.gen(function* () {
249
+ const handlers = McpToolAccess.toLayer(toolkit, {
250
+ probe: McpToolAccess.reads(() => Effect.succeed({ modes: "" })),
251
+ hold: McpToolAccess.reads(() => Effect.succeed({ modes: "" })),
252
+ refuse: McpToolAccess.reads(() => Effect.fail(refusal)),
253
+ });
254
+ const box = descriptorOf("environment-box", "Box");
255
+ const b = yield* servePeer(box, McpHttpServer.toolkitRegistration(toolkit, handlers));
256
+ const context = yield* Layer.build(
257
+ layerLinkingEnvironment(descriptorOf("environment-a", "A")),
258
+ );
259
+ const links = Context.get(context, PeerLinks.PeerLinks);
260
+ const client = Context.get(context, PeerMcpClient.PeerMcpClient);
261
+ const linked = yield* linkTo(links, b);
262
+ const day = 24 * 60 * 60 * 1000;
263
+ const call = client.call({
264
+ environmentId: box.environmentId,
265
+ tool: "probe",
266
+ arguments: {},
267
+ limits: { runtimeMode: "full-access", interactionMode: "default" },
268
+ success: Result,
269
+ });
270
+ const storedExpiry = links
271
+ .get(box.environmentId)
272
+ .pipe(
273
+ Effect.map((link) => (Option.isSome(link) ? link.value.expiresAt.epochMilliseconds : 0)),
274
+ );
275
+ const expiryThere = b.linkedSessions.pipe(
276
+ Effect.map((sessions) => sessions[0]?.expiresAt.epochMilliseconds),
277
+ );
278
+ const linkedAt = linked.linkedAt.epochMilliseconds;
279
+ expect(yield* storedExpiry).toBe(linkedAt + 30 * day);
280
+
281
+ yield* TestClock.adjust("20 days");
282
+ yield* call;
283
+ expect(yield* expiryThere).toBe(linkedAt + 50 * day);
284
+ expect(yield* storedExpiry).toBe(linkedAt + 50 * day);
285
+
286
+ yield* TestClock.adjust("20 days");
287
+ expect(yield* call).toEqual({ modes: "" });
288
+ expect(yield* storedExpiry).toBe(linkedAt + 70 * day);
289
+
290
+ // Idle for the whole window, the link expires on both sides.
291
+ yield* TestClock.adjust("30 days");
292
+ expect((yield* call.pipe(Effect.flip)).code).toBe("capability_denied");
293
+ expect((yield* links.list)[0]?.status).toBe("expired");
294
+ expect(yield* b.linkedSessions).toEqual([]);
295
+ }),
296
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
297
+);
298
+
299
it.effect("renews a missing peer session once and reuses its replacement", () =>
300
Effect.gen(function* () {
301
const sessionHeaders: Array<string | undefined> = [];
302
const statuses = [200, 202, 404, 200, 202, 200, 200, 200];
303
const outcomes: Array<string | null> = [];
304
+ const expiries: Array<string> = [];
305
const http = HttpClient.make((request) =>
306
Effect.sync(() => {
307
const index = sessionHeaders.length;
@@ -269,7 +324,10 @@ it.effect("renews a missing peer session once and reuses its replacement", () =>
324
status,
325
headers:
326
index === 0
272
- ? { "mcp-session-id": "old" }
327
+ ? {
328
+ "mcp-session-id": "old",
329
+ [McpInvocationContext.LINK_EXPIRES_AT_HEADER]: "1970-01-02T00:00:00.000Z",
330
+ }
331
: index === 3
332
? { "mcp-session-id": "renewed" }
333
: {},
@@ -301,6 +359,8 @@ it.effect("renews a missing peer session once and reuses its replacement", () =>
359
token: "fixture",
360
}),
361
recordOutcome: (_, outcome) => Effect.sync(() => outcomes.push(outcome.error)),
362
+ recordExpiry: (_, expiresAt) =>
363
+ Effect.sync(() => expiries.push(DateTime.formatIso(expiresAt))),
364
}),
365
),
366
),
@@ -329,6 +389,8 @@ it.effect("renews a missing peer session once and reuses its replacement", () =>
389
})
390
.pipe(Effect.flip);
391
expect(outcomes).toEqual([null, null, empty.message]);
392
+ // Only the handshake answered with an expiry, and it is kept.
393
+ expect(expiries).toEqual(["1970-01-02T00:00:00.000Z"]);
394
expect(sessionHeaders).toEqual([
395
undefined,
396
"old",
apps/server/src/peer/PeerMcpClient.ts
+30
-4
@@ -7,8 +7,10 @@ import {
7
type RuntimeMode,
8
} from "@t3tools/contracts";
9
import * as Context from "effect/Context";
10
+import * as DateTime from "effect/DateTime";
11
import * as Effect from "effect/Effect";
12
import * as Layer from "effect/Layer";
13
+import * as Option from "effect/Option";
14
import * as Ref from "effect/Ref";
15
import * as Result from "effect/Result";
16
import * as Schema from "effect/Schema";
@@ -124,8 +126,30 @@ const make = Effect.gen(function* () {
126
),
127
);
128
129
+ // A peer that renews a used link says when it now ends; one that does not sends nothing.
130
+ const recordLinkExpiry = (
131
+ link: PeerLinks.ResolvedPeerLink["link"],
132
+ headers: Readonly<Record<string, string>>,
133
+ ) =>
134
+ Option.match(
135
+ Option.filter(
136
+ Option.flatMap(
137
+ Option.fromNullishOr(headers[McpInvocationContext.LINK_EXPIRES_AT_HEADER]),
138
+ DateTime.make,
139
+ ),
140
+ (expiresAt) => !DateTime.Equivalence(expiresAt, link.expiresAt),
141
+ ),
142
+ {
143
+ onNone: () => Effect.void,
144
+ onSome: (expiresAt) => links.recordExpiry(link.environmentId, expiresAt),
145
+ },
146
+ );
147
+
148
const openSession = Effect.fn("PeerMcpClient.openSession")(
128
- function* (url: string, token: string, limitHeader: Record<string, string>) {
149
+ function* (
150
+ { link, url, token }: PeerLinks.ResolvedPeerLink,
151
+ limitHeader: Record<string, string>,
152
+ ) {
153
const initialized = yield* post(
154
url,
155
token,
@@ -152,6 +176,7 @@ const make = Effect.gen(function* () {
176
: `The linked environment refused to start an MCP session (HTTP ${initialized.status}).`,
177
});
178
}
179
+ yield* recordLinkExpiry(link, initialized.headers);
180
yield* post(
181
url,
182
token,
@@ -161,7 +186,7 @@ const make = Effect.gen(function* () {
186
return sessionId;
187
},
188
// Only the handshake is bounded: a forwarded tool call may wait for minutes.
164
- (effect, url) => Effect.timeout(effect, PeerLinks.probeTimeout(url)),
189
+ (effect, { url }) => Effect.timeout(effect, PeerLinks.probeTimeout(url)),
190
);
191
192
const call: PeerMcpClient["Service"]["call"] = Effect.fn("PeerMcpClient.call")(
@@ -205,14 +230,14 @@ const make = Effect.gen(function* () {
230
},
231
);
232
const existing = (yield* Ref.get(sessions)).get(sessionKey);
208
- const sessionId = existing ?? (yield* openSession(resolved.url, resolved.token, limitHeader));
233
+ const sessionId = existing ?? (yield* openSession(resolved, limitHeader));
234
// The initialized session outlives a tool request, including a long wait or cancellation.
235
if (existing === undefined) {
236
yield* Ref.update(sessions, (current) => new Map(current).set(sessionKey, sessionId));
237
}
238
let response = yield* callOnce(sessionId);
239
if (response.status === 404) {
215
- const renewed = yield* openSession(resolved.url, resolved.token, limitHeader);
240
+ const renewed = yield* openSession(resolved, limitHeader);
241
yield* Ref.update(sessions, (current) => new Map(current).set(sessionKey, renewed));
242
response = yield* callOnce(renewed);
243
}
@@ -230,6 +255,7 @@ const make = Effect.gen(function* () {
255
message: `The linked environment answered HTTP ${response.status}.`,
256
});
257
}
258
+ yield* recordLinkExpiry(resolved.link, response.headers);
259
const body = yield* decodeToolCallResponse(
260
responseJson(response.headers["content-type"], yield* response.text),
261
).pipe(
apps/server/src/persistence/AuthSessions.ts
+5
-2
@@ -85,6 +85,8 @@ export const ExtendAuthSessionInput = Schema.Struct({
85
sessionId: AuthSessionId,
86
expiresAt: Schema.DateTimeUtcFromString,
87
now: Schema.DateTimeUtcFromString,
88
+ /** When set, only a row whose expiry is at or before this is moved. */
89
+ onlyIfExpiresBy: Schema.optional(Schema.DateTimeUtcFromString),
90
});
91
export type ExtendAuthSessionInput = typeof ExtendAuthSessionInput.Type;
92
@@ -127,7 +129,7 @@ export class AuthSessionRepository extends Context.Service<
129
readonly revoke: (
130
input: RevokeAuthSessionInput,
131
) => Effect.Effect<boolean, AuthSessionRepositoryError>;
130
- /** Moves a live session's expiry; false when it is revoked, expired or missing. */
132
+ /** Moves a live session's expiry; false when it is revoked, expired, missing or past `onlyIfExpiresBy`. */
133
readonly extend: (
134
input: ExtendAuthSessionInput,
135
) => Effect.Effect<boolean, AuthSessionRepositoryError>;
@@ -363,13 +365,14 @@ export const make = Effect.gen(function* () {
365
const extendSessionRows = SqlSchema.findAll({
366
Request: ExtendAuthSessionInput,
367
Result: Schema.Struct({ sessionId: AuthSessionId }),
366
- execute: ({ sessionId, expiresAt, now }) =>
368
+ execute: ({ sessionId, expiresAt, now, onlyIfExpiresBy }) =>
369
sql`
370
UPDATE auth_sessions
371
SET expires_at = ${expiresAt}
372
WHERE session_id = ${sessionId}
373
AND revoked_at IS NULL
374
AND expires_at > ${now}
375
+ AND (${onlyIfExpiresBy ?? null} IS NULL OR expires_at <= ${onlyIfExpiresBy ?? null})
376
RETURNING session_id AS "sessionId"
377
`,
378
});
docs/internals/environment-auth.md
+9
-1
@@ -34,9 +34,17 @@ fresh token for the same session. The session itself must still be unexpired
34
and unrevoked, so a device idle past the window pairs again. Renewal stays in place rather than issuing a
35
successor, so live sockets keep their session, Sharing & access shows one row
36
per device for its whole renewal window, and one revoke ends it. T3 Connect,
37
-CLI, desktop and peer sessions never renew, so unlinking Connect or rotating
37
+CLI and desktop sessions never renew, so unlinking Connect or rotating
38
their credential still cuts a device off.
39
40
+A [peer link](remote.md#peer-links)'s session renews on use instead: its
41
+bearer token is never reissued, so the session row alone holds its deadline and
42
+the token's own expiry is ignored. Authenticating a call from it moves the
43
+row 30 days out, at most once a day so a busy link does not write on every
44
+call. Only an unexpired, unrevoked row moves, so an idle link still ends after
45
+30 days and a revoke is final. Other MCP clients keep the fixed 30 days their
46
+token carries.
47
+
48
### Guest links are not sessions
49
50
A [guest link](../user/guest-links.md) gives one browser read access to one
docs/internals/remote.md
+5
@@ -103,6 +103,11 @@ Unlinking on the linking side only forgets the token.
103
[`linkRequestTarget`](../../packages/client-runtime/src/linkRequest.ts) names
104
a machine for it only when the client already reaches exactly one machine
105
there. An address alone never moves an unexpired link to another address.
106
+- **The receiving side owns a link's expiry.** It renews the session when the
107
+ link is used and answers each call with `T3-Link-Expires-At`; the linking
108
+ side stores that and never extends a link on its own. A receiving side that
109
+ predates renewal sends no header, so the link keeps its original 30 days on
110
+ both sides.
111
- **All callers on one side share the link's single session on the other**,
112
so idempotency keys are hashed with the caller's namespace before they
113
leave. Without that, two agents reusing a key would collide on the far side.
docs/user/remote-access.md
+3
-1
@@ -451,7 +451,9 @@ an address you trust: the code is sent there.
451
- The link shows up in that machine's **Settings → Sharing & access** like any
452
outside agent. Revoke it there to end it. **Forget** on this machine only
453
removes it here.
454
-- Links last 30 days. Link again with a new pairing code to renew one.
454
+- A link stays valid while agents use it. One unused for 30 days expires, as
455
+ does one to a machine on an older T3 Code after 30 days; link again with a
456
+ new pairing code.
457
458
An agent can also hand a task to a linked machine with `delegate_task`: it runs
459
there as an ordinary thread, in the project with the same repository (or the