@devries-cameron20 / t3code-1 / commits / c9b8f21bcf
Fork 0

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

refactor(client-runtime): decide learned routes and session reuse in one place (#20445)

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

Julius Marminge committed Oct 16, 2026 at 23:04 UTC c9b8f21bcfda908ed2729e2693dc56581ac18cd5
17 files changed +395 -52
apps/web/src/connection/platform.test.ts
+86 -3
@@ -19,6 +19,7 @@ import {
19 isRejectedSecondaryBootstrap,
20 nextRejectedSecondaryBootstrap,
21 primaryRegistrationToRetainAfterTopologyRead,
22 + prepareDesktopSshEnvironment,
23 provisionDesktopSshEnvironment,
24 readPrimaryEnvironmentTargetResult,
25 secondaryRegistrationsToRetainAfterTopologyRead,
@@ -35,16 +36,30 @@ const TARGET: DesktopSshEnvironmentTarget = {
36
37 function makeBridge(
38 calls: string[],
38 - options?: { readonly failDescriptor?: boolean },
39 + options?: {
40 + readonly failDescriptor?: boolean;
41 + readonly savedTokenRejected?: boolean;
42 + readonly savedTokenPermissions?: ReadonlyArray<string>;
43 + },
44 ): DesktopBridge {
45 return {
41 - ensureSshEnvironment: async (target: DesktopSshEnvironmentTarget) => {
46 + ensureSshEnvironment: async (
47 + target: DesktopSshEnvironmentTarget,
48 + ensureOptions?: { issuePairingToken?: boolean },
49 + ) => {
50 calls.push("ensure");
51 return {
52 target,
53 httpBaseUrl: "http://127.0.0.1:3201/",
54 wsBaseUrl: "ws://127.0.0.1:3201/",
47 - pairingToken: "pairing-token",
55 + pairingToken: ensureOptions?.issuePairingToken === true ? "pairing-token" : null,
56 + };
57 + },
58 + fetchSshSessionState: async () => {
59 + calls.push("session");
60 + return {
61 + authenticated: options?.savedTokenRejected !== true,
62 + permissions: options?.savedTokenPermissions ?? AuthStandardClientScopes,
63 };
64 },
65 fetchSshEnvironmentDescriptor: async () => {
@@ -117,6 +132,74 @@ describe("desktop SSH pairing", () => {
132 expect(calls).toEqual(["ensure", "descriptor"]);
133 }),
134 );
135 +
136 + it.effect("reconnects with the saved token while it holds every standard scope", () =>
137 + Effect.gen(function* () {
138 + const calls: string[] = [];
139 +
140 + const prepared = yield* prepareDesktopSshEnvironment(makeBridge(calls), {
141 + target: TARGET,
142 + expectedEnvironmentId: EnvironmentId.make("environment-ssh"),
143 + bearerToken: "saved-token",
144 + });
145 +
146 + expect(prepared.bearerToken).toBe("saved-token");
147 + expect(calls).toEqual(["ensure", "descriptor", "session"]);
148 + }),
149 + );
150 +
151 + it.effect("pairs again when the host no longer accepts the saved token", () =>
152 + Effect.gen(function* () {
153 + const calls: string[] = [];
154 +
155 + const prepared = yield* prepareDesktopSshEnvironment(
156 + makeBridge(calls, { savedTokenRejected: true }),
157 + {
158 + target: TARGET,
159 + expectedEnvironmentId: EnvironmentId.make("environment-ssh"),
160 + bearerToken: "saved-token",
161 + },
162 + );
163 +
164 + expect(prepared.bearerToken).toBe("bearer-token");
165 + expect(calls).toEqual(["ensure", "descriptor", "session", "ensure", "descriptor", "token"]);
166 + }),
167 + );
168 +
169 + it.effect("pairs again when the saved token predates a standard scope", () =>
170 + Effect.gen(function* () {
171 + const calls: string[] = [];
172 +
173 + const prepared = yield* prepareDesktopSshEnvironment(
174 + makeBridge(calls, {
175 + savedTokenPermissions: ["orchestration:read", "orchestration:operate"],
176 + }),
177 + {
178 + target: TARGET,
179 + expectedEnvironmentId: EnvironmentId.make("environment-ssh"),
180 + bearerToken: "saved-token",
181 + },
182 + );
183 +
184 + expect(prepared.bearerToken).toBe("bearer-token");
185 + expect(calls).toEqual(["ensure", "descriptor", "session", "ensure", "descriptor", "token"]);
186 + }),
187 + );
188 +
189 + it.effect("stops before sending the saved token or pairing on a different machine", () =>
190 + Effect.gen(function* () {
191 + const calls: string[] = [];
192 +
193 + const error = yield* prepareDesktopSshEnvironment(makeBridge(calls), {
194 + target: TARGET,
195 + expectedEnvironmentId: EnvironmentId.make("some-other-machine"),
196 + bearerToken: "saved-token",
197 + }).pipe(Effect.flip);
198 +
199 + expect(error).toMatchObject({ reason: "configuration" });
200 + expect(calls).toEqual(["ensure", "descriptor"]);
201 + }),
202 + );
203 });
204
205 describe("desktop-local bearer cache", () => {
apps/web/src/connection/platform.ts
+56 -22
@@ -221,6 +221,61 @@ export const provisionDesktopSshEnvironment = Effect.fn(
221 };
222 });
223
224 +/**
225 + * Connects a saved SSH environment. A token from an earlier pairing is kept
226 + * while the host still accepts it with every standard scope, because every
227 + * pairing adds a session there.
228 + */
229 +export const prepareDesktopSshEnvironment = Effect.fn("web.connectionPlatform.ssh.prepareDesktop")(
230 + function* (
231 + bridge: DesktopBridge,
232 + input: {
233 + readonly target: DesktopSshEnvironmentTarget;
234 + readonly expectedEnvironmentId: EnvironmentId;
235 + readonly bearerToken?: string;
236 + },
237 + ) {
238 + const bearerToken = input.bearerToken;
239 + if (bearerToken !== undefined) {
240 + const bootstrap = yield* Effect.tryPromise({
241 + try: () => bridge.ensureSshEnvironment(input.target, { issuePairingToken: false }),
242 + catch: sshPreparationError,
243 + });
244 + // Stop without sending the saved token, or pairing, when the forward
245 + // reaches a different environment.
246 + const descriptor = yield* Effect.tryPromise({
247 + try: () => bridge.fetchSshEnvironmentDescriptor(bootstrap.httpBaseUrl),
248 + catch: sshPreparationError,
249 + });
250 + if (descriptor.environmentId !== input.expectedEnvironmentId) {
251 + return yield* new ConnectionBlockedError({
252 + reason: "configuration",
253 + detail: `That host reaches ${descriptor.label}, a different machine. Add it as its own environment instead.`,
254 + });
255 + }
256 + const session = yield* Effect.tryPromise({
257 + try: () => bridge.fetchSshSessionState(bootstrap.httpBaseUrl, bearerToken),
258 + catch: sshPreparationError,
259 + });
260 + // Servers never widen a stored grant, so a token from before the standard
261 + // scopes grew is replaced by pairing again.
262 + const granted = session.permissions ?? session.scopes ?? [];
263 + if (
264 + session.authenticated &&
265 + AuthStandardClientScopes.every((scope) => granted.includes(scope))
266 + ) {
267 + return { bootstrap, bearerToken };
268 + }
269 + }
270 + const provisioned = yield* provisionDesktopSshEnvironment(
271 + bridge,
272 + input.target,
273 + input.expectedEnvironmentId,
274 + );
275 + return { bootstrap: provisioned.bootstrap, bearerToken: provisioned.bearerToken };
276 + },
277 +);
278 +
279 const layerCapabilities = Layer.effectContext(
280 Effect.sync(() => {
281 const presentation = ClientCapabilities.ClientPresentation.of({
@@ -290,28 +345,7 @@ const layerCapabilities = Layer.effectContext(
345 detail: "SSH environments are only available in the desktop app.",
346 });
347 }
293 - const bootstrap = yield* Effect.tryPromise({
294 - try: () =>
295 - bridge.ensureSshEnvironment(input.target, {
296 - issuePairingToken: true,
297 - }),
298 - catch: sshPreparationError,
299 - });
300 - if (bootstrap.pairingToken === null) {
301 - return yield* new ConnectionBlockedError({
302 - reason: "authentication",
303 - detail: "The SSH environment did not issue a pairing credential.",
304 - });
305 - }
306 - const access = yield* Effect.tryPromise({
307 - try: () =>
308 - bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, bootstrap.pairingToken!),
309 - catch: sshPreparationError,
310 - });
311 - return {
312 - bootstrap,
313 - bearerToken: access.access_token,
314 - };
348 + return yield* prepareDesktopSshEnvironment(bridge, input);
349 }),
350 disconnect: Effect.fn("web.connectionPlatform.ssh.disconnect")(function* (target) {
351 const bridge = window.desktopBridge;
docs/internals/remote.md
+5 -3
@@ -47,9 +47,11 @@ A connected server reports the LAN and tailnet addresses it is bound to, and the
47 client saves them as learned routes. A learned route reuses the credential of
48 the route it was learned over: the T3 Connect access token, which is not bound
49 to an origin because each DPoP proof names the URL it signs, or the paired
50 -bearer token. Learned routes the server stops reporting are dropped, which is
51 -how a changed LAN address replaces the old one; routes the user saved are never
52 -touched. The reported addresses are hints like any advertised endpoint, so a
50 +bearer token. A paired token only learns a plain HTTP address off the tailnet
51 +when it was itself paired over plain HTTP, so a token paired over HTTPS never
52 +starts travelling unencrypted. Learned routes the server stops reporting are
53 +dropped, which is how a changed LAN address replaces the old one; routes the
54 +user saved are never touched. The reported addresses are hints like any advertised endpoint, so a
55 learned route still has to answer as this environment before it is used.
56
57 GitHub routing trust covers the whole route list. Adding or changing a route
docs/user/remote-access.md
+6
@@ -179,6 +179,12 @@ If SSH reconnecting fails after an app update, retry the launch once. Removing
179 the connection stops a server that T3 Code launched; a server that was already
180 running is left alone.
181
182 +Each desktop app keeps one session on the host for its SSH connection and reuses
183 +it when it reconnects. Revoke sessions you no longer use in **Settings →
184 +Connections** on the host, or on a headless host with `t3 auth session list` and
185 +`t3 auth session revoke <id>`. A desktop that can still sign in over SSH pairs
186 +again on its next connect.
187 +
188 For Antigravity's Google callback on a remote host, see
189 [remote sign-in](./providers-antigravity.md#sign-in-from-a-remote-device).
190
packages/client-runtime/src/connection/catalog.ts
+2
@@ -95,6 +95,8 @@ export class SshConnectionRegistration extends Schema.TaggedClass<SshConnectionR
95 {
96 target: SshConnectionTarget,
97 profile: SshConnectionProfile,
98 + /** The token from pairing over SSH, which later connects reuse. */
99 + credential: BearerConnectionCredential,
100 },
101 ) {}
102
packages/client-runtime/src/connection/driver.ts
+12 -3
@@ -14,7 +14,13 @@ import type {
14 } from "./model.ts";
15 import { ConnectionTransientError } from "./model.ts";
16 import * as ConnectionResolver from "./resolver.ts";
17 -import { connectionRoutes, routeEntry, routeHttpBaseUrl } from "./routes.ts";
17 +import {
18 + connectionRoutes,
19 + routeEntry,
20 + routeHttpBaseUrl,
21 + sendsTokenInClear,
22 + usableRoutes,
23 +} from "./routes.ts";
24 import * as RpcSession from "../rpc/session.ts";
25 import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
26
@@ -61,7 +67,7 @@ export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")
67 route: ConnectionRoute,
68 ) => Effect.Effect<EnvironmentConnectionLease, ConnectionAttemptError, R | Scope.Scope>,
69 ) {
64 - const routes = connectionRoutes(entry);
70 + const routes = usableRoutes(entry);
71 const checks =
72 routes.length === 1
73 ? []
@@ -162,7 +168,10 @@ export const make = Effect.gen(function* () {
168 });
169
170 const preflight = (entry: ConnectionCatalogEntry, route: ConnectionRoute) =>
165 - checkRoute(entry, route).pipe(
171 + (sendsTokenInClear(connectionRoutes(entry), route)
172 + ? Effect.succeed("silent" as const)
173 + : checkRoute(entry, route)
174 + ).pipe(
175 Effect.flatMap((check) =>
176 check === "answered"
177 ? resolver.prepare(routeEntry(entry, route)).pipe(
packages/client-runtime/src/connection/onboarding.test.ts
+2
@@ -640,6 +640,8 @@ describe("connection onboarding", () => {
640 connectionId: 'ssh:environment-ssh:["devbox","devbox.example.test","developer",22]',
641 target,
642 },
643 + // Saved so the first connect reuses this pairing instead of adding another.
644 + credential: { token: "bearer-token" },
645 });
646 }),
647 );
packages/client-runtime/src/connection/onboarding.ts
+1
@@ -267,6 +267,7 @@ export const prepareSshRegistration = Effect.fn(
267 label,
268 target: provisioned.bootstrap.target,
269 }),
270 + credential: new BearerConnectionCredential({ token: provisioned.bearerToken }),
271 });
272 });
273
packages/client-runtime/src/connection/outdatedHostUpdate.ts
+8 -2
@@ -26,7 +26,13 @@ import { isLegacyUpdateHandoffLoss, resolveServerUpdateProgressResult } from "..
26 import * as RelayEnvironmentDiscovery from "../relay/discovery.ts";
27 import * as ConnectionResolver from "./resolver.ts";
28 import * as EnvironmentRegistry from "./registry.ts";
29 -import { connectionRoutes, hasRelayRoute, routeEntry, routeHttpBaseUrl } from "./routes.ts";
29 +import {
30 + connectionRoutes,
31 + hasRelayRoute,
32 + routeEntry,
33 + routeHttpBaseUrl,
34 + usableRoutes,
35 +} from "./routes.ts";
36
37 // A v1 host restarting into v2 runs migrations before its descriptor answers again.
38 const OUTDATED_HOST_RESTART_TIMEOUT = Duration.minutes(4);
@@ -62,7 +68,7 @@ export const updateOutdatedHost = Effect.fn("clientRuntime.connection.updateOutd
68 return yield* new EnvironmentRegistry.EnvironmentNotRegisteredError({ environmentId });
69 }
70 const { prepared, descriptor } = yield* Effect.firstSuccessOf(
65 - connectionRoutes(entry).map((route) => resolver.prepareForUpdate(routeEntry(entry, route))),
71 + usableRoutes(entry).map((route) => resolver.prepareForUpdate(routeEntry(entry, route))),
72 );
73 const capabilities = descriptor.capabilities;
74 if (
packages/client-runtime/src/connection/registry.test.ts
+3 -6
@@ -216,6 +216,7 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
216 case "RelayConnectionRegistration":
217 return;
218 case "BearerConnectionRegistration":
219 + case "SshConnectionRegistration":
220 yield* Ref.update(storedProfiles, (current) => {
221 const next = new Map(current);
222 next.set(registration.profile.connectionId, registration.profile);
@@ -227,12 +228,6 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
228 return next;
229 });
230 return;
230 - case "SshConnectionRegistration":
231 - yield* Ref.update(storedProfiles, (current) => {
232 - const next = new Map(current);
233 - next.set(registration.profile.connectionId, registration.profile);
234 - return next;
235 - });
231 }
232 }),
233 setRoutes: (environmentId, routes) =>
@@ -1941,6 +1936,7 @@ describe("EnvironmentRegistry routes", () => {
1936 connectionId: other.connectionId,
1937 target: { ...SSH_TARGET, alias: "other", hostname: "other.example.test" },
1938 }),
1939 + credential: BEARER_CREDENTIAL,
1940 }),
1941 );
1942
@@ -1969,6 +1965,7 @@ describe("EnvironmentRegistry routes", () => {
1965 ...SSH_PROFILE,
1966 connectionId: again.connectionId,
1967 }),
1968 + credential: BEARER_CREDENTIAL,
1969 }),
1970 );
1971
packages/client-runtime/src/connection/resolver.test.ts
+42
@@ -443,6 +443,48 @@ describe("ConnectionResolver", () => {
443 }),
444 );
445
446 + it.effect("offers the saved SSH token on each connect and saves the one it gets back", () =>
447 + Effect.gen(function* () {
448 + const offeredTokens = yield* Ref.make<ReadonlyArray<string | undefined>>([]);
449 + const target = new SshConnectionTarget({
450 + environmentId: ENVIRONMENT_ID,
451 + label: "SSH",
452 + connectionId: "ssh-1",
453 + });
454 + const profile = new SshConnectionProfile({
455 + connectionId: "ssh-1",
456 + environmentId: ENVIRONMENT_ID,
457 + label: "SSH",
458 + target: SSH_TARGET,
459 + });
460 + const layerBroker = yield* makeDependencies({
461 + credentials: [["ssh-1", new BearerConnectionCredential({ token: "revoked-token" })]],
462 + // The host accepts only the token it paired last; anything else pairs again.
463 + prepareSsh: (input) =>
464 + Ref.update(offeredTokens, (tokens) => [...tokens, input.bearerToken]).pipe(
465 + Effect.as({
466 + bootstrap: {
467 + target: input.target,
468 + httpBaseUrl: "http://127.0.0.1:4010",
469 + wsBaseUrl: "ws://127.0.0.1:4010",
470 + pairingToken: null,
471 + },
472 + bearerToken: "paired-token",
473 + }),
474 + ),
475 + });
476 + const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(layerBroker));
477 + const entry = catalogEntry(target, Option.some(profile));
478 +
479 + const first = yield* broker.prepare(entry);
480 + const second = yield* broker.prepare(entry);
481 +
482 + expect(yield* Ref.get(offeredTokens)).toEqual(["revoked-token", "paired-token"]);
483 + expect(first.httpAuthorization).toMatchObject({ token: "paired-token" });
484 + expect(second.httpAuthorization).toMatchObject({ token: "paired-token" });
485 + }),
486 + );
487 +
488 it.effect.each(["unchanged", "changed", "revocation-failed"] as const)(
489 "handles %s SSH routing consent before saving or authorizing",
490 (scenario) =>
packages/client-runtime/src/connection/resolver.ts
+11
@@ -200,6 +200,7 @@ const makeRelayBroker = Effect.fn("clientRuntime.connection.broker.makeRelay")(f
200
201 const makeSshBroker = Effect.fn("clientRuntime.connection.broker.makeSsh")(function* () {
202 const profiles = yield* ConnectionProfileStore.ConnectionProfileStore;
203 + const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
204 const ssh = yield* ClientCapabilities.SshEnvironmentGateway;
205 const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
206
@@ -222,11 +223,21 @@ const makeSshBroker = Effect.fn("clientRuntime.connection.broker.makeSsh")(funct
223 actual: profile.environmentId,
224 });
225 }
226 + // Each pairing adds a session on the host, so connects reuse the saved token.
227 + const saved = Option.getOrUndefined(yield* credentials.get(target.connectionId));
228 + const savedToken = saved !== undefined && isBearerCredential(saved) ? saved.token : undefined;
229 const prepared = yield* ssh.prepare({
230 connectionId: target.connectionId,
231 expectedEnvironmentId: target.environmentId,
232 target: profile.target,
233 + ...(savedToken === undefined ? {} : { bearerToken: savedToken }),
234 });
235 + if (prepared.bearerToken !== savedToken) {
236 + yield* credentials.put(
237 + target.connectionId,
238 + new BearerConnectionCredential({ token: prepared.bearerToken }),
239 + );
240 + }
241 const preparedProfile = new SshConnectionProfile({
242 connectionId: profile.connectionId,
243 environmentId: profile.environmentId,
packages/client-runtime/src/connection/routes.test.ts
+92
@@ -19,7 +19,9 @@ import {
19 mergeLearnedRoutes,
20 removedWithRelay,
21 routesAfterRemoving,
22 + sendsTokenInClear,
23 upsertRoute,
24 + usableRoutes,
25 } from "./routes.ts";
26
27 const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
@@ -51,6 +53,15 @@ const LAN = direct("lan", "http://192.168.1.10:3773/");
53 const TAILNET = direct("tailnet", "https://desk.tail1234.ts.net/");
54 const PUBLIC = direct("public", "https://desk.example.com/");
55
56 +function learned(id: string, httpBaseUrl: string): ConnectionRoute {
57 + const route = direct(id, httpBaseUrl);
58 + const profile = Option.getOrThrow(route.profile) as BearerConnectionProfile;
59 + return {
60 + target: route.target,
61 + profile: Option.some(new BearerConnectionProfile({ ...profile, learned: true })),
62 + };
63 +}
64 +
65 describe("connection routes", () => {
66 it("classifies direct routes by address", () => {
67 expect(connectionRouteKind(LAN)).toBe("lan");
@@ -236,6 +247,87 @@ describe("learned routes", () => {
247 expect(credentialConnectionId(connectionRouteId(learned.target))).toBe("lan");
248 });
249
250 + it("keeps a token paired over HTTPS off plain HTTP addresses outside the tailnet", () => {
251 + const entry = entryWithRoutes(relayOnly, [PUBLIC, RELAY]);
252 + const routes = mergeLearnedRoutes({
253 + entry,
254 + activeRoute: PUBLIC,
255 + reported: [
256 + { kind: "lan", httpBaseUrl: "http://192.168.1.10:3773/" },
257 + { kind: "tailnet", httpBaseUrl: "http://100.101.102.103:3773/" },
258 + { kind: "tailnet", httpBaseUrl: "https://desk.tail1234.ts.net/" },
259 + ],
260 + allowInsecure: true,
261 + });
262 + expect(ids(routes)).toEqual([
263 + `learned:${ENVIRONMENT_ID}:http://100.101.102.103:3773@public`,
264 + `learned:${ENVIRONMENT_ID}:https://desk.tail1234.ts.net@public`,
265 + "public",
266 + "relay",
267 + ]);
268 + });
269 +
270 + it("drops a plain HTTP LAN route learned earlier over an HTTPS-paired token", () => {
271 + const lanOrigin = "http://192.168.1.10:3773";
272 + const stale = direct(`learned:${ENVIRONMENT_ID}:${lanOrigin}@public`, `${lanOrigin}/`);
273 + const staleProfile = profileOf(stale) as BearerConnectionProfile;
274 + const learnedStale: ConnectionRoute = {
275 + target: stale.target,
276 + profile: Option.some(new BearerConnectionProfile({ ...staleProfile, learned: true })),
277 + };
278 + const routes = mergeLearnedRoutes({
279 + entry: entryWithRoutes(relayOnly, [learnedStale, PUBLIC, RELAY]),
280 + activeRoute: PUBLIC,
281 + reported: [{ kind: "lan", httpBaseUrl: `${lanOrigin}/` }],
282 + allowInsecure: true,
283 + });
284 + expect(ids(routes)).toEqual(["public", "relay"]);
285 + });
286 +
287 + it("drops a stale plain HTTP route borrowing an HTTPS-paired token while another route is active", () => {
288 + const lanOrigin = "http://10.0.0.42:3773";
289 + const stale = learned(`learned:${ENVIRONMENT_ID}:${lanOrigin}@public`, `${lanOrigin}/`);
290 + const entry = entryWithRoutes(relayOnly, [stale, PUBLIC, RELAY]);
291 + expect(sendsTokenInClear([stale, PUBLIC, RELAY], stale)).toBe(true);
292 + expect(ids(usableRoutes(entry))).toEqual(["public", "relay"]);
293 + const routes = mergeLearnedRoutes({
294 + entry,
295 + activeRoute: RELAY,
296 + reported: [{ kind: "lan", httpBaseUrl: `${lanOrigin}/` }],
297 + allowInsecure: true,
298 + });
299 + // The stale route is gone; the address is learned again with T3 Connect's credential.
300 + expect(ids(routes)).toEqual([`learned:${ENVIRONMENT_ID}:${lanOrigin}`, "public", "relay"]);
301 + expect(profileOf(routes![0]!)).toMatchObject({ authorization: "t3-connect" });
302 + });
303 +
304 + it("keeps plain HTTP routes that don't borrow the active HTTPS-paired token", () => {
305 + const lanOrigin = "http://10.0.0.42:3773";
306 + const overLan = learned(`learned:${ENVIRONMENT_ID}:${lanOrigin}@lan`, `${lanOrigin}/`);
307 + const routes = mergeLearnedRoutes({
308 + entry: entryWithRoutes(relayOnly, [overLan, LAN, PUBLIC, RELAY]),
309 + activeRoute: PUBLIC,
310 + reported: [{ kind: "lan", httpBaseUrl: `${lanOrigin}/` }],
311 + allowInsecure: true,
312 + });
313 + expect(routes).toBeNull();
314 + });
315 +
316 + it("learns plain HTTP LAN addresses over a token paired over plain HTTP", () => {
317 + const entry = entryWithRoutes(relayOnly, [LAN, RELAY]);
318 + const routes = mergeLearnedRoutes({
319 + entry,
320 + activeRoute: LAN,
321 + reported: [{ kind: "lan", httpBaseUrl: "http://10.0.0.42:3773/" }],
322 + allowInsecure: true,
323 + });
324 + expect(ids(routes)).toEqual([
325 + "lan",
326 + `learned:${ENVIRONMENT_ID}:http://10.0.0.42:3773@lan`,
327 + "relay",
328 + ]);
329 + });
330 +
331 it("skips plain HTTP from an HTTPS page and never learns loopback", () => {
332 expect(
333 mergeLearnedRoutes({
packages/client-runtime/src/connection/routes.ts
+54 -1
@@ -218,7 +218,6 @@ export function mergeLearnedRoutes(input: {
218 authorization === undefined && active._tag === "BearerConnectionTarget"
219 ? credentialConnectionId(active.connectionId)
220 : undefined;
221 -
221 const reported = new Map<string, URL>();
222 const tailscaleOrigins = new Set<string>();
223 for (const endpoint of input.reported) {
@@ -252,12 +251,21 @@ export function mergeLearnedRoutes(input: {
251 ];
252 }
253 if (url === null || !reported.has(normalized(url)) || known.has(normalized(url))) return [];
254 + if (sendsTokenInClear(saved, route, tailscaleOrigins.has(normalized(url)))) return [];
255 known.add(normalized(url));
256 return [withNetwork(route, tailscaleOrigins.has(normalized(url)))];
257 });
258 let next: ReadonlyArray<ConnectionRoute> = kept;
259 for (const url of reported.values()) {
260 if (known.has(url.origin)) continue;
261 + if (
262 + url.protocol === "http:" &&
263 + sharedCredential !== undefined &&
264 + !tailscaleOrigins.has(url.origin) &&
265 + !tokenAllowsPlainHttp(saved, sharedCredential)
266 + ) {
267 + continue;
268 + }
269 const httpBaseUrl = `${url.origin}/`;
270 const connectionId = learnedConnectionId(
271 entry.target.environmentId,
@@ -294,6 +302,51 @@ export function mergeLearnedRoutes(input: {
302 return signature(saved) === signature(next) ? null : next;
303 }
304
305 +// A paired token goes to a plain HTTP address outside the tailnet only when
306 +// it was paired that way, so a token paired over HTTPS, loopback, or the
307 +// tailnet keeps to the transports it was issued for.
308 +function tokenAllowsPlainHttp(
309 + routes: ReadonlyArray<ConnectionRoute>,
310 + credentialId: string,
311 +): boolean {
312 + const credentialRoute = routes.find((route) => connectionRouteId(route.target) === credentialId);
313 + return (
314 + credentialRoute !== undefined &&
315 + routeHttpBaseUrl(credentialRoute)?.startsWith("http:") === true &&
316 + (connectionRouteKind(credentialRoute) === "lan" ||
317 + connectionRouteKind(credentialRoute) === "public")
318 + );
319 +}
320 +
321 +/**
322 + * Whether connecting over `route` would send a paired token over plain HTTP
323 + * that it wasn't paired over. Checked against the token the route borrows,
324 + * so a route learned before this rule existed is refused too.
325 + */
326 +export function sendsTokenInClear(
327 + routes: ReadonlyArray<ConnectionRoute>,
328 + route: ConnectionRoute,
329 + tailscale?: boolean,
330 +): boolean {
331 + const profile = Option.getOrNull(route.profile);
332 + if (profile?._tag !== "BearerConnectionProfile" || profile.authorization === "t3-connect") {
333 + return false;
334 + }
335 + if ((tailscale ?? profile.network === "tailscale") || !profile.httpBaseUrl.startsWith("http:")) {
336 + return false;
337 + }
338 + const credentialId = credentialConnectionId(connectionRouteId(route.target));
339 + return (
340 + credentialId !== connectionRouteId(route.target) && !tokenAllowsPlainHttp(routes, credentialId)
341 + );
342 +}
343 +
344 +/** Routes a connect may use: none sends a paired token over plain HTTP it wasn't paired over. */
345 +export function usableRoutes(entry: ConnectionCatalogEntry): ReadonlyArray<ConnectionRoute> {
346 + const routes = connectionRoutes(entry);
347 + return routes.filter((route) => !sendsTokenInClear(routes, route));
348 +}
349 +
350 export interface ReportedEndpoint {
351 readonly httpBaseUrl: string;
352 readonly kind?: string;
packages/client-runtime/src/platform/capabilities.ts
+7
@@ -65,10 +65,17 @@ export class SshEnvironmentGateway extends Context.Service<
65 target: DesktopSshEnvironmentTarget,
66 expectedEnvironmentId?: EnvironmentId,
67 ) => Effect.Effect<ProvisionedSshEnvironment, ConnectionAttemptError>;
68 + /**
69 + * Starts or reuses the remote server for a saved connection. Returns
70 + * `bearerToken`, the token this client saved from an earlier pairing, while
71 + * the host still accepts it with the standard scopes, and pairs again only
72 + * when it does not, so a reconnect adds no session on the host.
73 + */
74 readonly prepare: (input: {
75 readonly connectionId: string;
76 readonly expectedEnvironmentId: EnvironmentId;
77 readonly target: DesktopSshEnvironmentTarget;
78 + readonly bearerToken?: string;
79 }) => Effect.Effect<PreparedSshEnvironment, ConnectionAttemptError>;
80 readonly disconnect: (
81 target: DesktopSshEnvironmentTarget,
packages/client-runtime/src/platform/storageDocument.test.ts
+7 -3
@@ -387,7 +387,7 @@ describe("ConnectionCatalogDocument", () => {
387 );
388 });
389
390 - it("persists the normalized SSH profile beside its target", () => {
390 + it("persists the normalized SSH profile and its paired token beside its target", () => {
391 const target = new SshConnectionTarget({
392 environmentId: ENVIRONMENT_ID,
393 label: "SSH",
@@ -406,12 +406,16 @@ describe("ConnectionCatalogDocument", () => {
406 });
407 const document = registerConnectionInCatalog(
408 EMPTY_CONNECTION_CATALOG_DOCUMENT,
409 - new SshConnectionRegistration({ target, profile }),
409 + new SshConnectionRegistration({ target, profile, credential: BEARER_CREDENTIAL }),
410 );
411
412 expect(document.targets).toEqual([target]);
413 expect(document.profiles).toEqual([profile]);
414 - expect(document.credentials).toEqual([]);
414 + expect(document.credentials).toEqual([
415 + { connectionId: target.connectionId, credential: BEARER_CREDENTIAL },
416 + ]);
417 + // Removing the route forgets its token too.
418 + expect(removeConnectionFromCatalog(document, ENVIRONMENT_ID).credentials).toEqual([]);
419 });
420
421 it("keeps every route of an environment and drops only a removed route's records", () => {
packages/client-runtime/src/platform/storageDocument.ts
+1 -9
@@ -133,6 +133,7 @@ export function registerConnectionInCatalog(
133 case "RelayConnectionRegistration":
134 return next;
135 case "BearerConnectionRegistration":
136 + case "SshConnectionRegistration":
137 return {
138 ...next,
139 profiles: replaceCatalogValue(
@@ -145,15 +146,6 @@ export function registerConnectionInCatalog(
146 credential: registration.credential,
147 }),
148 };
148 - case "SshConnectionRegistration":
149 - return {
150 - ...next,
151 - profiles: replaceCatalogValue(
152 - next.profiles,
153 - (value) => value.connectionId,
154 - registration.profile,
155 - ),
156 - };
149 }
150 }
151