@devries-cameron20 / t3code Mirror · read-only / commits / 3cc31ed27c
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 22, 18:15 UTC

fix(server): websocket tickets name the route they open (#24554)

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>

Julius Marminge committed Oct 24, 2026 at 15:23 UTC 3cc31ed27c8956b36cee35a50509fb7c6869592b
16 files changed +527 -98
apps/server/src/auth/EnvironmentAuth.test.ts
+162 -14
@@ -1,6 +1,15 @@
1 +// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync or sign.
2 +import * as NodeCrypto from "node:crypto";
3 +
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 import { authScopeResponse, AuthStandardClientScopes } from "@t3tools/contracts";
6 +import {
7 + computeDpopAccessTokenHash,
8 + computeDpopJwkThumbprint,
9 + type DpopPublicJwk,
10 +} from "@t3tools/shared/dpop";
11 import { expect, it } from "@effect/vitest";
12 +import * as DateTime from "effect/DateTime";
13 import * as Effect from "effect/Effect";
14 import * as Layer from "effect/Layer";
15 import * as Redacted from "effect/Redacted";
@@ -68,6 +77,36 @@ const requestMetadata = {
77 ipAddress: "192.168.1.23",
78 };
79
80 +const makeDpopKey = () => {
81 + const { privateKey, publicKey } = NodeCrypto.generateKeyPairSync("ec", { namedCurve: "P-256" });
82 + const publicJwk = publicKey.export({ format: "jwk" }) as DpopPublicJwk;
83 + let proofCount = 0;
84 + return {
85 + thumbprint: computeDpopJwkThumbprint(publicJwk),
86 + sign: (input: {
87 + readonly method: string;
88 + readonly url: string;
89 + readonly token: string;
90 + readonly iat: number;
91 + }) => {
92 + const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
93 + const header = encode({ typ: "dpop+jwt", alg: "ES256", jwk: publicJwk });
94 + const payload = encode({
95 + htm: input.method,
96 + htu: input.url,
97 + jti: `proof-${++proofCount}`,
98 + iat: input.iat,
99 + ath: computeDpopAccessTokenHash(input.token),
100 + });
101 + const signature = NodeCrypto.sign("sha256", Buffer.from(`${header}.${payload}`), {
102 + key: privateKey,
103 + dsaEncoding: "ieee-p1363",
104 + }).toString("base64url");
105 + return `${header}.${payload}.${signature}`;
106 + },
107 + };
108 +};
109 +
110 it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
111 it.effect("uses the reusable dev cookie without overriding a normal scoped cookie", () =>
112 Effect.gen(function* () {
@@ -527,11 +566,14 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
566 const pairing = yield* serverAuth.issuePairingCredential();
567 const exchanged = yield* serverAuth.createBrowserSession(pairing.credential, requestMetadata);
568 const upgrade = (headers: Record<string, string>) =>
530 - serverAuth.authenticateWebSocketUpgrade({
531 - url: "/ws",
532 - cookies: { [sessions.cookieName]: exchanged.sessionToken },
533 - headers: { host: "192.168.1.50:3773", ...headers },
534 - } as never);
569 + serverAuth.authenticateWebSocketUpgrade(
570 + {
571 + url: "/ws",
572 + cookies: { [sessions.cookieName]: exchanged.sessionToken },
573 + headers: { host: "192.168.1.50:3773", ...headers },
574 + } as never,
575 + "rpc",
576 + );
577
578 yield* upgrade({ origin: "http://192.168.1.50:3773" });
579 yield* upgrade({
@@ -588,16 +630,122 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
630 Effect.gen(function* () {
631 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
632 const bearer = yield* serverAuth.issueSession();
591 - const verified = yield* serverAuth.authenticateWebSocketUpgrade({
592 - url: "/ws",
593 - cookies: {},
594 - headers: {
595 - host: "192.168.1.50:3773",
596 - origin: "http://192.168.1.50:8080",
597 - authorization: `Bearer ${bearer.token}`,
598 - },
599 - } as never);
633 + const verified = yield* serverAuth.authenticateWebSocketUpgrade(
634 + {
635 + url: "/ws",
636 + cookies: {},
637 + headers: {
638 + host: "192.168.1.50:3773",
639 + origin: "http://192.168.1.50:8080",
640 + authorization: `Bearer ${bearer.token}`,
641 + },
642 + } as never,
643 + "rpc",
644 + );
645 expect(verified.sessionId).toBe(bearer.sessionId);
646 }).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))),
647 );
648 +
649 + it.effect("binds a DPoP session's RPC socket ticket to its proof key", () =>
650 + Effect.gen(function* () {
651 + const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
652 + const sessions = yield* SessionStore.SessionStore;
653 + const key = makeDpopKey();
654 + const other = makeDpopKey();
655 + const exchanged = yield* serverAuth.exchangeBootstrapCredentialForAccessToken(
656 + "desktop-bootstrap-token",
657 + ["orchestration:read"],
658 + requestMetadata,
659 + { proofKeyThumbprint: key.thumbprint },
660 + );
661 + const session = yield* sessions.verify(exchanged.access_token);
662 + const host = "192.168.1.50:3773";
663 + const socketUrl = `http://${host}/ws`;
664 + const iat = Math.floor((yield* DateTime.now).epochMilliseconds / 1_000);
665 + const upgrade = (ticket: string, use: "rpc" | "media", proof?: string) =>
666 + serverAuth.authenticateWebSocketUpgrade(
667 + {
668 + method: "GET",
669 + url: `/ws?orchestrationProtocol=2&wsTicket=${ticket}${proof ? `&dpop=${proof}` : ""}`,
670 + cookies: {},
671 + headers: { host },
672 + } as never,
673 + use,
674 + );
675 +
676 + const rpc = yield* serverAuth.issueWebSocketTicket(session, { use: "rpc" });
677 + const bare = yield* Effect.flip(upgrade(rpc.ticket, "rpc"));
678 + expect(bare._tag).toBe("ServerAuthInvalidCredentialError");
679 + const signed = yield* upgrade(
680 + rpc.ticket,
681 + "rpc",
682 + key.sign({ method: "GET", url: socketUrl, token: rpc.ticket, iat }),
683 + );
684 + expect(signed.sessionId).toBe(session.sessionId);
685 +
686 + const wrongKey = yield* Effect.flip(
687 + upgrade(
688 + rpc.ticket,
689 + "rpc",
690 + other.sign({ method: "GET", url: socketUrl, token: rpc.ticket, iat }),
691 + ),
692 + );
693 + expect(wrongKey._tag).toBe("ServerAuthInvalidCredentialError");
694 + const onMedia = yield* Effect.flip(
695 + upgrade(
696 + rpc.ticket,
697 + "media",
698 + key.sign({ method: "GET", url: socketUrl, token: rpc.ticket, iat }),
699 + ),
700 + );
701 + expect(onMedia._tag).toBe("ServerAuthInvalidCredentialError");
702 +
703 + const media = yield* serverAuth.issueWebSocketTicket(session, { use: "media" });
704 + expect((yield* upgrade(media.ticket, "media")).sessionId).toBe(session.sessionId);
705 + const mediaOnRpc = yield* Effect.flip(upgrade(media.ticket, "rpc"));
706 + expect(mediaOnRpc._tag).toBe("ServerAuthInvalidCredentialError");
707 +
708 + // Clients that predate ticket binding still connect with the unbound ticket they mint.
709 + const legacy = yield* serverAuth.issueWebSocketTicket(session);
710 + expect((yield* upgrade(legacy.ticket, "rpc")).sessionId).toBe(session.sessionId);
711 + }).pipe(
712 + Effect.provide(layerEnvironmentAuth({ desktopBootstrapToken: "desktop-bootstrap-token" })),
713 + ),
714 + );
715 +
716 + it.effect("rejects a replayed proof on a bound RPC socket ticket", () =>
717 + Effect.gen(function* () {
718 + const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
719 + const sessions = yield* SessionStore.SessionStore;
720 + const key = makeDpopKey();
721 + const exchanged = yield* serverAuth.exchangeBootstrapCredentialForAccessToken(
722 + "desktop-bootstrap-token",
723 + ["orchestration:read"],
724 + requestMetadata,
725 + { proofKeyThumbprint: key.thumbprint },
726 + );
727 + const session = yield* sessions.verify(exchanged.access_token);
728 + const rpc = yield* serverAuth.issueWebSocketTicket(session, { use: "rpc" });
729 + const request = {
730 + method: "GET",
731 + url: `/ws?wsTicket=${rpc.ticket}&dpop=${key.sign({
732 + method: "GET",
733 + url: "http://192.168.1.50:3773/ws",
734 + token: rpc.ticket,
735 + iat: Math.floor((yield* DateTime.now).epochMilliseconds / 1_000),
736 + })}`,
737 + cookies: {},
738 + headers: { host: "192.168.1.50:3773" },
739 + } as never;
740 +
741 + yield* serverAuth.authenticateWebSocketUpgrade(request, "rpc");
742 + const replayed = yield* Effect.flip(serverAuth.authenticateWebSocketUpgrade(request, "rpc"));
743 + expect(replayed._tag).toBe("ServerAuthInvalidCredentialError");
744 + if (replayed._tag === "ServerAuthInvalidCredentialError") {
745 + expect(replayed.dpopFailureReason).toBe("replay");
746 + }
747 + }).pipe(
748 + Effect.provide(layerEnvironmentAuth({ desktopBootstrapToken: "desktop-bootstrap-token" })),
749 + ),
750 + );
751 });
apps/server/src/auth/EnvironmentAuth.ts
+75 -25
@@ -21,6 +21,7 @@ import {
21 type ServerAuthDescriptor,
22 type ServerAuthSessionMethod,
23 type AuthWebSocketTicketResult,
24 + type AuthWebSocketTicketUse,
25 DpopFailureReason,
26 type DpopFailureReason as DpopFailureReasonType,
27 } from "@t3tools/contracts";
@@ -543,9 +544,11 @@ export class EnvironmentAuth extends Context.Service<
544 ) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
545 readonly authenticateWebSocketUpgrade: (
546 request: HttpServerRequest.HttpServerRequest,
547 + use: AuthWebSocketTicketUse,
548 ) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
549 readonly issueWebSocketTicket: (
548 - session: Pick<AuthenticatedSession, "sessionId">,
550 + session: Pick<AuthenticatedSession, "sessionId" | "proofKeyThumbprint">,
551 + input?: { readonly use?: AuthWebSocketTicketUse },
552 ) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthInternalError>;
553 readonly issueStartupPairingUrl: (
554 baseUrl: string,
@@ -591,6 +594,7 @@ type BootstrapExchangeResult = {
594 const AUTHORIZATION_PREFIX = "Bearer ";
595 const DPOP_AUTHORIZATION_PREFIX = "DPoP ";
596 const WEBSOCKET_TICKET_QUERY_PARAM = "wsTicket";
597 +const WEBSOCKET_PROOF_QUERY_PARAM = "dpop";
598
599 const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {
600 const leftCanManage = left.scopes.includes(AuthAccessWriteScope);
@@ -1220,18 +1224,31 @@ export const make = Effect.gen(function* () {
1224 Effect.withSpan("EnvironmentAuth.issueStartupPairingUrl"),
1225 );
1226
1223 - const issueWebSocketTicket: EnvironmentAuth["Service"]["issueWebSocketTicket"] = (session) =>
1224 - sessions.issueWebSocketToken(session.sessionId).pipe(
1225 - Effect.mapError((cause) => new ServerAuthWebSocketTokenIssueError({ cause })),
1226 - Effect.map(
1227 - (issued) =>
1228 - ({
1229 - ticket: issued.token,
1230 - expiresAt: DateTime.toUtc(issued.expiresAt),
1231 - }) satisfies AuthWebSocketTicketResult,
1232 - ),
1233 - Effect.withSpan("EnvironmentAuth.issueWebSocketTicket"),
1234 - );
1227 + // Only the RPC socket's ticket is bound to the client's proof key. The media
1228 + // routes reuse one ticket across <img>, EventSource and several sockets, and
1229 + // each of those would need its own single-use proof.
1230 + const issueWebSocketTicket: EnvironmentAuth["Service"]["issueWebSocketTicket"] = (
1231 + session,
1232 + input,
1233 + ) =>
1234 + sessions
1235 + .issueWebSocketToken(session.sessionId, {
1236 + ...(input?.use ? { audience: input.use } : {}),
1237 + ...(input?.use === "rpc" && session.proofKeyThumbprint
1238 + ? { proofKeyThumbprint: session.proofKeyThumbprint }
1239 + : {}),
1240 + })
1241 + .pipe(
1242 + Effect.mapError((cause) => new ServerAuthWebSocketTokenIssueError({ cause })),
1243 + Effect.map(
1244 + (issued) =>
1245 + ({
1246 + ticket: issued.token,
1247 + expiresAt: DateTime.toUtc(issued.expiresAt),
1248 + }) satisfies AuthWebSocketTicketResult,
1249 + ),
1250 + Effect.withSpan("EnvironmentAuth.issueWebSocketTicket"),
1251 + );
1252
1253 const authenticateHttpRequest: EnvironmentAuth["Service"]["authenticateHttpRequest"] = (
1254 request,
@@ -1239,22 +1256,55 @@ export const make = Effect.gen(function* () {
1256 authenticateRequest(request).pipe(Effect.withSpan("EnvironmentAuth.authenticateHttpRequest"));
1257
1258 const authenticateWebSocketUpgrade: EnvironmentAuth["Service"]["authenticateWebSocketUpgrade"] =
1242 - Effect.fn("EnvironmentAuth.authenticateWebSocketUpgrade")(function* (request) {
1259 + Effect.fn("EnvironmentAuth.authenticateWebSocketUpgrade")(function* (request, use) {
1260 const requestUrl = HttpServerRequest.toURL(request);
1261 if (Option.isSome(requestUrl)) {
1262 const websocketTicket = requestUrl.value.searchParams.get(WEBSOCKET_TICKET_QUERY_PARAM);
1263 if (websocketTicket && websocketTicket.trim().length > 0) {
1247 - return yield* sessions.verifyWebSocketToken(websocketTicket).pipe(
1248 - mapSessionVerificationErrors,
1249 - Effect.flatMap(rejectMcpClientAudience),
1250 - Effect.map((session) => ({
1251 - sessionId: session.sessionId,
1252 - subject: session.subject,
1253 - method: session.method,
1254 - scopes: session.scopes,
1255 - ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
1256 - })),
1257 - );
1264 + const session = yield* sessions
1265 + .verifyWebSocketToken(websocketTicket)
1266 + .pipe(mapSessionVerificationErrors, Effect.flatMap(rejectMcpClientAudience));
1267 + if (session.audience !== undefined && session.audience !== use) {
1268 + return yield* new ServerAuthInvalidCredentialError({
1269 + diagnostic: `WebSocket ticket was issued for the ${session.audience} route.`,
1270 + });
1271 + }
1272 + if (session.proofKeyThumbprint) {
1273 + // A WebSocket cannot set headers, so the proof rides in the query.
1274 + // The ticket is the token the proof hashes, and the proof's jti is
1275 + // consumed like any other, so a captured socket URL is dead once the
1276 + // client has used it. Beating the client to first use still needs an
1277 + // active interceptor, which only encrypted transport rules out.
1278 + const proof =
1279 + request.headers.dpop ??
1280 + requestUrl.value.searchParams.get(WEBSOCKET_PROOF_QUERY_PARAM) ??
1281 + undefined;
1282 + if (!proof) {
1283 + return yield* new ServerAuthInvalidCredentialError({
1284 + diagnostic: "DPoP-bound WebSocket ticket requires a DPoP proof.",
1285 + dpopFailureReason: "invalid_proof",
1286 + });
1287 + }
1288 + yield* verifyRequestDpopProof({
1289 + request,
1290 + proof,
1291 + expectedThumbprint: session.proofKeyThumbprint,
1292 + expectedAccessToken: websocketTicket,
1293 + }).pipe(
1294 + Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore),
1295 + Effect.provideService(Crypto.Crypto, crypto),
1296 + );
1297 + }
1298 + return {
1299 + sessionId: session.sessionId,
1300 + subject: session.subject,
1301 + method: session.method,
1302 + scopes: session.scopes,
1303 + ...(session.proofKeyThumbprint
1304 + ? { proofKeyThumbprint: session.proofKeyThumbprint }
1305 + : {}),
1306 + ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
1307 + };
1308 }
1309 }
1310
apps/server/src/auth/SessionStore.ts
+15 -2
@@ -5,6 +5,7 @@ import {
5 type AuthClientMetadata,
6 type AuthClientSession,
7 type AuthEnvironmentScope,
8 + AuthWebSocketTicketUse,
9 type ClientSurface,
10 RuntimeMode,
11 type ServerAuthSessionMethod,
@@ -61,6 +62,10 @@ export interface VerifiedSession {
62 readonly runtimeModeCeiling?: RuntimeMode;
63 }
64
65 +export interface VerifiedWebSocketTicket extends VerifiedSession {
66 + readonly audience?: AuthWebSocketTicketUse;
67 +}
68 +
69 export type SessionCredentialChange =
70 | {
71 readonly type: "clientUpserted";
@@ -384,6 +389,8 @@ export class SessionStore extends Context.Service<
389 sessionId: AuthSessionId,
390 input?: {
391 readonly ttl?: Duration.Duration;
392 + readonly audience?: AuthWebSocketTicketUse;
393 + readonly proofKeyThumbprint?: string;
394 },
395 ) => Effect.Effect<
396 {
@@ -394,7 +401,7 @@ export class SessionStore extends Context.Service<
401 >;
402 readonly verifyWebSocketToken: (
403 token: string,
397 - ) => Effect.Effect<VerifiedSession, SessionCredentialError>;
404 + ) => Effect.Effect<VerifiedWebSocketTicket, SessionCredentialError>;
405 readonly listActive: () => Effect.Effect<
406 ReadonlyArray<AuthClientSession>,
407 SessionCredentialInternalError
@@ -443,6 +450,8 @@ const WebSocketClaims = Schema.Struct({
450 v: Schema.Literal(1),
451 kind: Schema.Literal("websocket"),
452 sid: AuthSessionId,
453 + aud: Schema.optionalKey(AuthWebSocketTicketUse),
454 + jkt: Schema.optionalKey(Schema.String),
455 iat: Schema.Number,
456 exp: Schema.Number,
457 });
@@ -867,6 +876,8 @@ const make = Effect.gen(function* () {
876 v: 1,
877 kind: "websocket",
878 sid: sessionId,
879 + ...(input?.audience ? { aud: input.audience } : {}),
880 + ...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),
881 iat: issuedAt.epochMilliseconds,
882 exp: expiresAt.epochMilliseconds,
883 };
@@ -959,7 +970,9 @@ const make = Effect.gen(function* () {
970 expiresAt: row.value.expiresAt,
971 subject: row.value.subject,
972 scopes: row.value.scopes,
962 - } satisfies VerifiedSession;
973 + ...(claims.aud ? { audience: claims.aud } : {}),
974 + ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
975 + } satisfies VerifiedWebSocketTicket;
976 });
977
978 const listActive: SessionStore["Service"]["listActive"] = Effect.fn("SessionStore.listActive")(
apps/server/src/auth/dpop.ts
+3 -1
@@ -54,10 +54,12 @@ export const mapDpopReplayStoreError = (
54
55 export const verifyRequestDpopProof = Effect.fn("dpop.verifyRequestDpopProof")(function* (input: {
56 readonly request: HttpServerRequest.HttpServerRequest;
57 + /** Overrides the `DPoP` header for requests that cannot carry one, such as a WebSocket upgrade. */
58 + readonly proof?: string;
59 readonly expectedThumbprint?: string;
60 readonly expectedAccessToken?: string;
61 }) {
60 - const proof = input.request.headers.dpop;
62 + const proof = input.proof ?? input.request.headers.dpop;
63 const url = HttpServerRequest.toURL(input.request);
64 if (Option.isNone(url)) {
65 return yield* new ServerAuthInvalidCredentialError({
apps/server/src/auth/http.ts
+15 -1
@@ -166,7 +166,7 @@ export const authenticateMediaRequest =
166 Effect.fnUntraced(function* (requiredScope: AuthEnvironmentScope) {
167 const request = yield* HttpServerRequest.HttpServerRequest;
168 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
169 - const session = yield* serverAuth.authenticateWebSocketUpgrade(request).pipe(
169 + const session = yield* serverAuth.authenticateWebSocketUpgrade(request, "media").pipe(
170 Effect.catch((error) =>
171 Effect.gen(function* () {
172 if (EnvironmentAuth.isServerAuthCredentialError(error)) {
@@ -426,6 +426,20 @@ export const layer = HttpApiBuilder.group(
426 ),
427 ),
428 )
429 + .handle(
430 + "webSocketTicketFor",
431 + Effect.fn("environment.auth.webSocketTicketFor")(
432 + function* (args) {
433 + yield* annotateEnvironmentRequest(args.endpoint.name);
434 + const session = yield* EnvironmentAuthenticatedPrincipal;
435 + yield* appendCredentialResponseHeaders;
436 + return yield* serverAuth.issueWebSocketTicket(session, { use: args.params.use });
437 + },
438 + Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
439 + failEnvironmentInternal("websocket_ticket_issuance_failed", error),
440 + ),
441 + ),
442 + )
443 .handle(
444 "pairingCredential",
445 Effect.fn("environment.auth.pairingCredential")(
apps/server/src/ws.ts
+1 -1
@@ -3220,7 +3220,7 @@ export const layer = Layer.unwrap(
3220 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
3221 const sessions = yield* SessionStore.SessionStore;
3222 const analytics = yield* AnalyticsService.AnalyticsService;
3223 - const session = yield* serverAuth.authenticateWebSocketUpgrade(request).pipe(
3223 + const session = yield* serverAuth.authenticateWebSocketUpgrade(request, "rpc").pipe(
3224 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
3225 failEnvironmentAuthInvalid(
3226 EnvironmentAuth.serverAuthCredentialReason(error),
apps/web/test/environmentHttpTest.ts
+1
@@ -101,6 +101,7 @@ export async function installEnvironmentHttpTest(scenario: EnvironmentHttpTestSc
101 )
102 .handle("token", () => unexpectedEndpoint("auth.token"))
103 .handle("webSocketTicket", () => unexpectedEndpoint("auth.webSocketTicket"))
104 + .handle("webSocketTicketFor", () => unexpectedEndpoint("auth.webSocketTicketFor"))
105 .handle(
106 "pairingCredential",
107 Effect.fn("test.environment.auth.pairingCredential")(function* ({ payload }) {
docs/internals/environment-auth.md
+10 -2
@@ -59,8 +59,16 @@ T3 Connect tunnel. A proxy that rewrites Host or drops the protocol header
59 breaks sign-in.
60
61 Bearer and DPoP clients obtain short-lived WebSocket tickets through authenticated
62 -HTTP so long-lived tokens stay out of socket URLs. Browser sessions can
63 -authenticate the upgrade with their cookie. A successful handshake grants no
62 +HTTP so long-lived tokens stay out of socket URLs. A ticket names the route it
63 +opens: the RPC socket, or the media routes (device hub, preview stream), which
64 +share one ticket across `<img>`, `EventSource` and several sockets. A DPoP
65 +client's RPC ticket is bound to its proof key and the upgrade carries a fresh
66 +proof in the `dpop` query parameter, since a WebSocket cannot set headers; a
67 +ticket captured on a plain HTTP LAN route is useless without the key, and the
68 +proof's `jti` is consumed like any other. Media tickets stay bearer because each
69 +media request would need its own proof. Clients that predate this mint unbound
70 +tickets that open either route. Browser sessions can authenticate the upgrade
71 +with their cookie. A successful handshake grants no
72 extra authority: [every RPC declares a required
73 scope](../../apps/server/src/auth/RpcAuthorization.ts), and the WebSocket RPC
74 group's `RpcScopeAuthorization` middleware checks it before any handler runs.
packages/client-runtime/src/authorization/layer.test.ts
+5 -3
@@ -255,7 +255,9 @@ describe("RemoteEnvironmentAuthorization", () => {
255 harness.fetch.calls.filter(([url]) => String(url).endsWith("/.well-known/t3/environment")),
256 ).toHaveLength(1);
257 expect(
258 - harness.fetch.calls.filter(([url]) => String(url).endsWith("/api/auth/websocket-ticket")),
258 + harness.fetch.calls.filter(([url]) =>
259 + String(url).endsWith("/api/auth/websocket-ticket/rpc"),
260 + ),
261 ).toHaveLength(2);
262 }),
263 );
@@ -288,7 +290,7 @@ describe("RemoteEnvironmentAuthorization", () => {
290 expect(yield* Ref.get(harness.bootstrapCalls)).toBe(0);
291 expect(harness.fetch.calls).toHaveLength(1);
292 expect(String(harness.fetch.calls[0]?.[0])).toBe(
291 - "https://environment.example.test/api/auth/websocket-ticket",
293 + "https://environment.example.test/api/auth/websocket-ticket/rpc",
294 );
295 }),
296 );
@@ -325,7 +327,7 @@ describe("RemoteEnvironmentAuthorization", () => {
327 expect(yield* Ref.get(harness.bootstrapCalls)).toBe(0);
328 expect(harness.fetch.calls.map(([url]) => String(url))).toEqual([
329 "http://192.168.1.10:3773/.well-known/t3/environment",
328 - "http://192.168.1.10:3773/api/auth/websocket-ticket",
330 + "http://192.168.1.10:3773/api/auth/websocket-ticket/rpc",
331 ]);
332 }),
333 );
packages/client-runtime/src/authorization/remote.test.ts
+102
@@ -10,6 +10,7 @@ import {
10 exchangeRemoteDpopAccessToken,
11 issueRemoteDpopWebSocketTicket,
12 issueRemoteWebSocketTicket,
13 + resolveRemoteDpopWebSocketConnectionUrl,
14 resolveRemoteWebSocketConnectionUrl,
15 } from "./remote.ts";
16 import * as ClientCapabilities from "../platform/capabilities.ts";
@@ -213,6 +214,107 @@ describe("remote environment authorization", () => {
214 }),
215 );
216
217 + it.effect("binds a DPoP client's rpc ticket to its key and proves the upgrade", () =>
218 + Effect.gen(function* () {
219 + const fetch = recordedFetch(
220 + Response.json({ ticket: "ws-ticket", expiresAt: "2026-05-01T12:05:00.000Z" }),
221 + );
222 + const proofs: Array<{ method: string; url: string; accessToken: string }> = [];
223 +
224 + const url = yield* resolveRemoteDpopWebSocketConnectionUrl({
225 + wsBaseUrl: "wss://remote.example.com/",
226 + httpBaseUrl: "https://remote.example.com/",
227 + accessToken: "dpop-access-token",
228 + createProof: (input) => {
229 + proofs.push(input);
230 + return Effect.succeed(`proof-${proofs.length}`);
231 + },
232 + connectionMethod: "relay",
233 + }).pipe(provideRemoteHttp(fetch.fetchFn));
234 +
235 + expectFetchCall(fetch.calls, 1, {
236 + url: "https://remote.example.com/api/auth/websocket-ticket/rpc",
237 + method: "POST",
238 + headers: { authorization: "DPoP dpop-access-token", dpop: "proof-1" },
239 + });
240 + expect(proofs).toEqual([
241 + {
242 + method: "POST",
243 + url: "https://remote.example.com/api/auth/websocket-ticket/rpc",
244 + accessToken: "dpop-access-token",
245 + },
246 + { method: "GET", url: "https://remote.example.com/ws", accessToken: "ws-ticket" },
247 + ]);
248 + expect(url).toBe(
249 + "wss://remote.example.com/ws?wsTicket=ws-ticket&dpop=proof-2&connectionMethod=relay",
250 + );
251 + }),
252 + );
253 +
254 + it.effect("requests the audience route even without a fallback proof", () =>
255 + Effect.gen(function* () {
256 + const fetch = recordedFetch(
257 + Response.json({ ticket: "media-ticket", expiresAt: "2026-05-01T12:05:00.000Z" }),
258 + );
259 + yield* issueRemoteDpopWebSocketTicket({
260 + httpBaseUrl: "https://remote.example.com/",
261 + accessToken: "dpop-access-token",
262 + dpopProof: "media-proof",
263 + use: "media",
264 + }).pipe(provideRemoteHttp(fetch.fetchFn));
265 + expectFetchCall(fetch.calls, 1, {
266 + url: "https://remote.example.com/api/auth/websocket-ticket/media",
267 + method: "POST",
268 + headers: { dpop: "media-proof" },
269 + });
270 + }),
271 + );
272 +
273 + it.effect("falls back to the bare ticket path on a server without the audience route", () =>
274 + Effect.gen(function* () {
275 + const fetch = recordedFetch(
276 + Response.json({ message: "Not Found" }, { status: 404 }),
277 + Response.json({ ticket: "old-ticket", expiresAt: "2026-05-01T12:05:00.000Z" }),
278 + );
279 + const proofs: Array<{ method: string; url: string; accessToken: string }> = [];
280 +
281 + const url = yield* resolveRemoteDpopWebSocketConnectionUrl({
282 + wsBaseUrl: "wss://remote.example.com/",
283 + httpBaseUrl: "https://remote.example.com/",
284 + accessToken: "dpop-access-token",
285 + createProof: (input) => {
286 + proofs.push(input);
287 + return Effect.succeed(`proof-${proofs.length}`);
288 + },
289 + }).pipe(provideRemoteHttp(fetch.fetchFn));
290 +
291 + expect(fetch.calls.map(([target]) => String(target))).toEqual([
292 + "https://remote.example.com/api/auth/websocket-ticket/rpc",
293 + "https://remote.example.com/api/auth/websocket-ticket",
294 + ]);
295 + expect(proofs).toEqual([
296 + {
297 + method: "POST",
298 + url: "https://remote.example.com/api/auth/websocket-ticket/rpc",
299 + accessToken: "dpop-access-token",
300 + },
301 + {
302 + method: "POST",
303 + url: "https://remote.example.com/api/auth/websocket-ticket",
304 + accessToken: "dpop-access-token",
305 + },
306 + { method: "GET", url: "https://remote.example.com/ws", accessToken: "old-ticket" },
307 + ]);
308 + expectFetchCall(fetch.calls, 2, {
309 + url: "https://remote.example.com/api/auth/websocket-ticket",
310 + method: "POST",
311 + headers: { dpop: "proof-2" },
312 + });
313 + expect(new URL(url).searchParams.get("wsTicket")).toBe("old-ticket");
314 + expect(new URL(url).searchParams.get("dpop")).toBe("proof-3");
315 + }),
316 + );
317 +
318 it.effect("names the signed-in Connect account and this device by hash only", () =>
319 Effect.gen(function* () {
320 const fetch = recordedFetch(
packages/client-runtime/src/authorization/remote.ts
+102 -29
@@ -5,6 +5,8 @@ import {
5 AuthTokenExchangeGrantType,
6 type ClientConnectionMethod,
7 type AuthEnvironmentScope,
8 + type AuthWebSocketTicketResult,
9 + type AuthWebSocketTicketUse,
10 } from "@t3tools/contracts";
11 import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
12 import { hashTelemetryId } from "@t3tools/shared/telemetryId";
@@ -15,6 +17,7 @@ import * as ClientCapabilities from "../platform/capabilities.ts";
17 import {
18 executeEnvironmentHttpRequest,
19 makeEnvironmentHttpApiGroupClient,
20 + RemoteEnvironmentAuthUndeclaredStatusError,
21 type RemoteEnvironmentRequestError,
22 } from "../rpc/http.ts";
23
@@ -182,46 +185,93 @@ export const fetchRemoteSessionState = Effect.fn(
185 );
186 });
187
188 +const webSocketTicketPath = (use: AuthWebSocketTicketUse | undefined) =>
189 + use === undefined ? "/api/auth/websocket-ticket" : `/api/auth/websocket-ticket/${use}`;
190 +
191 +/**
192 + * A server that predates ticket audiences has no `/:use` route and answers 404.
193 + * Its tickets are the unbound kind it always issued, so the bare path is the
194 + * right request there, not an error.
195 + */
196 +const issueWebSocketTicketWithFallback = <E, R>(
197 + use: AuthWebSocketTicketUse | undefined,
198 + issue: (
199 + use: AuthWebSocketTicketUse | undefined,
200 + ) => Effect.Effect<AuthWebSocketTicketResult, E, R>,
201 + canFallBack = true,
202 +) =>
203 + use === undefined || !canFallBack
204 + ? issue(use)
205 + : issue(use).pipe(
206 + Effect.catchIf(
207 + (error) =>
208 + error instanceof RemoteEnvironmentAuthUndeclaredStatusError && error.status === 404,
209 + () => issue(undefined),
210 + ),
211 + );
212 +
213 export const issueRemoteWebSocketTicket = Effect.fn(
214 "clientRuntime.authorization.issueRemoteWebSocketTicket",
215 )(function* (input: {
216 readonly httpBaseUrl: string;
217 readonly bearerToken: string;
218 + readonly use?: AuthWebSocketTicketUse;
219 readonly timeoutMs?: number;
220 }) {
221 const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
193 - return yield* executeEnvironmentHttpRequest(
194 - environmentEndpointUrl(input.httpBaseUrl, "/api/auth/websocket-ticket"),
195 - input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
196 - client.webSocketTicket({
197 - headers: {
198 - authorization: `Bearer ${input.bearerToken}`,
199 - },
200 - }),
222 + const headers = { authorization: `Bearer ${input.bearerToken}` };
223 + return yield* issueWebSocketTicketWithFallback(input.use, (use) =>
224 + executeEnvironmentHttpRequest(
225 + environmentEndpointUrl(input.httpBaseUrl, webSocketTicketPath(use)),
226 + input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
227 + use === undefined
228 + ? client.webSocketTicket({ headers })
229 + : client.webSocketTicketFor({ headers, params: { use } }),
230 + ),
231 );
232 });
233
234 export const issueRemoteDpopWebSocketTicket = Effect.fn(
235 "clientRuntime.authorization.issueRemoteDpopWebSocketTicket",
206 -)(function* (input: {
236 +)(function* <E = never>(input: {
237 readonly httpBaseUrl: string;
238 readonly accessToken: string;
239 readonly dpopProof: string;
240 + readonly use?: AuthWebSocketTicketUse;
241 + /** Proof for the bare path, used only when the server lacks the `/:use` route. */
242 + readonly fallbackProof?: Effect.Effect<string, E>;
243 readonly timeoutMs?: number;
244 }) {
245 const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
213 - return yield* executeEnvironmentHttpRequest(
214 - environmentEndpointUrl(input.httpBaseUrl, "/api/auth/websocket-ticket"),
215 - input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
216 - client.webSocketTicket({
217 - headers: {
218 - authorization: `DPoP ${input.accessToken}`,
219 - dpop: input.dpopProof,
220 - },
221 - }),
246 + const fallbackProof = input.fallbackProof;
247 + return yield* issueWebSocketTicketWithFallback(
248 + input.use,
249 + (use) =>
250 + Effect.gen(function* () {
251 + // The proof names the path it signs, so the fallback request needs its own.
252 + const dpopProof =
253 + use === input.use || fallbackProof === undefined ? input.dpopProof : yield* fallbackProof;
254 + const headers = { authorization: `DPoP ${input.accessToken}`, dpop: dpopProof };
255 + return yield* executeEnvironmentHttpRequest(
256 + environmentEndpointUrl(input.httpBaseUrl, webSocketTicketPath(use)),
257 + input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
258 + use === undefined
259 + ? client.webSocketTicket({ headers })
260 + : client.webSocketTicketFor({ headers, params: { use } }),
261 + );
262 + }),
263 + fallbackProof !== undefined,
264 );
265 });
266
267 +function rpcSocketUrl(wsBaseUrl: string): URL {
268 + const url = new URL(wsBaseUrl);
269 + if (url.pathname === "" || url.pathname === "/") {
270 + url.pathname = "/ws";
271 + }
272 + return url;
273 +}
274 +
275 export const resolveRemoteWebSocketConnectionUrl = Effect.fn(
276 "clientRuntime.authorization.resolveRemoteWebSocketConnectionUrl",
277 )(function* (input: {
@@ -235,13 +285,11 @@ export const resolveRemoteWebSocketConnectionUrl = Effect.fn(
285 const issued = yield* issueRemoteWebSocketTicket({
286 httpBaseUrl: input.httpBaseUrl,
287 bearerToken: input.bearerToken,
288 + use: "rpc",
289 ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),
290 });
291
241 - const url = new URL(input.wsBaseUrl);
242 - if (url.pathname === "" || url.pathname === "/") {
243 - url.pathname = "/ws";
244 - }
292 + const url = rpcSocketUrl(input.wsBaseUrl);
293 url.searchParams.set("wsTicket", issued.ticket);
294 appendClientConnectionParams(
295 url,
@@ -252,28 +300,53 @@ export const resolveRemoteWebSocketConnectionUrl = Effect.fn(
300 return url.toString();
301 });
302
303 +/**
304 + * A DPoP client's RPC ticket is bound to its key, so the upgrade carries a
305 + * proof too. A WebSocket cannot set headers, so it rides in the `dpop` query
306 + * parameter and names the socket URL as the HTTP request the server sees.
307 + */
308 export const resolveRemoteDpopWebSocketConnectionUrl = Effect.fn(
309 "clientRuntime.authorization.resolveRemoteDpopWebSocketConnectionUrl",
257 -)(function* (input: {
310 +)(function* <E>(input: {
311 readonly wsBaseUrl: string;
312 readonly httpBaseUrl: string;
313 readonly accessToken: string;
261 - readonly dpopProof: string;
314 + readonly createProof: (input: {
315 + readonly method: "GET" | "POST";
316 + readonly url: string;
317 + readonly accessToken: string;
318 + }) => Effect.Effect<string, E>;
319 readonly clientMetadata?: AuthClientPresentationMetadata;
320 readonly connectionMethod?: ClientConnectionMethod;
321 readonly timeoutMs?: number;
322 }) {
323 + const ticketProof = yield* input.createProof({
324 + method: "POST",
325 + url: environmentEndpointUrl(input.httpBaseUrl, webSocketTicketPath("rpc")),
326 + accessToken: input.accessToken,
327 + });
328 const issued = yield* issueRemoteDpopWebSocketTicket({
329 httpBaseUrl: input.httpBaseUrl,
330 accessToken: input.accessToken,
269 - dpopProof: input.dpopProof,
331 + dpopProof: ticketProof,
332 + use: "rpc",
333 + fallbackProof: Effect.suspend(() =>
334 + input.createProof({
335 + method: "POST",
336 + url: environmentEndpointUrl(input.httpBaseUrl, webSocketTicketPath(undefined)),
337 + accessToken: input.accessToken,
338 + }),
339 + ),
340 ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),
341 });
272 - const url = new URL(input.wsBaseUrl);
273 - if (url.pathname === "" || url.pathname === "/") {
274 - url.pathname = "/ws";
275 - }
342 + const url = rpcSocketUrl(input.wsBaseUrl);
343 + const upgradeProof = yield* input.createProof({
344 + method: "GET",
345 + url: `${url.protocol === "wss:" ? "https:" : "http:"}//${url.host}${url.pathname}`,
346 + accessToken: issued.ticket,
347 + });
348 url.searchParams.set("wsTicket", issued.ticket);
349 + url.searchParams.set("dpop", upgradeProof);
350 appendClientConnectionParams(
351 url,
352 input.clientMetadata,
packages/client-runtime/src/authorization/service.ts
+10 -16
@@ -218,26 +218,20 @@ export const make = Effect.gen(function* () {
218 timeoutMs?: number,
219 endpoint: { readonly httpBaseUrl: string; readonly wsBaseUrl: string } = token.endpoint,
220 ) {
221 - const ticketProof = yield* signer
222 - .createProof({
223 - method: "POST",
224 - url: environmentEndpointUrl(endpoint.httpBaseUrl, "/api/auth/websocket-ticket"),
225 - accessToken: token.accessToken,
226 - })
227 - .pipe(
228 - Effect.mapError(
229 - () =>
230 - new ConnectionBlockedError({
231 - reason: "configuration",
232 - detail: "Could not create the websocket authorization proof.",
233 - }),
234 - ),
235 - );
221 return yield* resolveRemoteDpopWebSocketConnectionUrl({
222 wsBaseUrl: endpoint.wsBaseUrl,
223 httpBaseUrl: endpoint.httpBaseUrl,
224 accessToken: token.accessToken,
240 - dpopProof: ticketProof,
225 + createProof: (proof) =>
226 + signer.createProof(proof).pipe(
227 + Effect.mapError(
228 + () =>
229 + new ConnectionBlockedError({
230 + reason: "configuration",
231 + detail: "Could not create the websocket authorization proof.",
232 + }),
233 + ),
234 + ),
235 clientMetadata: presentation.metadata,
236 connectionMethod: "relay",
237 ...(timeoutMs === undefined ? {} : { timeoutMs }),
packages/client-runtime/src/connection/supervisor.test.ts
+2 -2
@@ -862,7 +862,7 @@ describe("EnvironmentSupervisor", () => {
862 scope: AuthStandardClientScopes.join(" "),
863 }),
864 );
865 - case "/api/auth/websocket-ticket":
865 + case "/api/auth/websocket-ticket/rpc":
866 return Promise.resolve(
867 Response.json({
868 ticket: "ws-ticket",
@@ -984,7 +984,7 @@ describe("EnvironmentSupervisor", () => {
984 expect(failure._tag).toBe("RemoteEnvironmentAuthFetchError");
985 expect(yield* Ref.get(bootstrapCalls)).toBe(2);
986 expect(sessionAuthorizations).toEqual(["DPoP access-token-2"]);
987 - expect(httpPaths.filter((path) => path === "/api/auth/websocket-ticket")).toHaveLength(1);
987 + expect(httpPaths.filter((path) => path === "/api/auth/websocket-ticket/rpc")).toHaveLength(1);
988 expect(httpPaths.filter((path) => path === "/oauth/token")).toHaveLength(1);
989 expect(yield* Ref.get(harness.sessionCount)).toBe(1);
990 expect(yield* Ref.get(harness.releaseCount)).toBe(0);
packages/client-runtime/src/state/deviceHubAccess.ts
+3 -2
@@ -39,9 +39,10 @@ export const resolveDeviceHubAccess = Effect.fn("clientRuntime.state.resolveDevi
39 remoteAuthorization,
40 group: "auth",
41 method: "POST",
42 - url: (urls) => urls.webSocketTicket(),
42 + url: (urls) => urls.webSocketTicketFor({ params: { use: "media" } }),
43 timeoutMs: TICKET_TIMEOUT_MS,
44 - request: ({ client, headers }) => client.webSocketTicket({ headers }),
44 + request: ({ client, headers }) =>
45 + client.webSocketTicketFor({ headers, params: { use: "media" } }),
46 });
47 return {
48 httpBase,
packages/contracts/src/auth.ts
+12
@@ -246,6 +246,18 @@ export const AuthWebSocketTicketResult = Schema.Struct({
246 });
247 export type AuthWebSocketTicketResult = typeof AuthWebSocketTicketResult.Type;
248
249 +/**
250 + * The route a WebSocket ticket opens: the RPC socket, or the media routes
251 + * (device hub, preview stream) that share one ticket across many requests.
252 + * It is a path segment so a DPoP mint proof covers it; a query parameter is
253 + * outside the proof's `htu` and could be stripped on the way to the server.
254 + * Clients that predate this mint at the bare path and get tickets that open either.
255 + */
256 +export const AuthWebSocketTicketUse = Schema.Literals(["rpc", "media"]);
257 +export type AuthWebSocketTicketUse = typeof AuthWebSocketTicketUse.Type;
258 +
259 +export const AuthWebSocketTicketParams = Schema.Struct({ use: AuthWebSocketTicketUse });
260 +
261 export const AuthPairingCredentialResult = Schema.Struct({
262 id: TrimmedNonEmptyString,
263 credential: TrimmedNonEmptyString,
packages/contracts/src/environmentHttp.ts
+9
@@ -35,6 +35,7 @@ import {
35 AuthEnvironmentScope,
36 AuthTokenExchangeRequest,
37 AuthSessionState,
38 + AuthWebSocketTicketParams,
39 AuthWebSocketTicketResult,
40 ServerAuthSessionMethod,
41 } from "./auth.ts";
@@ -562,6 +563,14 @@ class EnvironmentAuthHttpApi extends HttpApiGroup.make("auth")
563 error: [EnvironmentInternalError],
564 }).middleware(EnvironmentAuthenticatedAuth),
565 )
566 + .add(
567 + HttpApiEndpoint.post("webSocketTicketFor", "/api/auth/websocket-ticket/:use", {
568 + headers: OptionalBearerHeaders,
569 + params: AuthWebSocketTicketParams,
570 + success: AuthWebSocketTicketResult,
571 + error: [EnvironmentInternalError],
572 + }).middleware(EnvironmentAuthenticatedAuth),
573 + )
574 .add(
575 HttpApiEndpoint.post("pairingCredential", "/api/auth/pairing-token", {
576 headers: OptionalBearerHeaders,