@devries-cameron20 / t3code Mirror · read-only / commits / dd512d86c5
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, 07:15 UTC

feat(server): pairing-link sessions renew with the device's DPoP key (#37980)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 18, 2026 at 12:01 UTC dd512d86c5e42c15b04d4a04aa663340aaee603f
10 files changed +422 -48
apps/server/src/auth/EnvironmentAuth.test.ts
+107
@@ -10,6 +10,7 @@ import * as DateTime from "effect/DateTime";
10 import * as Effect from "effect/Effect";
11 import * as Layer from "effect/Layer";
12 import * as Redacted from "effect/Redacted";
13 +import * as TestClock from "effect/testing/TestClock";
14
15 import * as ServerConfig from "../config.ts";
16 import { makeDpopKey } from "./dpop.testkit.ts";
@@ -415,6 +416,112 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))(
416 }).pipe(Effect.provide(layerEnvironmentAuth())),
417 );
418
419 + it.effect("renews a pairing-link DPoP session in place while its device keeps using it", () =>
420 + Effect.gen(function* () {
421 + const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
422 + const sessions = yield* SessionStore.SessionStore;
423 + const admin = yield* serverAuth.issueSession({ label: "Owner" });
424 + const key = makeDpopKey();
425 + const other = makeDpopKey();
426 + const pair = (proofKeyThumbprint?: string) =>
427 + serverAuth
428 + .issuePairingCredential({ scopes: ["orchestration:read"] })
429 + .pipe(
430 + Effect.flatMap((pairing) =>
431 + serverAuth.exchangeBootstrapCredentialForAccessToken(
432 + pairing.credential,
433 + undefined,
434 + requestMetadata,
435 + proofKeyThumbprint ? { proofKeyThumbprint } : undefined,
436 + ),
437 + ),
438 + );
439 + const sessionExpiry = (sessionId: string) =>
440 + serverAuth
441 + .listClientSessions(admin.sessionId)
442 + .pipe(
443 + Effect.map(
444 + (sessions) =>
445 + sessions.find((session) => session.sessionId === sessionId)?.expiresAt
446 + .epochMilliseconds,
447 + ),
448 + );
449 +
450 + const paired = yield* pair(key.thumbprint);
451 + expect(paired.expires_in).toBe(60 * 60);
452 + const { sessionId } = yield* sessions.verify(paired.access_token);
453 + const pairedAt = (yield* DateTime.now).epochMilliseconds;
454 + // Listed for the whole renewal window, so an idle device can still be revoked.
455 + expect(yield* sessionExpiry(sessionId)).toBe(pairedAt + 30 * 24 * 60 * 60 * 1000);
456 +
457 + yield* TestClock.adjust("20 days");
458 + const replay = new EnvironmentAuth.ServerAuthInvalidCredentialError({
459 + dpopFailureReason: "replay",
460 + });
461 + const rejected = yield* serverAuth
462 + .renewAccessToken(paired.access_token, key.thumbprint, Effect.fail(replay))
463 + .pipe(Effect.flip);
464 + expect(rejected).toBe(replay);
465 + expect(yield* sessionExpiry(sessionId)).toBe(pairedAt + 30 * 24 * 60 * 60 * 1000);
466 +
467 + const renewed = yield* serverAuth.renewAccessToken(
468 + paired.access_token,
469 + key.thumbprint,
470 + Effect.void,
471 + );
472 + expect(renewed.scope).toBe("orchestration:read");
473 + const verified = yield* sessions.verify(renewed.access_token);
474 + expect(verified.sessionId).toBe(sessionId);
475 + expect(yield* sessionExpiry(sessionId)).toBe(pairedAt + 50 * 24 * 60 * 60 * 1000);
476 +
477 + const refused = (token: string, thumbprint: string) =>
478 + serverAuth
479 + .renewAccessToken(
480 + token,
481 + thumbprint,
482 + Effect.die("Invalid credentials cannot consume a proof."),
483 + )
484 + .pipe(
485 + Effect.flip,
486 + Effect.map((error) => error._tag),
487 + );
488 + expect(yield* refused(renewed.access_token, other.thumbprint)).toBe(
489 + "ServerAuthInvalidCredentialError",
490 + );
491 + // Bearer and T3 Connect sessions keep their fixed lifetimes, so unlinking still cuts off.
492 + const bearer = yield* pair();
493 + expect(yield* refused(bearer.access_token, key.thumbprint)).toBe(
494 + "ServerAuthInvalidCredentialError",
495 + );
496 + const connect = yield* serverAuth.issueConnectCredential({
497 + proofKeyThumbprint: key.thumbprint,
498 + requireApproval: false,
499 + });
500 + const connected = yield* serverAuth.exchangeBootstrapCredentialForAccessToken(
501 + connect.credential,
502 + undefined,
503 + requestMetadata,
504 + { proofKeyThumbprint: key.thumbprint },
505 + );
506 + expect(yield* refused(connected.access_token, key.thumbprint)).toBe(
507 + "ServerAuthInvalidCredentialError",
508 + );
509 +
510 + // Inside the renewed window, so only the revocation can refuse it.
511 + expect(yield* serverAuth.revokeClientSession(admin.sessionId, sessionId)).toBe(true);
512 + expect(yield* refused(renewed.access_token, key.thumbprint)).toBe(
513 + "ServerAuthInvalidCredentialError",
514 + );
515 +
516 + // Idle past the window, the device pairs again.
517 + const idle = yield* pair(key.thumbprint);
518 + yield* TestClock.adjust("31 days");
519 + expect(yield* refused(idle.access_token, key.thumbprint)).toBe(
520 + "ServerAuthInvalidCredentialError",
521 + );
522 + }).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))),
523 + );
524 +
525 it.effect("preserves pairing grants after rejecting scopes they do not grant", () =>
526 Effect.gen(function* () {
527 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
apps/server/src/auth/EnvironmentAuth.ts
+67 -27
@@ -85,6 +85,12 @@ export interface IssuedBearerSession {
85 const MCP_CLIENT_SUBJECT = "mcp-client";
86 const MCP_CLIENT_SESSION_TTL = Duration.days(30);
87
88 +// A device pairing with its DPoP key renews the session itself, so the token can be short and
89 +// the device stays signed in while used. One idle for the whole window pairs again.
90 +const RENEWABLE_ACCESS_TOKEN_TTL = Duration.hours(1);
91 +const RENEWABLE_SESSION_WINDOW = Duration.days(30);
92 +const PAIRING_LINK_SUBJECT = "one-time-token";
93 +
94 export interface McpClientSession {
95 readonly sessionId: AuthSessionId;
96 readonly label: string;
@@ -514,6 +520,14 @@ export class EnvironmentAuth extends Context.Service<
520 | ServerAuthConnectApprovalPendingError
521 | ServerAuthInternalError
522 >;
523 + readonly renewAccessToken: (
524 + accessToken: string,
525 + proofKeyThumbprint: string,
526 + consumeProof: Effect.Effect<void, ServerAuthInvalidCredentialError | ServerAuthInternalError>,
527 + ) => Effect.Effect<
528 + AuthAccessTokenResult,
529 + ServerAuthInvalidCredentialError | ServerAuthInternalError
530 + >;
531 readonly createPairingLink: (input?: {
532 readonly ttl?: Duration.Duration;
533 readonly label?: string;
@@ -687,16 +701,15 @@ const rejectMcpClientAudience = <S extends { readonly subject: string }>(session
701 ).pipe(Effect.tap(() => Effect.logWarning("Rejected an MCP client session outside /mcp.")))
702 : Effect.succeed(session);
703
704 +const toSessionVerificationError = (cause: SessionStore.SessionCredentialError) =>
705 + SessionStore.isSessionCredentialInvalidError(cause)
706 + ? new ServerAuthInvalidCredentialError({ cause })
707 + : new ServerAuthSessionCredentialValidationError({ cause });
708 +
709 const mapSessionVerificationErrors = <A, R>(
710 effect: Effect.Effect<A, SessionStore.SessionCredentialError, R>,
711 ): Effect.Effect<A, ServerAuthInvalidCredentialError | ServerAuthInternalError, R> =>
693 - effect.pipe(
694 - Effect.mapError((cause) =>
695 - SessionStore.isSessionCredentialInvalidError(cause)
696 - ? new ServerAuthInvalidCredentialError({ cause })
697 - : new ServerAuthSessionCredentialValidationError({ cause }),
698 - ),
699 - );
712 + effect.pipe(Effect.mapError(toSessionVerificationError));
713
714 export function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {
715 const header = request.headers["authorization"];
@@ -1040,6 +1053,43 @@ export const make = Effect.gen(function* () {
1053 // spending its credential and trusting the key would be undone by that exchange.
1054 const connectTrustLock = yield* Semaphore.make(1);
1055
1056 + const toAccessTokenResult = (session: SessionStore.IssuedSession) =>
1057 + DateTime.now.pipe(
1058 + Effect.map(
1059 + (now) =>
1060 + ({
1061 + access_token: session.token,
1062 + issued_token_type: AuthAccessTokenType,
1063 + token_type: session.proofKeyThumbprint ? "DPoP" : "Bearer",
1064 + expires_in: Math.max(
1065 + 0,
1066 + Math.floor((session.expiresAt.epochMilliseconds - now.epochMilliseconds) / 1000),
1067 + ),
1068 + scope: encodeOAuthScope(session.scopes),
1069 + }) satisfies AuthAccessTokenResult,
1070 + ),
1071 + );
1072 +
1073 + const renewAccessToken: EnvironmentAuth["Service"]["renewAccessToken"] = Effect.fn(
1074 + "EnvironmentAuth.renewAccessToken",
1075 + )(function* (accessToken, proofKeyThumbprint, consumeProof) {
1076 + const session = yield* sessions
1077 + .renew(accessToken, {
1078 + proofKeyThumbprint,
1079 + ttl: RENEWABLE_ACCESS_TOKEN_TTL,
1080 + renewalWindow: RENEWABLE_SESSION_WINDOW,
1081 + consumeProof,
1082 + })
1083 + .pipe(
1084 + Effect.mapError((cause) =>
1085 + isServerAuthCredentialError(cause) || isServerAuthInternalError(cause)
1086 + ? cause
1087 + : toSessionVerificationError(cause),
1088 + ),
1089 + );
1090 + return yield* toAccessTokenResult(session);
1091 + });
1092 +
1093 const exchangeBootstrapCredentialForAccessToken: EnvironmentAuth["Service"]["exchangeBootstrapCredentialForAccessToken"] =
1094 (credential, requestedScopes, requestMetadata, input) => {
1095 return resolveBootstrapGrant(credential, {
@@ -1065,6 +1115,12 @@ export const make = Effect.gen(function* () {
1115 if (grantedScopes.length === 0) {
1116 return yield* new ServerAuthScopeNotGrantedError({});
1117 }
1118 + // Only plain pairing links renew. T3 Connect, CLI, desktop and peer sessions keep
1119 + // their own lifetimes, so unlinking Connect or rotating a credential still cuts off.
1120 + const renewable =
1121 + input?.proofKeyThumbprint !== undefined &&
1122 + grant.method === "one-time-token" &&
1123 + grant.subject === PAIRING_LINK_SUBJECT;
1124 return yield* sessions
1125 .issue({
1126 method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token",
@@ -1073,9 +1129,10 @@ export const make = Effect.gen(function* () {
1129 ...(input?.proofKeyThumbprint
1130 ? {
1131 proofKeyThumbprint: input.proofKeyThumbprint,
1076 - ttl: Duration.hours(1),
1132 + ttl: renewable ? RENEWABLE_ACCESS_TOKEN_TTL : Duration.hours(1),
1133 }
1134 : {}),
1135 + ...(renewable ? { renewalWindow: RENEWABLE_SESSION_WINDOW } : {}),
1136 replaceActiveForSubjectAndMethod: grant.method === "desktop-bootstrap",
1137 client: {
1138 ...requestMetadata,
@@ -1089,25 +1146,7 @@ export const make = Effect.gen(function* () {
1146 );
1147 }),
1148 ),
1092 - Effect.flatMap((session) =>
1093 - DateTime.now.pipe(
1094 - Effect.map(
1095 - (now) =>
1096 - ({
1097 - access_token: session.token,
1098 - issued_token_type: AuthAccessTokenType,
1099 - token_type: input?.proofKeyThumbprint ? "DPoP" : "Bearer",
1100 - expires_in: Math.max(
1101 - 0,
1102 - Math.floor(
1103 - (session.expiresAt.epochMilliseconds - now.epochMilliseconds) / 1000,
1104 - ),
1105 - ),
1106 - scope: encodeOAuthScope(session.scopes),
1107 - }) satisfies AuthAccessTokenResult,
1108 - ),
1109 - ),
1110 - ),
1149 + Effect.flatMap(toAccessTokenResult),
1150 (exchange) =>
1151 input?.proofKeyThumbprint ? connectTrustLock.withPermits(1)(exchange) : exchange,
1152 Effect.withSpan("EnvironmentAuth.exchangeBootstrapCredentialForAccessToken"),
@@ -1611,6 +1650,7 @@ export const make = Effect.gen(function* () {
1650 getSessionState,
1651 createBrowserSession,
1652 exchangeBootstrapCredentialForAccessToken,
1653 + renewAccessToken,
1654 createPairingLink,
1655 issueConnectCredential,
1656 approveConnectDevice,
apps/server/src/auth/SessionStore.test.ts
+25
@@ -184,6 +184,31 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("SessionStore.lay
184 }).pipe(Effect.scoped, Effect.provide(Layer.merge(layerSessionStore(), TestClock.layer()))),
185 );
186
187 + it.effect("keeps a socket on a session renewed in place until its moved deadline", () =>
188 + Effect.gen(function* () {
189 + const sessions = yield* SessionStore.SessionStore;
190 + const renewable = { ttl: Duration.hours(1), renewalWindow: Duration.hours(2) };
191 + const client = yield* sessions.issue({ ...relaySessionInput, ...renewable });
192 + const invalidated = yield* Deferred.make<void>();
193 + const watcher = yield* sessions
194 + .awaitInvalidation(client.sessionId, relaySessionInput.proofKeyThumbprint)
195 + .pipe(
196 + Effect.andThen(Deferred.succeed(invalidated, undefined)),
197 + Effect.forkScoped({ startImmediately: true }),
198 + );
199 + yield* TestClock.adjust(Duration.minutes(90));
200 + yield* sessions.renew(client.token, {
201 + proofKeyThumbprint: relaySessionInput.proofKeyThumbprint,
202 + consumeProof: Effect.void,
203 + ...renewable,
204 + });
205 + yield* TestClock.adjust(Duration.millis(120 * 60_000 - 1));
206 + expect(yield* Deferred.isDone(invalidated)).toBe(false);
207 + yield* TestClock.adjust(Duration.millis(1));
208 + yield* Fiber.join(watcher);
209 + }).pipe(Effect.scoped, Effect.provide(Layer.merge(layerSessionStore(), TestClock.layer()))),
210 + );
211 +
212 it.effect("closes a DPoP socket when an earlier renewal in its chain is revoked", () =>
213 Effect.gen(function* () {
214 const sessions = yield* SessionStore.SessionStore;
apps/server/src/auth/SessionStore.ts
+154 -18
@@ -24,6 +24,10 @@ import * as Option from "effect/Option";
24 import * as ServerConfig from "../config.ts";
25 import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
26 import * as AuthSessions from "../persistence/AuthSessions.ts";
27 +import type {
28 + ServerAuthInternalError,
29 + ServerAuthInvalidCredentialError,
30 +} from "./EnvironmentAuth.ts";
31 import * as PayloadSigner from "./PayloadSigner.ts";
32 import * as ServerSecretStore from "./ServerSecretStore.ts";
33 import {
@@ -129,6 +133,17 @@ export class UnknownSessionTokenError extends Schema.TaggedError<UnknownSessionT
133 }
134 }
135
136 +export class SessionTokenNotRenewableError extends Schema.TaggedError<SessionTokenNotRenewableError>()(
137 + "SessionTokenNotRenewableError",
138 + {
139 + sessionId: AuthSessionId,
140 + },
141 +) {
142 + override get message(): string {
143 + return "Session token cannot be renewed with this key.";
144 + }
145 +}
146 +
147 export class SessionTokenRevokedError extends Schema.TaggedError<SessionTokenRevokedError>()(
148 "SessionTokenRevokedError",
149 {
@@ -238,6 +253,7 @@ export const SessionCredentialInvalidError = Schema.Union([
253 SessionTokenExpiredError,
254 UnknownSessionTokenError,
255 SessionTokenRevokedError,
256 + SessionTokenNotRenewableError,
257 InvalidSessionExpirationClaimError,
258 MalformedWebSocketTokenError,
259 InvalidWebSocketTokenSignatureError,
@@ -397,7 +413,25 @@ export class SessionStore extends Context.Service<
413 readonly peerLink?: boolean;
414 readonly replaceActiveForSubjectAndMethod?: boolean;
415 readonly replaceSessionId?: AuthSessionId;
416 + /** Keeps the session alive this long past each renewal; `ttl` then bounds only the token. */
417 + readonly renewalWindow?: Duration.Duration;
418 }) => Effect.Effect<IssuedSession, SessionCredentialInternalError>;
419 + /** Trades a renewable token, even an expired one, for a fresh token on the same session. */
420 + readonly renew: (
421 + token: string,
422 + input: {
423 + readonly proofKeyThumbprint: string;
424 + readonly ttl: Duration.Duration;
425 + readonly renewalWindow: Duration.Duration;
426 + readonly consumeProof: Effect.Effect<
427 + void,
428 + ServerAuthInvalidCredentialError | ServerAuthInternalError
429 + >;
430 + },
431 + ) => Effect.Effect<
432 + IssuedSession,
433 + SessionCredentialError | ServerAuthInvalidCredentialError | ServerAuthInternalError
434 + >;
435 readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;
436 readonly issueWebSocketToken: (
437 sessionId: AuthSessionId,
@@ -459,6 +493,8 @@ const SessionClaims = Schema.Struct({
493 rtc: Schema.optionalKey(RuntimeMode),
494 /** Signed, so a client cannot shed its peer link's limits. */
495 plk: Schema.optionalKey(Schema.Literal(1)),
496 + /** Signed, so only sessions issued as renewable can renew. */
497 + rnw: Schema.optionalKey(Schema.Literal(1)),
498 iat: Schema.Number,
499 exp: Schema.Number,
500 });
@@ -661,6 +697,23 @@ const make = Effect.gen(function* () {
697 );
698
699 const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
700 + const signClaims = Effect.fnUntraced(function* (claims: SessionClaims) {
701 + const encodedPayload = yield* encodeClaims(claims).pipe(
702 + Effect.map(base64UrlEncode),
703 + Effect.mapError(
704 + (cause) =>
705 + new SessionCredentialIssueError({
706 + sessionId: claims.sid,
707 + cause: new SessionClaimsEncodingError({
708 + sessionId: claims.sid,
709 + operation: "encode_session_claims",
710 + cause,
711 + }),
712 + }),
713 + ),
714 + );
715 + return `${encodedPayload}.${yield* signer.sign(encodedPayload)}`;
716 + });
717 const issue: SessionStore["Service"]["issue"] = Effect.fn("SessionStore.issue")(
718 function* (input) {
719 const sessionId = AuthSessionId.make(
@@ -672,6 +725,9 @@ const make = Effect.gen(function* () {
725 const expiresAt = DateTime.add(issuedAt, {
726 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
727 });
728 + const sessionExpiresAt = input?.renewalWindow
729 + ? DateTime.add(issuedAt, { milliseconds: Duration.toMillis(input.renewalWindow) })
730 + : expiresAt;
731 const claims: SessionClaims = {
732 v: 1,
733 kind: "session",
@@ -682,25 +738,12 @@ const make = Effect.gen(function* () {
738 ...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),
739 ...(input?.runtimeModeCeiling ? { rtc: input.runtimeModeCeiling } : {}),
740 ...(input?.peerLink === true ? { plk: 1 as const } : {}),
741 + ...(input?.renewalWindow ? { rnw: 1 as const } : {}),
742 iat: issuedAt.epochMilliseconds,
743 exp: expiresAt.epochMilliseconds,
744 };
745
689 - const encodedPayload = yield* encodeClaims(claims).pipe(
690 - Effect.map(base64UrlEncode),
691 - Effect.mapError(
692 - (cause) =>
693 - new SessionCredentialIssueError({
694 - sessionId,
695 - cause: new SessionClaimsEncodingError({
696 - sessionId,
697 - operation: "encode_session_claims",
698 - cause,
699 - }),
700 - }),
701 - ),
702 - );
703 - const signature = yield* signer.sign(encodedPayload);
746 + const token = yield* signClaims(claims);
747 const client = input?.client ?? createDefaultClientMetadata();
748 const sessionRecord = {
749 sessionId,
@@ -716,7 +759,7 @@ const make = Effect.gen(function* () {
759 browser: client.browser ?? null,
760 },
761 issuedAt,
719 - expiresAt,
762 + expiresAt: sessionExpiresAt,
763 ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
764 } satisfies AuthSessions.CreateAuthSessionInput;
765 const replacedSessionIds = yield* (
@@ -752,7 +795,7 @@ const make = Effect.gen(function* () {
795 method: claims.method,
796 client,
797 issuedAt,
755 - expiresAt,
798 + expiresAt: sessionExpiresAt,
799 lastConnectedAt: null,
800 connected: false,
801 }),
@@ -760,7 +803,7 @@ const make = Effect.gen(function* () {
803
804 return {
805 sessionId,
763 - token: `${encodedPayload}.${signature}`,
806 + token,
807 method: claims.method,
808 client,
809 expiresAt: expiresAt,
@@ -869,6 +912,86 @@ const make = Effect.gen(function* () {
912 },
913 );
914
915 + const renew: SessionStore["Service"]["renew"] = Effect.fn("SessionStore.renew")(
916 + function* (token, input) {
917 + const [encodedPayload, signature] = token.split(".");
918 + if (!encodedPayload || !signature) {
919 + return yield* new MalformedSessionTokenError({});
920 + }
921 + if (!(yield* signer.verify(encodedPayload, signature))) {
922 + return yield* new InvalidSessionTokenSignatureError({});
923 + }
924 + const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
925 + Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),
926 + );
927 + // The token's own expiry is ignored here: the session row's expiry is the renewal window.
928 + if (claims.rnw !== 1 || claims.jkt !== input.proofKeyThumbprint) {
929 + return yield* new SessionTokenNotRenewableError({ sessionId: claims.sid });
930 + }
931 + const row = yield* authSessions
932 + .getById({ sessionId: claims.sid })
933 + .pipe(
934 + Effect.mapError(
935 + (cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),
936 + ),
937 + );
938 + if (Option.isNone(row)) {
939 + return yield* new UnknownSessionTokenError({ sessionId: claims.sid });
940 + }
941 + if (row.value.revokedAt !== null) {
942 + return yield* new SessionTokenRevokedError({
943 + sessionId: claims.sid,
944 + revokedAt: row.value.revokedAt,
945 + });
946 + }
947 + const now = yield* DateTime.now;
948 + if (row.value.expiresAt.epochMilliseconds <= now.epochMilliseconds) {
949 + return yield* new SessionTokenExpiredError({
950 + sessionId: claims.sid,
951 + expiresAt: row.value.expiresAt,
952 + observedAt: now,
953 + });
954 + }
955 + yield* input.consumeProof;
956 + const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(input.ttl) });
957 + const extended = yield* authSessions
958 + .extend({
959 + sessionId: claims.sid,
960 + expiresAt: DateTime.add(now, { milliseconds: Duration.toMillis(input.renewalWindow) }),
961 + now,
962 + })
963 + .pipe(
964 + Effect.mapError(
965 + (cause) => new SessionCredentialIssueError({ sessionId: claims.sid, cause }),
966 + ),
967 + );
968 + // A revoke can land between the read above and the update.
969 + if (!extended) {
970 + return yield* new SessionTokenNotRenewableError({ sessionId: claims.sid });
971 + }
972 + const renewedToken = yield* signClaims({
973 + ...claims,
974 + iat: now.epochMilliseconds,
975 + exp: expiresAt.epochMilliseconds,
976 + });
977 + const session = yield* loadActiveSession(claims.sid).pipe(
978 + Effect.mapError(
979 + (cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),
980 + ),
981 + );
982 + if (Option.isSome(session)) yield* emitUpsert(session.value);
983 + return {
984 + sessionId: claims.sid,
985 + token: renewedToken,
986 + method: claims.method,
987 + client: toClientMetadata(row.value.client),
988 + expiresAt,
989 + scopes: row.value.scopes,
990 + proofKeyThumbprint: input.proofKeyThumbprint,
991 + } satisfies IssuedSession;
992 + },
993 + );
994 +
995 const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
996 const issueWebSocketToken: SessionStore["Service"]["issueWebSocketToken"] = Effect.fn(
997 "SessionStore.issueWebSocketToken",
@@ -1113,12 +1236,24 @@ const make = Effect.gen(function* () {
1236 while (true) {
1237 const rows = yield* Effect.forEach(chain, readRow);
1238 if (rows.some((row) => Option.isNone(row) || row.value.revokedAt !== null)) return;
1239 + // Renewal moves a session's expiry in place, so the snapshot can be stale.
1240 + const currentRow = rows.at(-1);
1241 + if (currentRow !== undefined && Option.isSome(currentRow)) current = currentRow.value;
1242 const now = yield* DateTime.now;
1243 const remaining = current.expiresAt.epochMilliseconds - now.epochMilliseconds;
1244 if (remaining > 0) {
1245 yield* Effect.raceFirst(nextRemoval, Effect.sleep(Duration.millis(remaining)));
1246 continue;
1247 }
1248 + // A renewal can land between the read above and the clock sample.
1249 + const latest = yield* readRow(current.sessionId);
1250 + if (
1251 + Option.isSome(latest) &&
1252 + latest.value.expiresAt.epochMilliseconds > current.expiresAt.epochMilliseconds
1253 + ) {
1254 + current = latest.value;
1255 + continue;
1256 + }
1257 const successorId =
1258 proofKeyThumbprint === undefined
1259 ? undefined
@@ -1144,6 +1279,7 @@ const make = Effect.gen(function* () {
1279 cookieName,
1280 legacyCookieName,
1281 issue,
1282 + renew,
1283 verify,
1284 issueWebSocketToken,
1285 verifyWebSocketToken,
apps/server/src/auth/http.ts
+16 -2
@@ -1,5 +1,6 @@
1 import {
2 authScopeRequiredResponse,
3 + AuthAccessTokenType,
4 AuthAccessWriteScope,
5 AuthStandardClientScopes,
6 AuthGrantScope,
@@ -380,8 +381,7 @@ export const layer = HttpApiBuilder.group(
381 if (requestedScopes === null || requestedScopes?.length === 0) {
382 return yield* failEnvironmentInvalidRequest("invalid_scope");
383 }
383 - // Not recorded: a replayer also holds the subject token and could sign its own proof.
384 - // Recording would let anyone write replay state to disk.
384 + // Bootstrap exchanges leave the proof unrecorded because its key is not always trusted.
385 const proof = args.headers.dpop
386 ? yield* checkRequestDpopProof({ request }).pipe(
387 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
@@ -400,6 +400,20 @@ export const layer = HttpApiBuilder.group(
400 )
401 : undefined;
402 yield* appendCredentialResponseHeaders;
403 + if (args.payload.subject_token_type === AuthAccessTokenType) {
404 + if (requestedScopes !== undefined) {
405 + return yield* failEnvironmentInvalidRequest("invalid_scope");
406 + }
407 + if (!proof) {
408 + yield* appendDpopChallengeHeader;
409 + return yield* failEnvironmentAuthInvalid("invalid_credential");
410 + }
411 + return yield* serverAuth.renewAccessToken(
412 + args.payload.subject_token,
413 + proof.thumbprint,
414 + proof.consume,
415 + );
416 + }
417 return yield* serverAuth.exchangeBootstrapCredentialForAccessToken(
418 args.payload.subject_token,
419 requestedScopes,
apps/server/src/environment/ServerEnvironment.ts
+1
@@ -223,6 +223,7 @@ export const make = Effect.gen(function* () {
223 repositoryIdentity: true,
224 connectionProbe: true,
225 attachmentUploads: true,
226 + accessTokenRenewal: true,
227 questionAttachments: true,
228 fileAttachments: { maxUploadBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES },
229 pullRequests: true,
apps/server/src/persistence/AuthSessions.ts
+38
@@ -81,6 +81,13 @@ export const RevokeAuthSessionInput = Schema.Struct({
81 });
82 export type RevokeAuthSessionInput = typeof RevokeAuthSessionInput.Type;
83
84 +export const ExtendAuthSessionInput = Schema.Struct({
85 + sessionId: AuthSessionId,
86 + expiresAt: Schema.DateTimeUtcFromString,
87 + now: Schema.DateTimeUtcFromString,
88 +});
89 +export type ExtendAuthSessionInput = typeof ExtendAuthSessionInput.Type;
90 +
91 export const RevokeOtherAuthSessionsInput = Schema.Struct({
92 currentSessionId: AuthSessionId,
93 revokedAt: Schema.DateTimeUtcFromString,
@@ -120,6 +127,10 @@ export class AuthSessionRepository extends Context.Service<
127 readonly revoke: (
128 input: RevokeAuthSessionInput,
129 ) => Effect.Effect<boolean, AuthSessionRepositoryError>;
130 + /** Moves a live session's expiry; false when it is revoked, expired or missing. */
131 + readonly extend: (
132 + input: ExtendAuthSessionInput,
133 + ) => Effect.Effect<boolean, AuthSessionRepositoryError>;
134 readonly revokeAllExcept: (
135 input: RevokeOtherAuthSessionsInput,
136 ) => Effect.Effect<ReadonlyArray<AuthSessionId>, AuthSessionRepositoryError>;
@@ -349,6 +360,20 @@ export const make = Effect.gen(function* () {
360 `,
361 });
362
363 + const extendSessionRows = SqlSchema.findAll({
364 + Request: ExtendAuthSessionInput,
365 + Result: Schema.Struct({ sessionId: AuthSessionId }),
366 + execute: ({ sessionId, expiresAt, now }) =>
367 + sql`
368 + UPDATE auth_sessions
369 + SET expires_at = ${expiresAt}
370 + WHERE session_id = ${sessionId}
371 + AND revoked_at IS NULL
372 + AND expires_at > ${now}
373 + RETURNING session_id AS "sessionId"
374 + `,
375 + });
376 +
377 const proofKeyThumbprintRows = SqlSchema.findAll({
378 Request: GetAuthSessionByIdInput,
379 Result: Schema.Struct({ proofKeyThumbprint: Schema.String }),
@@ -497,6 +522,18 @@ export const make = Effect.gen(function* () {
522 Effect.map((rows) => rows.length > 0),
523 );
524
525 + const extend: AuthSessionRepository["Service"]["extend"] = (input) =>
526 + extendSessionRows(input).pipe(
527 + Effect.mapError(
528 + toPersistenceSqlOrDecodeError(
529 + "AuthSessionRepository.extend:query",
530 + "AuthSessionRepository.extend:decodeRows",
531 + { sessionId: input.sessionId },
532 + ),
533 + ),
534 + Effect.map((rows) => rows.length > 0),
535 + );
536 +
537 const revokeAllExcept: AuthSessionRepository["Service"]["revokeAllExcept"] = (input) =>
538 revokeOtherSessionRows(input).pipe(
539 Effect.mapError(
@@ -553,6 +590,7 @@ export const make = Effect.gen(function* () {
590 getById,
591 listActive,
592 revoke,
593 + extend,
594 revokeAllExcept,
595 setLastConnectedAt,
596 getProofKeyThumbprint,
docs/internals/environment-auth.md
+10
@@ -27,6 +27,16 @@ model. DPoP binds a token to a client's proof key; an invalid proof must fail
27 rather than fall back to bearer authentication. The OAuth token-exchange
28 vocabulary gives these grants a familiar meaning.
29
30 +A device that exchanges a plain pairing link with a DPoP proof gets a one-hour
31 +token on a session that renews: presenting the token, even expired, with a
32 +proof from the same key moves the session's expiry 30 days out and returns a
33 +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
38 +their credential still cuts a device off.
39 +
40 ### Guest links are not sessions
41
42 A [guest link](../user/guest-links.md) gives one browser read access to one
packages/contracts/src/auth.ts
+2 -1
@@ -221,7 +221,8 @@ export type AuthClientPresentationMetadata = typeof AuthClientPresentationMetada
221 export const AuthTokenExchangeRequest = Schema.Struct({
222 grant_type: Schema.Literal(AuthTokenExchangeGrantType),
223 subject_token: TrimmedNonEmptyString,
224 - subject_token_type: Schema.Literal(AuthEnvironmentBootstrapTokenType),
224 + /** An access token renews its own session, with a DPoP proof from the key it is bound to. */
225 + subject_token_type: Schema.Literals([AuthEnvironmentBootstrapTokenType, AuthAccessTokenType]),
226 requested_token_type: Schema.Literal(AuthAccessTokenType),
227 scope: Schema.optionalKey(TrimmedNonEmptyString),
228 client_label: Schema.optionalKey(TrimmedNonEmptyString),
packages/contracts/src/environment.ts
+2
@@ -86,6 +86,8 @@ export type ServerSelfUpdateCapability = typeof ServerSelfUpdateCapability.Type;
86 export const ExecutionEnvironmentCapabilities = Schema.Struct({
87 repositoryIdentity: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
88 connectionProbe: Schema.optionalKey(Schema.Boolean),
89 + /** A DPoP session from a pairing link renews at /oauth/token; pair with a bearer where absent. */
90 + accessTokenRenewal: Schema.optionalKey(Schema.Boolean),
91 attachmentUploads: Schema.optionalKey(Schema.Boolean),
92 questionAttachments: Schema.optionalKey(Schema.Boolean),
93 fileAttachments: Schema.optionalKey(