Skip to content

Commit c9b8f21

Browse files
refactor(client-runtime): decide learned routes and session reuse in one place (pingdotgg#20445)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 47683f6 commit c9b8f21

17 files changed

Lines changed: 395 additions & 52 deletions

File tree

‎apps/web/src/connection/platform.test.ts‎

Lines changed: 86 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
isRejectedSecondaryBootstrap,
2020
nextRejectedSecondaryBootstrap,
2121
primaryRegistrationToRetainAfterTopologyRead,
22+
prepareDesktopSshEnvironment,
2223
provisionDesktopSshEnvironment,
2324
readPrimaryEnvironmentTargetResult,
2425
secondaryRegistrationsToRetainAfterTopologyRead,
@@ -35,16 +36,30 @@ const TARGET: DesktopSshEnvironmentTarget = {
3536

3637
function makeBridge(
3738
calls: string[],
38-
options?: { readonly failDescriptor?: boolean },
39+
options?: {
40+
readonly failDescriptor?: boolean;
41+
readonly savedTokenRejected?: boolean;
42+
readonly savedTokenPermissions?: ReadonlyArray<string>;
43+
},
3944
): DesktopBridge {
4045
return {
41-
ensureSshEnvironment: async (target: DesktopSshEnvironmentTarget) => {
46+
ensureSshEnvironment: async (
47+
target: DesktopSshEnvironmentTarget,
48+
ensureOptions?: { issuePairingToken?: boolean },
49+
) => {
4250
calls.push("ensure");
4351
return {
4452
target,
4553
httpBaseUrl: "http://127.0.0.1:3201/",
4654
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,
4863
};
4964
},
5065
fetchSshEnvironmentDescriptor: async () => {
@@ -117,6 +132,74 @@ describe("desktop SSH pairing", () => {
117132
expect(calls).toEqual(["ensure", "descriptor"]);
118133
}),
119134
);
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+
);
120203
});
121204

122205
describe("desktop-local bearer cache", () => {

‎apps/web/src/connection/platform.ts‎

Lines changed: 56 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,61 @@ export const provisionDesktopSshEnvironment = Effect.fn(
221221
};
222222
});
223223

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+
224279
const layerCapabilities = Layer.effectContext(
225280
Effect.sync(() => {
226281
const presentation = ClientCapabilities.ClientPresentation.of({
@@ -290,28 +345,7 @@ const layerCapabilities = Layer.effectContext(
290345
detail: "SSH environments are only available in the desktop app.",
291346
});
292347
}
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);
315349
}),
316350
disconnect: Effect.fn("web.connectionPlatform.ssh.disconnect")(function* (target) {
317351
const bridge = window.desktopBridge;

‎docs/internals/remote.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,11 @@ A connected server reports the LAN and tailnet addresses it is bound to, and the
4747
client saves them as learned routes. A learned route reuses the credential of
4848
the route it was learned over: the T3 Connect access token, which is not bound
4949
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
5355
learned route still has to answer as this environment before it is used.
5456

5557
GitHub routing trust covers the whole route list. Adding or changing a route

‎docs/user/remote-access.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,12 @@ If SSH reconnecting fails after an app update, retry the launch once. Removing
179179
the connection stops a server that T3 Code launched; a server that was already
180180
running is left alone.
181181

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+
182188
For Antigravity's Google callback on a remote host, see
183189
[remote sign-in](./providers-antigravity.md#sign-in-from-a-remote-device).
184190

‎packages/client-runtime/src/connection/catalog.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,8 @@ export class SshConnectionRegistration extends Schema.TaggedClass<SshConnectionR
9595
{
9696
target: SshConnectionTarget,
9797
profile: SshConnectionProfile,
98+
/** The token from pairing over SSH, which later connects reuse. */
99+
credential: BearerConnectionCredential,
98100
},
99101
) {}
100102

‎packages/client-runtime/src/connection/driver.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,13 @@ import type {
1414
} from "./model.ts";
1515
import { ConnectionTransientError } from "./model.ts";
1616
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";
1824
import * as RpcSession from "../rpc/session.ts";
1925
import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
2026

@@ -61,7 +67,7 @@ export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")
6167
route: ConnectionRoute,
6268
) => Effect.Effect<EnvironmentConnectionLease, ConnectionAttemptError, R | Scope.Scope>,
6369
) {
64-
const routes = connectionRoutes(entry);
70+
const routes = usableRoutes(entry);
6571
const checks =
6672
routes.length === 1
6773
? []
@@ -162,7 +168,10 @@ export const make = Effect.gen(function* () {
162168
});
163169

164170
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(
166175
Effect.flatMap((check) =>
167176
check === "answered"
168177
? resolver.prepare(routeEntry(entry, route)).pipe(

‎packages/client-runtime/src/connection/onboarding.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -640,6 +640,8 @@ describe("connection onboarding", () => {
640640
connectionId: 'ssh:environment-ssh:["devbox","devbox.example.test","developer",22]',
641641
target,
642642
},
643+
// Saved so the first connect reuses this pairing instead of adding another.
644+
credential: { token: "bearer-token" },
643645
});
644646
}),
645647
);

‎packages/client-runtime/src/connection/onboarding.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,7 @@ export const prepareSshRegistration = Effect.fn(
267267
label,
268268
target: provisioned.bootstrap.target,
269269
}),
270+
credential: new BearerConnectionCredential({ token: provisioned.bearerToken }),
270271
});
271272
});
272273

‎packages/client-runtime/src/connection/outdatedHostUpdate.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,13 @@ import { isLegacyUpdateHandoffLoss, resolveServerUpdateProgressResult } from "..
2626
import * as RelayEnvironmentDiscovery from "../relay/discovery.ts";
2727
import * as ConnectionResolver from "./resolver.ts";
2828
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";
3036

3137
// A v1 host restarting into v2 runs migrations before its descriptor answers again.
3238
const OUTDATED_HOST_RESTART_TIMEOUT = Duration.minutes(4);
@@ -62,7 +68,7 @@ export const updateOutdatedHost = Effect.fn("clientRuntime.connection.updateOutd
6268
return yield* new EnvironmentRegistry.EnvironmentNotRegisteredError({ environmentId });
6369
}
6470
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))),
6672
);
6773
const capabilities = descriptor.capabilities;
6874
if (

‎packages/client-runtime/src/connection/registry.test.ts‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,7 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
216216
case "RelayConnectionRegistration":
217217
return;
218218
case "BearerConnectionRegistration":
219+
case "SshConnectionRegistration":
219220
yield* Ref.update(storedProfiles, (current) => {
220221
const next = new Map(current);
221222
next.set(registration.profile.connectionId, registration.profile);
@@ -227,12 +228,6 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
227228
return next;
228229
});
229230
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-
});
236231
}
237232
}),
238233
setRoutes: (environmentId, routes) =>
@@ -1941,6 +1936,7 @@ describe("EnvironmentRegistry routes", () => {
19411936
connectionId: other.connectionId,
19421937
target: { ...SSH_TARGET, alias: "other", hostname: "other.example.test" },
19431938
}),
1939+
credential: BEARER_CREDENTIAL,
19441940
}),
19451941
);
19461942

@@ -1969,6 +1965,7 @@ describe("EnvironmentRegistry routes", () => {
19691965
...SSH_PROFILE,
19701966
connectionId: again.connectionId,
19711967
}),
1968+
credential: BEARER_CREDENTIAL,
19721969
}),
19731970
);
19741971

0 commit comments

Comments
 (0)