Skip to content

Commit f6e4fd4

Browse files
refactor(client-runtime): decide learned routes and session reuse in one place
Learned routes only take a plain-HTTP address off the tailnet when the paired credential they borrow was itself paired over plain HTTP to a LAN or public address. A token paired over HTTPS, loopback, or the tailnet keeps to the transports it was issued for. Relay credentials are unaffected. SSH reconnects reuse their existing session instead of creating a new one. The SSH route's bearer token is now saved in the connection catalog, the resolver's SSH broker passes it to the gateway and saves whatever comes back, and the desktop gateway checks the saved session against the host (valid and holding every standard client scope) before reusing it. It pairs again only when the session is rejected or lacks a scope, and stops without pairing or sending the token when the forward reaches a different environment. Adding an environment and its first connect share one session, and removing the route drops the token. Docs: docs/user/remote-access.md describes one session per desktop and how to revoke unused ones; docs/internals/remote.md notes the plain-HTTP rule for learned routes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent f5cb328 commit f6e4fd4

16 files changed

Lines changed: 307 additions & 51 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: 61 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,13 @@ function sshPreparationError(cause: unknown) {
178178
});
179179
}
180180

181+
function differentSshMachineError(label: string) {
182+
return new ConnectionBlockedError({
183+
reason: "configuration",
184+
detail: `That host reaches ${label}, a different machine. Add it as its own environment instead.`,
185+
});
186+
}
187+
181188
export const provisionDesktopSshEnvironment = Effect.fn(
182189
"web.connectionPlatform.ssh.provisionDesktop",
183190
)(function* (
@@ -204,10 +211,7 @@ export const provisionDesktopSshEnvironment = Effect.fn(
204211
catch: sshPreparationError,
205212
});
206213
if (expectedEnvironmentId !== undefined && descriptor.environmentId !== expectedEnvironmentId) {
207-
return yield* new ConnectionBlockedError({
208-
reason: "configuration",
209-
detail: `That host reaches ${descriptor.label}, a different machine. Add it as its own environment instead.`,
210-
});
214+
return yield* differentSshMachineError(descriptor.label);
211215
}
212216
const access = yield* Effect.tryPromise({
213217
try: () => bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, pairingToken),
@@ -221,6 +225,58 @@ export const provisionDesktopSshEnvironment = Effect.fn(
221225
};
222226
});
223227

228+
/**
229+
* Connects a saved SSH environment. A token from an earlier pairing is kept
230+
* while the host still accepts it with every standard scope, because every
231+
* pairing adds a session there.
232+
*/
233+
export const prepareDesktopSshEnvironment = Effect.fn("web.connectionPlatform.ssh.prepareDesktop")(
234+
function* (
235+
bridge: DesktopBridge,
236+
input: {
237+
readonly target: DesktopSshEnvironmentTarget;
238+
readonly expectedEnvironmentId: EnvironmentId;
239+
readonly bearerToken?: string;
240+
},
241+
) {
242+
const bearerToken = input.bearerToken;
243+
if (bearerToken !== undefined) {
244+
const bootstrap = yield* Effect.tryPromise({
245+
try: () => bridge.ensureSshEnvironment(input.target, { issuePairingToken: false }),
246+
catch: sshPreparationError,
247+
});
248+
// Stop without sending the saved token, or pairing, when the forward
249+
// reaches a different environment.
250+
const descriptor = yield* Effect.tryPromise({
251+
try: () => bridge.fetchSshEnvironmentDescriptor(bootstrap.httpBaseUrl),
252+
catch: sshPreparationError,
253+
});
254+
if (descriptor.environmentId !== input.expectedEnvironmentId) {
255+
return yield* differentSshMachineError(descriptor.label);
256+
}
257+
const session = yield* Effect.tryPromise({
258+
try: () => bridge.fetchSshSessionState(bootstrap.httpBaseUrl, bearerToken),
259+
catch: sshPreparationError,
260+
});
261+
// Servers never widen a stored grant, so a token from before the standard
262+
// scopes grew is replaced by pairing again.
263+
const granted = session.permissions ?? session.scopes ?? [];
264+
if (
265+
session.authenticated &&
266+
AuthStandardClientScopes.every((scope) => granted.includes(scope))
267+
) {
268+
return { bootstrap, bearerToken };
269+
}
270+
}
271+
const provisioned = yield* provisionDesktopSshEnvironment(
272+
bridge,
273+
input.target,
274+
input.expectedEnvironmentId,
275+
);
276+
return { bootstrap: provisioned.bootstrap, bearerToken: provisioned.bearerToken };
277+
},
278+
);
279+
224280
const layerCapabilities = Layer.effectContext(
225281
Effect.sync(() => {
226282
const presentation = ClientCapabilities.ClientPresentation.of({
@@ -290,28 +346,7 @@ const layerCapabilities = Layer.effectContext(
290346
detail: "SSH environments are only available in the desktop app.",
291347
});
292348
}
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-
};
349+
return yield* prepareDesktopSshEnvironment(bridge, input);
315350
}),
316351
disconnect: Effect.fn("web.connectionPlatform.ssh.disconnect")(function* (target) {
317352
const bridge = window.desktopBridge;

‎apps/web/src/routeTree.gen.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@
44

55
// noinspection JSUnusedGlobalSymbols
66

7+
// This file was automatically generated by TanStack Router.
8+
// You should NOT make any changes in this file as it will be overwritten.
9+
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
10+
711
import { Route as rootRouteImport } from './routes/__root'
812
import { Route as WelcomeRouteImport } from './routes/welcome'
913
import { Route as UsageRouteImport } from './routes/usage'

‎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/onboarding.test.ts‎

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

‎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/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

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

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,48 @@ describe("ConnectionResolver", () => {
443443
}),
444444
);
445445

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+
446488
it.effect.each(["unchanged", "changed", "revocation-failed"] as const)(
447489
"handles %s SSH routing consent before saving or authorizing",
448490
(scenario) =>

0 commit comments

Comments
 (0)