@devries-cameron20 / t3code Mirror · read-only / commits / e396bb2e26
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(client-runtime): direct links pair with the device key and renew themselves (#37990)

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

Julius Marminge committed Nov 18, 2026 at 12:01 UTC e396bb2e264d828977bb2dbed69b425dc272d489
19 files changed +512 -61
docs/user/remote-access.md
+4 -1
@@ -126,7 +126,10 @@ install that CA on Android as a **CA certificate** in its security settings; the
126 Android app then trusts it.
127
128 Pairing authorizes that device for future connections. Use a fresh one-time link
129 -for each new device; you do not need the original token to reconnect. Links
129 +for each new device; you do not need the original token to reconnect. A device
130 +stays signed in while you keep using it, until you revoke it in **Settings →
131 +Sharing & access** on the host. One unused for 30 days, or paired with a host
132 +older than this release, has to pair again. Links
133 created in Settings can only be copied from the client that created them while
134 its Sharing & access page stays open. If you leave or reload that page, create
135 another link to share.
packages/client-runtime/src/authorization/layer.test.ts
+145 -1
@@ -20,7 +20,12 @@ import * as RpcHttp from "../rpc/http.ts";
20 import * as ClientCapabilities from "../platform/capabilities.ts";
21 import * as RemoteEnvironmentAuthorization from "./service.ts";
22 import * as TokenStore from "./tokenStore.ts";
23 -import { BearerConnectionCredential, BearerConnectionProfile } from "../connection/catalog.ts";
23 +import {
24 + BearerConnectionCredential,
25 + BearerConnectionProfile,
26 + type ConnectionCredential,
27 + DpopConnectionCredential,
28 +} from "../connection/catalog.ts";
29 import * as ConnectionCredentialStore from "../connection/credentialStore.ts";
30 import { BearerConnectionTarget } from "../connection/model.ts";
31 import * as ConnectionProfileStore from "../connection/profileStore.ts";
@@ -122,6 +127,7 @@ const makeHarness = Effect.fn("TestRemoteAuthorization.makeHarness")(function* (
127 readonly beforeBootstrap?: Effect.Effect<void, ManagedRelay.ManagedRelayClientError>;
128 readonly beforePut?: Effect.Effect<void>;
129 readonly clerkToken?: ClientCapabilities.CloudSession["Service"]["clerkToken"];
130 + readonly credentials?: ReadonlyArray<readonly [string, ConnectionCredential]>;
131 }) {
132 const tokens = yield* Ref.make(
133 new Map(
@@ -217,6 +223,7 @@ const makeHarness = Effect.fn("TestRemoteAuthorization.makeHarness")(function* (
223 deviceId: Effect.succeedSome("device-1"),
224 }),
225 Layer.succeed(TokenStore.RemoteDpopAccessTokenStore, tokenStore),
226 + ConnectionCredentialStore.layerMemory(input.credentials),
227 Layer.succeed(
228 ClientCapabilities.ClientPresentation,
229 ClientCapabilities.ClientPresentation.of({
@@ -326,6 +333,100 @@ describe("RemoteEnvironmentAuthorization", () => {
333 }),
334 );
335
336 + it.effect("renews an expired direct DPoP token with the host and keeps the renewal", () =>
337 + Effect.gen(function* () {
338 + const renewal = (init: RequestInit) => {
339 + const fields = new URLSearchParams(
340 + init.body instanceof Uint8Array ? new TextDecoder().decode(init.body) : String(init.body),
341 + );
342 + expect(fields.get("subject_token")).toBe("expired-direct-token");
343 + expect(fields.get("subject_token_type")).toBe(
344 + "urn:ietf:params:oauth:token-type:access_token",
345 + );
346 + return accessToken("renewed-direct-token");
347 + };
348 + const harness = yield* makeHarness({
349 + responses: [renewal, websocketTicket("direct-ticket")],
350 + descriptor: DESCRIPTOR,
351 + credentials: [
352 + [
353 + "direct-1",
354 + new DpopConnectionCredential({
355 + accessToken: "expired-direct-token",
356 + expiresAtEpochMs: 0,
357 + }),
358 + ],
359 + ],
360 + });
361 +
362 + const [authorized, stored] = yield* Effect.gen(function* () {
363 + const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
364 + const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
365 + const authorized = yield* remote.authorizeDirectDpop({
366 + expectedEnvironmentId: ENVIRONMENT_ID,
367 + connectionId: "direct-1",
368 + httpBaseUrl: ENDPOINT.httpBaseUrl,
369 + wsBaseUrl: ENDPOINT.wsBaseUrl,
370 + });
371 + return [authorized, yield* credentials.get("direct-1")] as const;
372 + }).pipe(Effect.provide(harness.layer));
373 +
374 + expect(authorized.socketUrl).toContain("wsTicket=direct-ticket");
375 + expect(authorized.httpAuthorization).toMatchObject({
376 + _tag: "Dpop",
377 + accessToken: "renewed-direct-token",
378 + directConnection: { connectionId: "direct-1", httpBaseUrl: ENDPOINT.httpBaseUrl },
379 + });
380 + expect(Option.getOrThrow(stored)).toMatchObject({
381 + _tag: "DpopConnectionCredential",
382 + accessToken: "renewed-direct-token",
383 + });
384 + expect((yield* Ref.get(harness.proofInputs)).map((proof) => proof.url)).toEqual([
385 + `${ENDPOINT.httpBaseUrl}/oauth/token`,
386 + `${ENDPOINT.httpBaseUrl}/api/auth/websocket-ticket/rpc`,
387 + `${ENDPOINT.httpBaseUrl}/ws`,
388 + ]);
389 + }),
390 + );
391 +
392 + it.effect("renews another direct host while the first host is unresponsive", () =>
393 + Effect.gen(function* () {
394 + const started = Promise.withResolvers<void>();
395 + const release = Promise.withResolvers<Response>();
396 + const first = { connectionId: "direct-1", httpBaseUrl: ENDPOINT.httpBaseUrl };
397 + const second = { connectionId: "direct-2", httpBaseUrl: "https://other.example.test" };
398 + const harness = yield* makeHarness({
399 + responses: [
400 + () => {
401 + started.resolve();
402 + return release.promise;
403 + },
404 + () => accessToken("renewed-second-token"),
405 + ],
406 + credentials: [first, second].map(({ connectionId }) => [
407 + connectionId,
408 + new DpopConnectionCredential({ accessToken: connectionId, expiresAtEpochMs: 0 }),
409 + ]),
410 + });
411 +
412 + yield* Effect.gen(function* () {
413 + const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
414 + const pending = yield* remote.authorizeDirectDpopHttp(first).pipe(Effect.forkScoped);
415 + yield* Effect.promise(() => started.promise);
416 + const healthy = yield* remote
417 + .authorizeDirectDpopHttp(second)
418 + .pipe(Effect.timeoutOption("1 second"), Effect.forkScoped);
419 + yield* TestClock.adjust("1 second");
420 + expect(yield* Fiber.join(healthy)).toMatchObject({
421 + _tag: "Some",
422 + value: { accessToken: "renewed-second-token" },
423 + });
424 + release.resolve(accessToken("renewed-first-token"));
425 + expect((yield* Fiber.join(pending)).accessToken).toBe("renewed-first-token");
426 + }).pipe(Effect.scoped, Effect.provide(Layer.merge(harness.layer, TestClock.layer())));
427 + }),
428 + );
429 +
430 it.effect("reuses a matching descriptor a check just read, once, while fresh", () =>
431 Effect.gen(function* () {
432 const descriptor = {
@@ -784,6 +885,49 @@ describe("RemoteEnvironmentAuthorization", () => {
885 }),
886 );
887
888 + it.effect("keeps renewing a direct socket after a failed renewal past token expiry", () =>
889 + Effect.gen(function* () {
890 + let markLoopRenewal = () => {};
891 + const loopRenewed = new Promise<void>((resolve) => (markLoopRenewal = resolve));
892 + const connection = { connectionId: "direct-1", httpBaseUrl: ENDPOINT.httpBaseUrl };
893 + const harness = yield* makeHarness({
894 + responses: [
895 + () => Promise.reject(new TypeError("network down")),
896 + () => {
897 + markLoopRenewal();
898 + return accessToken("renewed-direct-token");
899 + },
900 + ],
901 + credentials: [
902 + [
903 + "direct-1",
904 + new DpopConnectionCredential({ accessToken: "direct-token", expiresAtEpochMs: 1_000 }),
905 + ],
906 + ],
907 + });
908 +
909 + const renewed = yield* Effect.gen(function* () {
910 + const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
911 + yield* remote
912 + .renewDpopBeforeExpiry({
913 + expectedEnvironmentId: ENVIRONMENT_ID,
914 + expiresAtEpochMs: 1_000,
915 + directConnection: connection,
916 + })
917 + .pipe(Effect.forkScoped);
918 + // The first try, at 5 s, is already past the token's expiry and fails.
919 + yield* TestClock.adjust(5_000);
920 + // The host keeps a direct socket for its session's window, so the loop tries again.
921 + yield* TestClock.adjust(60_000);
922 + yield* Effect.promise(() => loopRenewed);
923 + // Waits behind the loop's renewal and reads what it stored, with no request of its own.
924 + return yield* remote.authorizeDirectDpopHttp(connection);
925 + }).pipe(Effect.scoped, Effect.provide(Layer.merge(harness.layer, TestClock.layer())));
926 +
927 + expect(renewed.accessToken).toBe("renewed-direct-token");
928 + }),
929 + );
930 +
931 it.effect("evicts an auth-invalid cached token and obtains a fresh bootstrap", () =>
932 Effect.gen(function* () {
933 const cached = new TokenStore.RemoteDpopAccessToken({
packages/client-runtime/src/authorization/remote.ts
+3 -1
@@ -118,6 +118,8 @@ export const exchangeRemoteDpopAccessToken = Effect.fn(
118 )(function* (input: {
119 readonly httpBaseUrl: string;
120 readonly credential: string;
121 + /** An access token renews its own session on hosts that advertise `accessTokenRenewal`. */
122 + readonly credentialType?: typeof AuthEnvironmentBootstrapTokenType | typeof AuthAccessTokenType;
123 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
124 readonly clientMetadata?: AuthClientPresentationMetadata;
125 readonly dpopProof: string;
@@ -132,7 +134,7 @@ export const exchangeRemoteDpopAccessToken = Effect.fn(
134 payload: {
135 grant_type: AuthTokenExchangeGrantType,
136 subject_token: input.credential,
135 - subject_token_type: AuthEnvironmentBootstrapTokenType,
137 + subject_token_type: input.credentialType ?? AuthEnvironmentBootstrapTokenType,
138 requested_token_type: AuthAccessTokenType,
139 ...(input.scopes ? { scope: encodeOAuthScope(input.scopes) } : {}),
140 ...clientMetadataTokenExchangeFields(input.clientMetadata),
packages/client-runtime/src/authorization/service.ts
+158 -8
@@ -1,12 +1,14 @@
1 import { msg } from "gt-i18n";
2 import { translatableDetail } from "../errors/translatable.ts";
3 import {
4 + AuthAccessTokenType,
5 connectDeviceVerificationCode,
6 type ClientConnectionMethod,
7 EnvironmentId,
8 type ExecutionEnvironmentDescriptor,
9 } from "@t3tools/contracts";
10 import { RelayEnvironmentConnectScope } from "@t3tools/contracts/relay";
11 +import * as KeyedLock from "@t3tools/shared/KeyedLock";
12 import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
13 import {
14 exchangeRemoteDpopAccessToken,
@@ -15,15 +17,19 @@ import {
17 resolveRemoteWebSocketConnectionUrl,
18 } from "./remote.ts";
19 import {
20 + credentialMissingError,
21 environmentMismatchError,
22 mapManagedRelayError,
23 mapRemoteDpopEnvironmentError,
24 mapRemoteEnvironmentError,
25 } from "../connection/errors.ts";
26 +import { DpopConnectionCredential } from "../connection/catalog.ts";
27 +import * as ConnectionCredentialStore from "../connection/credentialStore.ts";
28 import {
29 ConnectionBlockedError,
30 ConnectionTransientError,
31 type ConnectionAttemptError,
32 + type DirectDpopConnection,
33 } from "../connection/model.ts";
34 import { isNearbyAddress } from "../connection/routes.ts";
35 import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
@@ -82,6 +88,20 @@ export class RemoteEnvironmentAuthorization extends Context.Service<
88 */
89 readonly directEndpoint?: { readonly httpBaseUrl: string; readonly wsBaseUrl: string };
90 }) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
91 + /** A saved address paired with this device's DPoP key, which renews with the host itself. */
92 + readonly authorizeDirectDpop: (input: {
93 + readonly expectedEnvironmentId: EnvironmentId;
94 + readonly connectionId: string;
95 + readonly httpBaseUrl: string;
96 + readonly wsBaseUrl: string;
97 + }) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
98 + readonly authorizeDirectDpopHttp: (
99 + connection: DirectDpopConnection,
100 + rejectedAccessToken?: string,
101 + ) => Effect.Effect<
102 + Extract<PreparedHttpAuthorization, { readonly _tag: "Dpop" }>,
103 + ConnectionAttemptError
104 + >;
105 readonly authorizeDpopHttp: (input: {
106 readonly expectedEnvironmentId: EnvironmentId;
107 readonly rejectedAccessToken?: string;
@@ -102,7 +122,8 @@ export class RemoteEnvironmentAuthorization extends Context.Service<
122 readonly renewDpopBeforeExpiry: (input: {
123 readonly expectedEnvironmentId: EnvironmentId;
124 readonly expiresAtEpochMs: number;
105 - }) => Effect.Effect<void, ConnectionBlockedError>;
125 + readonly directConnection?: DirectDpopConnection;
126 + }) => Effect.Effect<void, ConnectionAttemptError>;
127 }
128 >()("@t3tools/client-runtime/authorization/service/RemoteEnvironmentAuthorization") {}
129
@@ -161,8 +182,10 @@ export const make = Effect.gen(function* () {
182 const deviceIdentity = yield* ClientCapabilities.RelayDeviceIdentity;
183 const presentation = yield* ClientCapabilities.ClientPresentation;
184 const tokenStore = yield* TokenStore.RemoteDpopAccessTokenStore;
185 + const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
186 const httpClient = yield* HttpClient.HttpClient;
187 const tokenLock = yield* Semaphore.make(1);
188 + const directTokenLocks = yield* KeyedLock.make<string>();
189 const tokenOwners = new Map<
190 EnvironmentId,
191 { readonly accessToken: string; readonly identity: ClientCapabilities.CloudSessionIdentity }
@@ -529,6 +552,120 @@ export const make = Effect.gen(function* () {
552 return { ...issued, fromCache: selected.fromCache, identity };
553 });
554
555 + const proofError = (detail: string) => () =>
556 + new ConnectionBlockedError({ reason: "configuration", ...translatableDetail(detail) });
557 +
558 + // Requests for the same credential share a renewal without waiting on other hosts.
559 + const directDpopToken = Effect.fn("clientRuntime.connection.remote.directDpopToken")(function* (
560 + connection: DirectDpopConnection,
561 + rejectedAccessToken?: string,
562 + ) {
563 + return yield* directTokenLocks.withLock(
564 + connection.connectionId,
565 + Effect.gen(function* () {
566 + const stored = yield* credentials.get(connection.connectionId);
567 + if (Option.isNone(stored) || stored.value._tag !== "DpopConnectionCredential") {
568 + return yield* credentialMissingError(connection.connectionId);
569 + }
570 + const current = stored.value;
571 + const now = yield* Clock.currentTimeMillis;
572 + if (
573 + current.accessToken !== rejectedAccessToken &&
574 + current.expiresAtEpochMs - DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS > now
575 + ) {
576 + return current;
577 + }
578 + const proof = yield* signer
579 + .createProof({
580 + method: "POST",
581 + url: environmentEndpointUrl(connection.httpBaseUrl, "/oauth/token"),
582 + })
583 + .pipe(
584 + Effect.mapError(
585 + proofError(msg("Could not create the environment authorization proof.")),
586 + ),
587 + );
588 + const access = yield* exchangeRemoteDpopAccessToken({
589 + httpBaseUrl: connection.httpBaseUrl,
590 + credential: current.accessToken,
591 + credentialType: AuthAccessTokenType,
592 + dpopProof: proof,
593 + }).pipe(
594 + Effect.mapError((error) => mapRemoteDpopEnvironmentError(error, "direct")),
595 + Effect.provideService(HttpClient.HttpClient, httpClient),
596 + Effect.withSpan("environment.authorization.directRenewal"),
597 + );
598 + const renewed = new DpopConnectionCredential({
599 + accessToken: access.access_token,
600 + expiresAtEpochMs: (yield* Clock.currentTimeMillis) + access.expires_in * 1_000,
601 + });
602 + yield* credentials.put(connection.connectionId, renewed);
603 + return renewed;
604 + }),
605 + );
606 + });
607 +
608 + const directHttpAuthorization = (
609 + connection: DirectDpopConnection,
610 + credential: DpopConnectionCredential,
611 + ) =>
612 + ({
613 + _tag: "Dpop",
614 + accessToken: credential.accessToken,
615 + expiresAtEpochMs: credential.expiresAtEpochMs,
616 + directConnection: connection,
617 + }) as const;
618 +
619 + const authorizeDirectDpop = Effect.fn("clientRuntime.connection.remote.authorizeDirectDpop")(
620 + function* (
621 + input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDirectDpop"]>[0],
622 + ) {
623 + const descriptor = yield* verifyDirectEndpoint({
624 + expectedEnvironmentId: input.expectedEnvironmentId,
625 + httpBaseUrl: input.httpBaseUrl,
626 + connectionMethod: "direct",
627 + });
628 + const connection = { connectionId: input.connectionId, httpBaseUrl: input.httpBaseUrl };
629 + const openSocket = (credential: DpopConnectionCredential) =>
630 + resolveRemoteDpopWebSocketConnectionUrl({
631 + wsBaseUrl: input.wsBaseUrl,
632 + httpBaseUrl: input.httpBaseUrl,
633 + accessToken: credential.accessToken,
634 + createProof: (proof) =>
635 + signer
636 + .createProof(proof)
637 + .pipe(
638 + Effect.mapError(
639 + proofError(msg("Could not create the websocket authorization proof.")),
640 + ),
641 + ),
642 + clientMetadata: presentation.metadata,
643 + connectionMethod: "direct",
644 + }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient), Effect.result);
645 + let credential = yield* directDpopToken(connection);
646 + let socket = yield* openSocket(credential);
647 + // A token the host refuses before its expiry, such as after a clock jump, renews once.
648 + if (Result.isFailure(socket) && socket.failure._tag === "EnvironmentAuthInvalidError") {
649 + credential = yield* directDpopToken(connection, credential.accessToken);
650 + socket = yield* openSocket(credential);
651 + }
652 + if (Result.isFailure(socket)) {
653 + const failure = socket.failure;
654 + return yield* failure._tag === "ConnectionBlockedError"
655 + ? failure
656 + : mapRemoteDpopEnvironmentError(failure, "direct");
657 + }
658 + return {
659 + environmentId: descriptor.environmentId,
660 + label: descriptor.label,
661 + httpBaseUrl: input.httpBaseUrl,
662 + socketUrl: socket.success,
663 + descriptor,
664 + httpAuthorization: directHttpAuthorization(connection, credential),
665 + };
666 + },
667 + );
668 +
669 const httpAuthorization = (
670 token: TokenStore.RemoteDpopAccessToken,
671 httpBaseUrl = token.endpoint.httpBaseUrl,
@@ -629,6 +766,13 @@ export const make = Effect.gen(function* () {
766 authorizeDpop: Effect.fn("environment.authorization")(function (input) {
767 return authorizeDpop(input);
768 }),
769 + authorizeDirectDpop,
770 + authorizeDirectDpopHttp: Effect.fn("environment.authorization.directHttp")(
771 + function* (connection, rejectedAccessToken) {
772 + const credential = yield* directDpopToken(connection, rejectedAccessToken);
773 + return directHttpAuthorization(connection, credential);
774 + },
775 + ),
776 // The relay tracer must wrap span creation, not just the token request.
777 authorizeDpopHttp: Effect.fnUntraced(function* (input) {
778 return yield* getDpopToken(input).pipe(
@@ -639,19 +783,25 @@ export const make = Effect.gen(function* () {
783 }),
784 // Untraced: a span here would stay open for the socket's lifetime. Each renewal has its own.
785 renewDpopBeforeExpiry: Effect.fnUntraced(function* (input) {
786 + const direct = input.directConnection;
787 let expiresAtEpochMs = input.expiresAtEpochMs;
788 let now = yield* Clock.currentTimeMillis;
644 - // Past expiry the server has closed the socket.
645 - while (now < expiresAtEpochMs) {
789 + // Past expiry the server has closed a T3 Connect socket. A direct socket stays open for
790 + // its session's whole renewal window, so it keeps retrying until a blocked credential.
791 + while (direct !== undefined || now < expiresAtEpochMs) {
792 // getDpopToken reuses a cached token until it is within the skew of expiry.
793 // The floor spaces out retries and keeps a wall-clock jump from spinning.
794 + const floor = now < expiresAtEpochMs ? 5_000 : DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS;
795 yield* Effect.sleep(
649 - Math.max(5_000, expiresAtEpochMs - DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS - now),
796 + Math.max(floor, expiresAtEpochMs - DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS - now),
797 );
651 - const renewed = yield* getDpopToken({
652 - expectedEnvironmentId: input.expectedEnvironmentId,
653 - }).pipe(
654 - Effect.map(({ token }) => token.expiresAtEpochMs),
798 + const renewed = yield* (
799 + direct === undefined
800 + ? getDpopToken({ expectedEnvironmentId: input.expectedEnvironmentId }).pipe(
801 + Effect.map(({ token }) => token.expiresAtEpochMs),
802 + )
803 + : directDpopToken(direct).pipe(Effect.map((credential) => credential.expiresAtEpochMs))
804 + ).pipe(
805 Effect.withSpan("environment.authorization.renewSocket"),
806 withRelayClientTracing,
807 // A relay blip retries until expiry; a blocked credential ends the loop.
packages/client-runtime/src/connection/catalog.ts
+14 -2
@@ -64,7 +64,19 @@ export class BearerConnectionCredential extends Schema.TaggedClass<BearerConnect
64 },
65 ) {}
66
67 -export const ConnectionCredential = Schema.Union([BearerConnectionCredential]);
67 +/** A token bound to this device's DPoP key, which the host renews while the device uses it. */
68 +export class DpopConnectionCredential extends Schema.TaggedClass<DpopConnectionCredential>()(
69 + "DpopConnectionCredential",
70 + {
71 + accessToken: Schema.String,
72 + expiresAtEpochMs: Schema.Number,
73 + },
74 +) {}
75 +
76 +export const ConnectionCredential = Schema.Union([
77 + BearerConnectionCredential,
78 + DpopConnectionCredential,
79 +]);
80 export type ConnectionCredential = typeof ConnectionCredential.Type;
81
82 export class PrimaryConnectionRegistration extends Schema.TaggedClass<PrimaryConnectionRegistration>()(
@@ -86,7 +98,7 @@ export class BearerConnectionRegistration extends Schema.TaggedClass<BearerConne
98 {
99 target: BearerConnectionTarget,
100 profile: BearerConnectionProfile,
89 - credential: BearerConnectionCredential,
101 + credential: ConnectionCredential,
102 },
103 ) {}
104
packages/client-runtime/src/connection/credentialStore.ts
+15 -2
@@ -1,6 +1,7 @@
1 import * as Context from "effect/Context";
2 -import type * as Effect from "effect/Effect";
3 -import type * as Option from "effect/Option";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import * as Option from "effect/Option";
5
6 import type { ConnectionCredential } from "./catalog.ts";
7 import type { ConnectionAttemptError } from "./model.ts";
@@ -21,3 +22,15 @@ export class ConnectionCredentialStore extends Context.Service<
22
23 export const make = (service: ConnectionCredentialStore["Service"]) =>
24 ConnectionCredentialStore.of(service);
25 +
26 +/** A store that lives only as long as its layer, for tests and other throwaway runtimes. */
27 +export const layerMemory = (initial: Iterable<readonly [string, ConnectionCredential]> = []) =>
28 + Layer.sync(ConnectionCredentialStore, () => {
29 + const stored = new Map(initial);
30 + return make({
31 + get: (connectionId) => Effect.sync(() => Option.fromNullishOr(stored.get(connectionId))),
32 + put: (connectionId, credential) =>
33 + Effect.sync(() => void stored.set(connectionId, credential)),
34 + remove: (connectionId) => Effect.sync(() => void stored.delete(connectionId)),
35 + });
36 + });
packages/client-runtime/src/connection/driver.ts
+3
@@ -254,6 +254,9 @@ export const make = Effect.gen(function* () {
254 .renewDpopBeforeExpiry({
255 expectedEnvironmentId: prepared.environmentId,
256 expiresAtEpochMs: prepared.httpAuthorization.expiresAtEpochMs,
257 + ...(prepared.httpAuthorization.directConnection
258 + ? { directConnection: prepared.httpAuthorization.directConnection }
259 + : {}),
260 })
261 .pipe(
262 Effect.catch((error) =>
packages/client-runtime/src/connection/errors.test.ts
+20 -1
@@ -3,9 +3,14 @@ import {
3 RelayEnvironmentConnectNotAuthorizedError,
4 RelayEnvironmentEndpointTimedOutError,
5 } from "@t3tools/contracts/relay";
6 +import { EnvironmentAuthInvalidError } from "@t3tools/contracts";
7 import { describe, expect, it } from "@effect/vitest";
8
8 -import { mapManagedRelayError, mapRemoteDpopEnvironmentError } from "./errors.ts";
9 +import {
10 + isHostCredentialRefusal,
11 + mapManagedRelayError,
12 + mapRemoteDpopEnvironmentError,
13 +} from "./errors.ts";
14 import { DPOP_UNKNOWN_HINT } from "../relay/errorPresentation.ts";
15 import { ManagedRelayRequestFailedError } from "../relay/managedRelay.ts";
16 import { NETWORK_BLOCKING_HINT } from "../errors/network.ts";
@@ -104,4 +109,18 @@ describe("mapRemoteDpopEnvironmentError", () => {
109 detail: `${error.message} ${NETWORK_BLOCKING_HINT}`,
110 });
111 });
112 +
113 + it("keeps a direct host's clock refusal apart from a refused pairing", () => {
114 + const mapped = mapRemoteDpopEnvironmentError(
115 + new EnvironmentAuthInvalidError({
116 + code: "auth_invalid",
117 + reason: "invalid_credential",
118 + dpopFailureReason: "time_window",
119 + traceId: "trace-clock",
120 + }),
121 + "direct",
122 + );
123 + expect(mapped).toMatchObject({ via: "direct", failureCause: "clock_skew" });
124 + expect(isHostCredentialRefusal(mapped)).toBe(false);
125 + });
126 });
packages/client-runtime/src/connection/errors.ts
+3 -2
@@ -321,6 +321,7 @@ export function mapRemoteEnvironmentError(
321 */
322 export function mapRemoteDpopEnvironmentError(
323 error: RemoteEnvironmentAuthError,
324 + connectionMethod: "relay" | "direct" = "relay",
325 ): ConnectionAttemptError {
326 if (error._tag === "EnvironmentAuthInvalidError" && error.reason === "invalid_credential") {
327 return new ConnectionBlockedError({
@@ -330,9 +331,9 @@ export function mapRemoteDpopEnvironmentError(
331 ),
332 traceId: error.traceId,
333 hop: "server",
333 - via: "relay",
334 + via: connectionMethod,
335 ...(error.dpopFailureReason === "time_window" ? { failureCause: "clock_skew" } : {}),
336 });
337 }
337 - return mapRemoteEnvironmentError(error, "relay");
338 + return mapRemoteEnvironmentError(error, connectionMethod);
339 }
packages/client-runtime/src/connection/model.ts
+8
@@ -153,8 +153,16 @@ export type PreparedHttpAuthorization =
153 readonly _tag: "Dpop";
154 readonly accessToken: string;
155 readonly expiresAtEpochMs: number;
156 + /** Set when the token renews directly with the host instead of through T3 Connect. */
157 + readonly directConnection?: DirectDpopConnection;
158 };
159
160 +export interface DirectDpopConnection {
161 + /** The credential store key. */
162 + readonly connectionId: string;
163 + readonly httpBaseUrl: string;
164 +}
165 +
166 export interface PreparedConnection {
167 readonly environmentId: EnvironmentId;
168 readonly label: string;
packages/client-runtime/src/connection/onboarding.test.ts
+41 -3
@@ -4,7 +4,7 @@ import {
4 type AuthEnvironmentScope,
5 ORCHESTRATION_PROTOCOL_VERSION,
6 } from "@t3tools/contracts";
7 -import { describe, expect, it } from "@effect/vitest";
7 +import { assert, describe, expect, it } from "@effect/vitest";
8 import * as Effect from "effect/Effect";
9 import * as Fiber from "effect/Fiber";
10 import * as Layer from "effect/Layer";
@@ -14,6 +14,7 @@ import * as SubscriptionRef from "effect/SubscriptionRef";
14
15 import * as RpcHttp from "../rpc/http.ts";
16 import * as ClientCapabilities from "../platform/capabilities.ts";
17 +import * as ManagedRelay from "../relay/managedRelay.ts";
18 import * as Persistence from "../platform/persistence.ts";
19 import { fetchRemoteSessionState } from "../authorization/remote.ts";
20 import {
@@ -61,6 +62,7 @@ function layerPairingHttp(
62 readonly selfUpdate?: boolean;
63 readonly grantScopes?: ReadonlyArray<AuthEnvironmentScope>;
64 readonly exchangeGate?: { readonly reached: () => void; readonly release: Promise<void> };
65 + readonly accessTokenRenewal?: boolean;
66 },
67 ) {
68 const grantScopes = options?.grantScopes ?? AuthStandardClientScopes;
@@ -88,6 +90,7 @@ function layerPairingHttp(
90 capabilities: {
91 repositoryIdentity: true,
92 ...(options?.selfUpdate === true ? { serverSelfUpdate: "boot-service" } : {}),
93 + ...(options?.accessTokenRenewal === true ? { accessTokenRenewal: true } : {}),
94 },
95 }),
96 );
@@ -124,10 +127,11 @@ function layerPairingHttp(
127 ),
128 );
129 }
130 + const dpop = new Headers(init.headers).has("dpop");
131 const granted = Response.json({
128 - access_token: "bearer-token",
132 + access_token: dpop ? "dpop-token" : "bearer-token",
133 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
130 - token_type: "Bearer",
134 + token_type: dpop ? "DPoP" : "Bearer",
135 expires_in: 3600,
136 scope: sessionScopes.join(" "),
137 });
@@ -552,6 +556,7 @@ describe("connection onboarding", () => {
556 pairingCode: "pairing-token",
557 });
558
559 + assert(registration.credential._tag === "BearerConnectionCredential");
560 const session = yield* fetchRemoteSessionState({
561 httpBaseUrl: registration.profile.httpBaseUrl,
562 bearerToken: registration.credential.token,
@@ -562,6 +567,39 @@ describe("connection onboarding", () => {
567 }).pipe(Effect.provide(layerPairingOnboarding({ grantScopes: scopes }))),
568 );
569
570 + it.effect.each([
571 + { name: "a host that renews, with a device key", renews: true, signer: true, dpop: true },
572 + { name: "a host that renews, without a device key", renews: true, signer: false, dpop: false },
573 + { name: "an older host, with a device key", renews: false, signer: true, dpop: false },
574 + ])("pairs with $name as DPoP: $dpop", ({ renews, signer, dpop }) =>
575 + Effect.gen(function* () {
576 + const registration = yield* preparePairingRegistration({
577 + host: "remote.example.test",
578 + pairingCode: "pairing-token",
579 + });
580 + expect(registration.credential).toMatchObject(
581 + dpop
582 + ? { _tag: "DpopConnectionCredential", accessToken: "dpop-token" }
583 + : { _tag: "BearerConnectionCredential", token: "bearer-token" },
584 + );
585 + }).pipe(
586 + Effect.provide(
587 + Layer.merge(
588 + layerPairingOnboarding({ accessTokenRenewal: renews }),
589 + signer
590 + ? Layer.succeed(
591 + ManagedRelay.ManagedRelayDpopSigner,
592 + ManagedRelay.ManagedRelayDpopSigner.of({
593 + thumbprint: Effect.succeed("device-key"),
594 + createProof: (proof) => Effect.succeed(`proof:${proof.url}`),
595 + }),
596 + )
597 + : Layer.empty,
598 + ),
599 + ),
600 + ),
601 + );
602 +
603 it.effect("refuses to add a route that reaches a different machine, keeping the code", () =>
604 Effect.gen(function* () {
605 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
packages/client-runtime/src/connection/onboarding.ts
+40 -4
@@ -2,6 +2,7 @@ import { msg } from "gt-i18n";
2 import { detailFromError, translatableDetail } from "../errors/translatable.ts";
3 import type { DesktopSshEnvironmentTarget, EnvironmentId } from "@t3tools/contracts";
4 import { resolveRemotePairingTarget } from "@t3tools/shared/remote";
5 +import * as Clock from "effect/Clock";
6 import * as Context from "effect/Context";
7 import * as Effect from "effect/Effect";
8 import * as Layer from "effect/Layer";
@@ -10,16 +11,25 @@ import * as Schema from "effect/Schema";
11 import * as SubscriptionRef from "effect/SubscriptionRef";
12 import * as HttpClient from "effect/http/HttpClient";
13
13 -import { bootstrapRemoteBearerSession } from "../authorization/remote.ts";
14 -import { deriveWsBaseUrl, normalizeHttpBaseUrl } from "../environment/endpoint.ts";
14 +import {
15 + bootstrapRemoteBearerSession,
16 + exchangeRemoteDpopAccessToken,
17 +} from "../authorization/remote.ts";
18 +import {
19 + deriveWsBaseUrl,
20 + environmentEndpointUrl,
21 + normalizeHttpBaseUrl,
22 +} from "../environment/endpoint.ts";
23 import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
24 import * as ClientCapabilities from "../platform/capabilities.ts";
25 +import * as ManagedRelay from "../relay/managedRelay.ts";
26 import {
27 BearerConnectionCredential,
28 BearerConnectionProfile,
29 BearerConnectionRegistration,
30 type ConnectionCatalogEntry,
31 type ConnectionCredential,
32 + DpopConnectionCredential,
33 SshConnectionProfile,
34 SshConnectionRegistration,
35 } from "./catalog.ts";
@@ -147,6 +157,33 @@ export const preparePairingRegistration = Effect.fn(
157 if (compatibilityError !== null && compatibilityError.serverUpdateRequired !== true) {
158 return yield* compatibilityError;
159 }
160 + // A key-bound session renews itself, but only on a host that can renew it. The proof is made
161 + // before the one-time code is sent, so a device that cannot sign keeps the code for bearer.
162 + const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
163 + const dpopProof =
164 + descriptor.capabilities.accessTokenRenewal === true && Option.isSome(signer)
165 + ? yield* signer.value
166 + .createProof({
167 + method: "POST",
168 + url: environmentEndpointUrl(target.httpBaseUrl, "/oauth/token"),
169 + })
170 + .pipe(Effect.option)
171 + : Option.none<string>();
172 + if (Option.isSome(dpopProof)) {
173 + const access = yield* exchangeRemoteDpopAccessToken({
174 + httpBaseUrl: target.httpBaseUrl,
175 + credential: target.credential,
176 + clientMetadata: presentation.metadata,
177 + dpopProof: dpopProof.value,
178 + }).pipe(Effect.mapError(mapRemoteEnvironmentError));
179 + return new BearerConnectionRegistration({
180 + ...route,
181 + credential: new DpopConnectionCredential({
182 + accessToken: access.access_token,
183 + expiresAtEpochMs: (yield* Clock.currentTimeMillis) + access.expires_in * 1_000,
184 + }),
185 + });
186 + }
187 const access = yield* bootstrapRemoteBearerSession({
188 httpBaseUrl: target.httpBaseUrl,
189 credential: target.credential,
@@ -177,7 +214,6 @@ const registerPairingConnection = Effect.fn(
214 return registration.target.environmentId;
215 });
216
180 -const isBearerCredential = Schema.is(BearerConnectionCredential);
217 const isBearerProfile = Schema.is(BearerConnectionProfile);
218
219 const updateBearerConnection = Effect.fn(
@@ -227,7 +263,7 @@ export const prepareBearerConnectionUpdate = Effect.fn(
263 }
264
265 const credential = options.credential;
230 - if (Option.isNone(credential) || !isBearerCredential(credential.value)) {
266 + if (Option.isNone(credential)) {
267 return yield* new ConnectionBlockedError({
268 reason: "authentication",
269 ...translatableDetail(msg("The saved bearer credential is unavailable.")),
packages/client-runtime/src/connection/registry.test.ts
+10 -7
@@ -394,9 +394,10 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
394 ...PREPARED,
395 environmentId: target.environmentId,
396 label: target.label,
397 - httpAuthorization: Option.isSome(credential)
398 - ? { _tag: "Bearer", token: credential.value.token }
399 - : null,
397 + httpAuthorization:
398 + Option.isSome(credential) && credential.value._tag === "BearerConnectionCredential"
399 + ? { _tag: "Bearer", token: credential.value.token }
400 + : null,
401 target,
402 };
403 if (options?.prepareError) return yield* options.prepareError;
@@ -1421,11 +1422,13 @@ describe("EnvironmentRegistry", () => {
1422 target._tag !== "BearerConnectionTarget" || storedCredentials === undefined
1423 ? Effect.undefined
1424 : Ref.get(storedCredentials).pipe(
1424 - Effect.map((current) =>
1425 - current.get(target.connectionId)?.token === "old-bearer"
1425 + Effect.map((current) => {
1426 + const stored = current.get(target.connectionId);
1427 + return stored?._tag === "BearerConnectionCredential" &&
1428 + stored.token === "old-bearer"
1429 ? new ConnectionBlockedError({ reason: "authentication", detail: "revoked" })
1427 - : undefined,
1428 - ),
1430 + : undefined;
1431 + }),
1432 ),
1433 });
1434 storedCredentials = harness.storedCredentials;
packages/client-runtime/src/connection/registry.ts
+5 -1
@@ -727,7 +727,11 @@ export const make = Effect.gen(function* () {
727
728 yield* installEntryLocked(entry, { retainEquivalentRuntime: true });
729
730 - if (bearerReplaced && registration._tag === "BearerConnectionRegistration") {
730 + if (
731 + bearerReplaced &&
732 + registration._tag === "BearerConnectionRegistration" &&
733 + registration.credential._tag === "BearerConnectionCredential"
734 + ) {
735 const scope = (yield* SubscriptionRef.get(serviceScopes)).get(target.environmentId);
736 if (scope !== undefined) {
737 const state = yield* SubscriptionRef.get(scope.supervisor.state);
packages/client-runtime/src/connection/resolver.test.ts
+2
@@ -108,6 +108,8 @@ const makeDependencies = Effect.fn("TestConnectionResolver.makeDependencies")((o
108 },
109 })),
110 authorizeDpopHttp: () => Effect.die("unused"),
111 + authorizeDirectDpop: () => Effect.die("unused"),
112 + authorizeDirectDpopHttp: () => Effect.die("unused"),
113 rememberCheckedDescriptor: () => Effect.void,
114 renewDpopBeforeExpiry: () => Effect.die("unused"),
115 });
packages/client-runtime/src/connection/resolver.ts
+15 -10
@@ -166,16 +166,21 @@ const makeBearerBroker = Effect.fn("clientRuntime.connection.broker.makeBearer")
166 }),
167 ),
168 );
169 - if (!isBearerCredential(credential)) {
170 - return yield* credentialMissingError(target.connectionId);
171 - }
172 - const authorized = yield* remote.authorizeBearer({
173 - expectedEnvironmentId: target.environmentId,
174 - httpBaseUrl: profile.httpBaseUrl,
175 - wsBaseUrl: profile.wsBaseUrl,
176 - bearerToken: credential.token,
177 - connectionMethod: "direct",
178 - });
169 + const authorized =
170 + credential._tag === "DpopConnectionCredential"
171 + ? yield* remote.authorizeDirectDpop({
172 + expectedEnvironmentId: target.environmentId,
173 + connectionId: credentialConnectionId(target.connectionId),
174 + httpBaseUrl: profile.httpBaseUrl,
175 + wsBaseUrl: profile.wsBaseUrl,
176 + })
177 + : yield* remote.authorizeBearer({
178 + expectedEnvironmentId: target.environmentId,
179 + httpBaseUrl: profile.httpBaseUrl,
180 + wsBaseUrl: profile.wsBaseUrl,
181 + bearerToken: credential.token,
182 + connectionMethod: "direct",
183 + });
184 return {
185 ...authorized,
186 target,
packages/client-runtime/src/connection/supervisor.test.ts
+2
@@ -21,6 +21,7 @@ import * as TestClock from "effect/testing/TestClock";
21 import * as Tracer from "effect/Tracer";
22
23 import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
24 +import * as ConnectionCredentialStore from "./credentialStore.ts";
25 import * as TokenStore from "../authorization/tokenStore.ts";
26 import * as ClientCapabilities from "../platform/capabilities.ts";
27 import * as ManagedRelay from "../relay/managedRelay.ts";
@@ -1744,6 +1745,7 @@ describe("EnvironmentSupervisor", () => {
1745 Layer.succeed(ClientCapabilities.ClientPresentation, {
1746 metadata: { label: "Test client", deviceType: "desktop" },
1747 }),
1748 + ConnectionCredentialStore.layerMemory(),
1749 ),
1750 ),
1751 );
packages/client-runtime/src/state/environmentHttpAuth.test.ts
+2
@@ -133,6 +133,8 @@ function makeHarness(reply: (requestNumber: number) => Response | Promise<Respon
133 const remoteAuthorization = RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({
134 authorizeBearer: () => Effect.die("Unexpected bearer connection preparation."),
135 authorizeDpop: () => Effect.die("HTTP requests must not prepare a WebSocket connection."),
136 + authorizeDirectDpop: () => Effect.die("HTTP requests must not prepare a WebSocket connection."),
137 + authorizeDirectDpopHttp: () => Effect.die("Unexpected direct DPoP authorization."),
138 authorizeDpopHttp: (input) =>
139 Effect.sync(() => {
140 authorizations.push(input);
packages/client-runtime/src/state/environmentHttpAuth.ts
+22 -18
@@ -198,25 +198,29 @@ const executeEnvironmentRequest = Effect.fnUntraced(function* <
198 cause: input.prepared.target._tag,
199 });
200 }
201 - const current = yield* remote.value
202 - .authorizeDpopHttp({
203 - expectedEnvironmentId: input.prepared.environmentId,
204 - ...(rejectedAccessToken === undefined ? {} : { rejectedAccessToken }),
205 - })
206 - .pipe(
207 - Effect.mapError(
208 - (cause) =>
209 - new RemoteEnvironmentAuthFetchError({
210 - ...translatableMessage(msg("Could not authorize the environment request.")),
211 - cause,
212 - }),
213 - ),
214 - );
215 - // A learned direct route keeps its own origin; only the token renews.
216 - if (input.prepared.target._tag === "RelayConnectionTarget") {
217 - httpBaseUrl = current.httpBaseUrl;
201 + const authFetchError = (cause: unknown) =>
202 + new RemoteEnvironmentAuthFetchError({
203 + ...translatableMessage(msg("Could not authorize the environment request.")),
204 + cause,
205 + });
206 + const direct = authorization.directConnection;
207 + if (direct !== undefined) {
208 + authorization = yield* remote.value
209 + .authorizeDirectDpopHttp(direct, rejectedAccessToken)
210 + .pipe(Effect.mapError(authFetchError));
211 + } else {
212 + const current = yield* remote.value
213 + .authorizeDpopHttp({
214 + expectedEnvironmentId: input.prepared.environmentId,
215 + ...(rejectedAccessToken === undefined ? {} : { rejectedAccessToken }),
216 + })
217 + .pipe(Effect.mapError(authFetchError));
218 + // A learned direct route keeps its own origin; only the token renews.
219 + if (input.prepared.target._tag === "RelayConnectionTarget") {
220 + httpBaseUrl = current.httpBaseUrl;
221 + }
222 + authorization = current.httpAuthorization;
223 }
219 - authorization = current.httpAuthorization;
224 }
225
226 const requestUrl = requestUrlFor(httpBaseUrl);