TypeScript
refactor(client-runtime): decide learned routes and session reuse in one place (#20445)
Julius Marmingec9b8f21bcfda
diff --git a/apps/web/src/connection/platform.test.ts b/apps/web/src/connection/platform.test.tsindex b1404ac8445..d0176c239e9 100644--- a/apps/web/src/connection/platform.test.ts+++ b/apps/web/src/connection/platform.test.ts@@ -19,6 +19,7 @@ import {isRejectedSecondaryBootstrap,nextRejectedSecondaryBootstrap,primaryRegistrationToRetainAfterTopologyRead,+ prepareDesktopSshEnvironment,provisionDesktopSshEnvironment,readPrimaryEnvironmentTargetResult,secondaryRegistrationsToRetainAfterTopologyRead,@@ -35,16 +36,30 @@ const TARGET: DesktopSshEnvironmentTarget = {function makeBridge(calls: string[],- options?: { readonly failDescriptor?: boolean },+ options?: {+ readonly failDescriptor?: boolean;+ readonly savedTokenRejected?: boolean;+ readonly savedTokenPermissions?: ReadonlyArray<string>;+ },): DesktopBridge {return {- ensureSshEnvironment: async (target: DesktopSshEnvironmentTarget) => {+ ensureSshEnvironment: async (+ target: DesktopSshEnvironmentTarget,+ ensureOptions?: { issuePairingToken?: boolean },+ ) => {calls.push("ensure");return {target,httpBaseUrl: "http://127.0.0.1:3201/",wsBaseUrl: "ws://127.0.0.1:3201/",- pairingToken: "pairing-token",+ pairingToken: ensureOptions?.issuePairingToken === true ? "pairing-token" : null,+ };+ },+ fetchSshSessionState: async () => {+ calls.push("session");+ return {+ authenticated: options?.savedTokenRejected !== true,+ permissions: options?.savedTokenPermissions ?? AuthStandardClientScopes,};},fetchSshEnvironmentDescriptor: async () => {@@ -117,6 +132,74 @@ describe("desktop SSH pairing", () => {expect(calls).toEqual(["ensure", "descriptor"]);}),);++ it.effect("reconnects with the saved token while it holds every standard scope", () =>+ Effect.gen(function* () {+ const calls: string[] = [];++ const prepared = yield* prepareDesktopSshEnvironment(makeBridge(calls), {+ target: TARGET,+ expectedEnvironmentId: EnvironmentId.make("environment-ssh"),+ bearerToken: "saved-token",+ });++ expect(prepared.bearerToken).toBe("saved-token");+ expect(calls).toEqual(["ensure", "descriptor", "session"]);+ }),+ );++ it.effect("pairs again when the host no longer accepts the saved token", () =>+ Effect.gen(function* () {+ const calls: string[] = [];++ const prepared = yield* prepareDesktopSshEnvironment(+ makeBridge(calls, { savedTokenRejected: true }),+ {+ target: TARGET,+ expectedEnvironmentId: EnvironmentId.make("environment-ssh"),+ bearerToken: "saved-token",+ },+ );++ expect(prepared.bearerToken).toBe("bearer-token");+ expect(calls).toEqual(["ensure", "descriptor", "session", "ensure", "descriptor", "token"]);+ }),+ );++ it.effect("pairs again when the saved token predates a standard scope", () =>+ Effect.gen(function* () {+ const calls: string[] = [];++ const prepared = yield* prepareDesktopSshEnvironment(+ makeBridge(calls, {+ savedTokenPermissions: ["orchestration:read", "orchestration:operate"],+ }),+ {+ target: TARGET,+ expectedEnvironmentId: EnvironmentId.make("environment-ssh"),+ bearerToken: "saved-token",+ },+ );++ expect(prepared.bearerToken).toBe("bearer-token");+ expect(calls).toEqual(["ensure", "descriptor", "session", "ensure", "descriptor", "token"]);+ }),+ );++ it.effect("stops before sending the saved token or pairing on a different machine", () =>+ Effect.gen(function* () {+ const calls: string[] = [];++ const error = yield* prepareDesktopSshEnvironment(makeBridge(calls), {+ target: TARGET,+ expectedEnvironmentId: EnvironmentId.make("some-other-machine"),+ bearerToken: "saved-token",+ }).pipe(Effect.flip);++ expect(error).toMatchObject({ reason: "configuration" });+ expect(calls).toEqual(["ensure", "descriptor"]);+ }),+ );});describe("desktop-local bearer cache", () => {diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.tsindex 4fd0bf76f46..0f3a263f611 100644--- a/apps/web/src/connection/platform.ts+++ b/apps/web/src/connection/platform.ts@@ -221,6 +221,61 @@ export const provisionDesktopSshEnvironment = Effect.fn(};});+/**+ * Connects a saved SSH environment. A token from an earlier pairing is kept+ * while the host still accepts it with every standard scope, because every+ * pairing adds a session there.+ */+export const prepareDesktopSshEnvironment = Effect.fn("web.connectionPlatform.ssh.prepareDesktop")(+ function* (+ bridge: DesktopBridge,+ input: {+ readonly target: DesktopSshEnvironmentTarget;+ readonly expectedEnvironmentId: EnvironmentId;+ readonly bearerToken?: string;+ },+ ) {+ const bearerToken = input.bearerToken;+ if (bearerToken !== undefined) {+ const bootstrap = yield* Effect.tryPromise({+ try: () => bridge.ensureSshEnvironment(input.target, { issuePairingToken: false }),+ catch: sshPreparationError,+ });+ // Stop without sending the saved token, or pairing, when the forward+ // reaches a different environment.+ const descriptor = yield* Effect.tryPromise({+ try: () => bridge.fetchSshEnvironmentDescriptor(bootstrap.httpBaseUrl),+ catch: sshPreparationError,+ });+ if (descriptor.environmentId !== input.expectedEnvironmentId) {+ return yield* new ConnectionBlockedError({+ reason: "configuration",+ detail: `That host reaches ${descriptor.label}, a different machine. Add it as its own environment instead.`,+ });+ }+ const session = yield* Effect.tryPromise({+ try: () => bridge.fetchSshSessionState(bootstrap.httpBaseUrl, bearerToken),+ catch: sshPreparationError,+ });+ // Servers never widen a stored grant, so a token from before the standard+ // scopes grew is replaced by pairing again.+ const granted = session.permissions ?? session.scopes ?? [];+ if (+ session.authenticated &&+ AuthStandardClientScopes.every((scope) => granted.includes(scope))+ ) {+ return { bootstrap, bearerToken };+ }+ }+ const provisioned = yield* provisionDesktopSshEnvironment(+ bridge,+ input.target,+ input.expectedEnvironmentId,+ );+ return { bootstrap: provisioned.bootstrap, bearerToken: provisioned.bearerToken };+ },+);+const layerCapabilities = Layer.effectContext(Effect.sync(() => {const presentation = ClientCapabilities.ClientPresentation.of({@@ -290,28 +345,7 @@ const layerCapabilities = Layer.effectContext(detail: "SSH environments are only available in the desktop app.",});}- const bootstrap = yield* Effect.tryPromise({- try: () =>- bridge.ensureSshEnvironment(input.target, {- issuePairingToken: true,- }),- catch: sshPreparationError,- });- if (bootstrap.pairingToken === null) {- return yield* new ConnectionBlockedError({- reason: "authentication",- detail: "The SSH environment did not issue a pairing credential.",- });- }- const access = yield* Effect.tryPromise({- try: () =>- bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, bootstrap.pairingToken!),- catch: sshPreparationError,- });- return {- bootstrap,- bearerToken: access.access_token,- };+ return yield* prepareDesktopSshEnvironment(bridge, input);}),disconnect: Effect.fn("web.connectionPlatform.ssh.disconnect")(function* (target) {const bridge = window.desktopBridge;diff --git a/docs/internals/remote.md b/docs/internals/remote.mdindex 3f9e64b03cf..5fcec03bbaf 100644--- a/docs/internals/remote.md+++ b/docs/internals/remote.md@@ -47,9 +47,11 @@ A connected server reports the LAN and tailnet addresses it is bound to, and theclient saves them as learned routes. A learned route reuses the credential ofthe route it was learned over: the T3 Connect access token, which is not boundto an origin because each DPoP proof names the URL it signs, or the paired-bearer token. Learned routes the server stops reporting are dropped, which is-how a changed LAN address replaces the old one; routes the user saved are never-touched. The reported addresses are hints like any advertised endpoint, so a+bearer token. A paired token only learns a plain HTTP address off the tailnet+when it was itself paired over plain HTTP, so a token paired over HTTPS never+starts travelling unencrypted. Learned routes the server stops reporting are+dropped, which is how a changed LAN address replaces the old one; routes the+user saved are never touched. The reported addresses are hints like any advertised endpoint, so alearned route still has to answer as this environment before it is used.GitHub routing trust covers the whole route list. Adding or changing a routediff --git a/docs/user/remote-access.md b/docs/user/remote-access.mdindex 72af4583501..6ba7a63ef27 100644--- a/docs/user/remote-access.md+++ b/docs/user/remote-access.md@@ -179,6 +179,12 @@ If SSH reconnecting fails after an app update, retry the launch once. Removingthe connection stops a server that T3 Code launched; a server that was alreadyrunning is left alone.+Each desktop app keeps one session on the host for its SSH connection and reuses+it when it reconnects. Revoke sessions you no longer use in **Settings →+Connections** on the host, or on a headless host with `t3 auth session list` and+`t3 auth session revoke <id>`. A desktop that can still sign in over SSH pairs+again on its next connect.+For Antigravity's Google callback on a remote host, see[remote sign-in](./providers-antigravity.md#sign-in-from-a-remote-device).diff --git a/packages/client-runtime/src/connection/catalog.ts b/packages/client-runtime/src/connection/catalog.tsindex 6ef20741078..17065b8a486 100644--- a/packages/client-runtime/src/connection/catalog.ts+++ b/packages/client-runtime/src/connection/catalog.ts@@ -95,6 +95,8 @@ export class SshConnectionRegistration extends Schema.TaggedClass<SshConnectionR{target: SshConnectionTarget,profile: SshConnectionProfile,+ /** The token from pairing over SSH, which later connects reuse. */+ credential: BearerConnectionCredential,},) {}diff --git a/packages/client-runtime/src/connection/driver.ts b/packages/client-runtime/src/connection/driver.tsindex 5f5f233dedf..c4e6486da2f 100644--- a/packages/client-runtime/src/connection/driver.ts+++ b/packages/client-runtime/src/connection/driver.ts@@ -14,7 +14,13 @@ import type {} from "./model.ts";import { ConnectionTransientError } from "./model.ts";import * as ConnectionResolver from "./resolver.ts";-import { connectionRoutes, routeEntry, routeHttpBaseUrl } from "./routes.ts";+import {+ connectionRoutes,+ routeEntry,+ routeHttpBaseUrl,+ sendsTokenInClear,+ usableRoutes,+} from "./routes.ts";import * as RpcSession from "../rpc/session.ts";import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";@@ -61,7 +67,7 @@ export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")route: ConnectionRoute,) => Effect.Effect<EnvironmentConnectionLease, ConnectionAttemptError, R | Scope.Scope>,) {- const routes = connectionRoutes(entry);+ const routes = usableRoutes(entry);const checks =routes.length === 1? []@@ -162,7 +168,10 @@ export const make = Effect.gen(function* () {});const preflight = (entry: ConnectionCatalogEntry, route: ConnectionRoute) =>- checkRoute(entry, route).pipe(+ (sendsTokenInClear(connectionRoutes(entry), route)+ ? Effect.succeed("silent" as const)+ : checkRoute(entry, route)+ ).pipe(Effect.flatMap((check) =>check === "answered"? resolver.prepare(routeEntry(entry, route)).pipe(diff --git a/packages/client-runtime/src/connection/onboarding.test.ts b/packages/client-runtime/src/connection/onboarding.test.tsindex 7aaaf80cee0..5e1dcd72222 100644--- a/packages/client-runtime/src/connection/onboarding.test.ts+++ b/packages/client-runtime/src/connection/onboarding.test.ts@@ -640,6 +640,8 @@ describe("connection onboarding", () => {connectionId: 'ssh:environment-ssh:["devbox","devbox.example.test","developer",22]',target,},+ // Saved so the first connect reuses this pairing instead of adding another.+ credential: { token: "bearer-token" },});}),);diff --git a/packages/client-runtime/src/connection/onboarding.ts b/packages/client-runtime/src/connection/onboarding.tsindex e71e9514c99..4f8cdba449d 100644--- a/packages/client-runtime/src/connection/onboarding.ts+++ b/packages/client-runtime/src/connection/onboarding.ts@@ -267,6 +267,7 @@ export const prepareSshRegistration = Effect.fn(label,target: provisioned.bootstrap.target,}),+ credential: new BearerConnectionCredential({ token: provisioned.bearerToken }),});});diff --git a/packages/client-runtime/src/connection/outdatedHostUpdate.ts b/packages/client-runtime/src/connection/outdatedHostUpdate.tsindex 3703744321e..e248fb03f19 100644--- a/packages/client-runtime/src/connection/outdatedHostUpdate.ts+++ b/packages/client-runtime/src/connection/outdatedHostUpdate.ts@@ -26,7 +26,13 @@ import { isLegacyUpdateHandoffLoss, resolveServerUpdateProgressResult } from "..import * as RelayEnvironmentDiscovery from "../relay/discovery.ts";import * as ConnectionResolver from "./resolver.ts";import * as EnvironmentRegistry from "./registry.ts";-import { connectionRoutes, hasRelayRoute, routeEntry, routeHttpBaseUrl } from "./routes.ts";+import {+ connectionRoutes,+ hasRelayRoute,+ routeEntry,+ routeHttpBaseUrl,+ usableRoutes,+} from "./routes.ts";// A v1 host restarting into v2 runs migrations before its descriptor answers again.const OUTDATED_HOST_RESTART_TIMEOUT = Duration.minutes(4);@@ -62,7 +68,7 @@ export const updateOutdatedHost = Effect.fn("clientRuntime.connection.updateOutdreturn yield* new EnvironmentRegistry.EnvironmentNotRegisteredError({ environmentId });}const { prepared, descriptor } = yield* Effect.firstSuccessOf(- connectionRoutes(entry).map((route) => resolver.prepareForUpdate(routeEntry(entry, route))),+ usableRoutes(entry).map((route) => resolver.prepareForUpdate(routeEntry(entry, route))),);const capabilities = descriptor.capabilities;if (diff --git a/packages/client-runtime/src/connection/registry.test.ts b/packages/client-runtime/src/connection/registry.test.tsindex 1b83162fd9e..419dd08c546 100644--- a/packages/client-runtime/src/connection/registry.test.ts+++ b/packages/client-runtime/src/connection/registry.test.ts@@ -216,6 +216,7 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (case "RelayConnectionRegistration":return;case "BearerConnectionRegistration":+ case "SshConnectionRegistration":yield* Ref.update(storedProfiles, (current) => {const next = new Map(current);next.set(registration.profile.connectionId, registration.profile);@@ -227,12 +228,6 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (return next;});return;- case "SshConnectionRegistration":- yield* Ref.update(storedProfiles, (current) => {- const next = new Map(current);- next.set(registration.profile.connectionId, registration.profile);- return next;- });}}),setRoutes: (environmentId, routes) =>@@ -1941,6 +1936,7 @@ describe("EnvironmentRegistry routes", () => {connectionId: other.connectionId,target: { ...SSH_TARGET, alias: "other", hostname: "other.example.test" },}),+ credential: BEARER_CREDENTIAL,}),);@@ -1969,6 +1965,7 @@ describe("EnvironmentRegistry routes", () => {...SSH_PROFILE,connectionId: again.connectionId,}),+ credential: BEARER_CREDENTIAL,}),);diff --git a/packages/client-runtime/src/connection/resolver.test.ts b/packages/client-runtime/src/connection/resolver.test.tsindex b99b686fd48..253ba85b367 100644--- a/packages/client-runtime/src/connection/resolver.test.ts+++ b/packages/client-runtime/src/connection/resolver.test.ts@@ -443,6 +443,48 @@ describe("ConnectionResolver", () => {}),);+ it.effect("offers the saved SSH token on each connect and saves the one it gets back", () =>+ Effect.gen(function* () {+ const offeredTokens = yield* Ref.make<ReadonlyArray<string | undefined>>([]);+ const target = new SshConnectionTarget({+ environmentId: ENVIRONMENT_ID,+ label: "SSH",+ connectionId: "ssh-1",+ });+ const profile = new SshConnectionProfile({+ connectionId: "ssh-1",+ environmentId: ENVIRONMENT_ID,+ label: "SSH",+ target: SSH_TARGET,+ });+ const layerBroker = yield* makeDependencies({+ credentials: [["ssh-1", new BearerConnectionCredential({ token: "revoked-token" })]],+ // The host accepts only the token it paired last; anything else pairs again.+ prepareSsh: (input) =>+ Ref.update(offeredTokens, (tokens) => [...tokens, input.bearerToken]).pipe(+ Effect.as({+ bootstrap: {+ target: input.target,+ httpBaseUrl: "http://127.0.0.1:4010",+ wsBaseUrl: "ws://127.0.0.1:4010",+ pairingToken: null,+ },+ bearerToken: "paired-token",+ }),+ ),+ });+ const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(layerBroker));+ const entry = catalogEntry(target, Option.some(profile));++ const first = yield* broker.prepare(entry);+ const second = yield* broker.prepare(entry);++ expect(yield* Ref.get(offeredTokens)).toEqual(["revoked-token", "paired-token"]);+ expect(first.httpAuthorization).toMatchObject({ token: "paired-token" });+ expect(second.httpAuthorization).toMatchObject({ token: "paired-token" });+ }),+ );+it.effect.each(["unchanged", "changed", "revocation-failed"] as const)("handles %s SSH routing consent before saving or authorizing",(scenario) =>diff --git a/packages/client-runtime/src/connection/resolver.ts b/packages/client-runtime/src/connection/resolver.tsindex f0db52beb00..4e1a99a8af4 100644--- a/packages/client-runtime/src/connection/resolver.ts+++ b/packages/client-runtime/src/connection/resolver.ts@@ -200,6 +200,7 @@ const makeRelayBroker = Effect.fn("clientRuntime.connection.broker.makeRelay")(fconst makeSshBroker = Effect.fn("clientRuntime.connection.broker.makeSsh")(function* () {const profiles = yield* ConnectionProfileStore.ConnectionProfileStore;+ const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;const ssh = yield* ClientCapabilities.SshEnvironmentGateway;const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;@@ -222,11 +223,21 @@ const makeSshBroker = Effect.fn("clientRuntime.connection.broker.makeSsh")(functactual: profile.environmentId,});}+ // Each pairing adds a session on the host, so connects reuse the saved token.+ const saved = Option.getOrUndefined(yield* credentials.get(target.connectionId));+ const savedToken = saved !== undefined && isBearerCredential(saved) ? saved.token : undefined;const prepared = yield* ssh.prepare({connectionId: target.connectionId,expectedEnvironmentId: target.environmentId,target: profile.target,+ ...(savedToken === undefined ? {} : { bearerToken: savedToken }),});+ if (prepared.bearerToken !== savedToken) {+ yield* credentials.put(+ target.connectionId,+ new BearerConnectionCredential({ token: prepared.bearerToken }),+ );+ }const preparedProfile = new SshConnectionProfile({connectionId: profile.connectionId,environmentId: profile.environmentId,diff --git a/packages/client-runtime/src/connection/routes.test.ts b/packages/client-runtime/src/connection/routes.test.tsindex fb127918854..7cb8dafa4ca 100644--- a/packages/client-runtime/src/connection/routes.test.ts+++ b/packages/client-runtime/src/connection/routes.test.ts@@ -19,7 +19,9 @@ import {mergeLearnedRoutes,removedWithRelay,routesAfterRemoving,+ sendsTokenInClear,upsertRoute,+ usableRoutes,} from "./routes.ts";const ENVIRONMENT_ID = EnvironmentId.make("environment-1");@@ -51,6 +53,15 @@ const LAN = direct("lan", "http://192.168.1.10:3773/");const TAILNET = direct("tailnet", "https://desk.tail1234.ts.net/");const PUBLIC = direct("public", "https://desk.example.com/");+function learned(id: string, httpBaseUrl: string): ConnectionRoute {+ const route = direct(id, httpBaseUrl);+ const profile = Option.getOrThrow(route.profile) as BearerConnectionProfile;+ return {+ target: route.target,+ profile: Option.some(new BearerConnectionProfile({ ...profile, learned: true })),+ };+}+describe("connection routes", () => {it("classifies direct routes by address", () => {expect(connectionRouteKind(LAN)).toBe("lan");@@ -236,6 +247,87 @@ describe("learned routes", () => {expect(credentialConnectionId(connectionRouteId(learned.target))).toBe("lan");});+ it("keeps a token paired over HTTPS off plain HTTP addresses outside the tailnet", () => {+ const entry = entryWithRoutes(relayOnly, [PUBLIC, RELAY]);+ const routes = mergeLearnedRoutes({+ entry,+ activeRoute: PUBLIC,+ reported: [+ { kind: "lan", httpBaseUrl: "http://192.168.1.10:3773/" },+ { kind: "tailnet", httpBaseUrl: "http://100.101.102.103:3773/" },+ { kind: "tailnet", httpBaseUrl: "https://desk.tail1234.ts.net/" },+ ],+ allowInsecure: true,+ });+ expect(ids(routes)).toEqual([+ `learned:${ENVIRONMENT_ID}:http://100.101.102.103:3773@public`,+ `learned:${ENVIRONMENT_ID}:https://desk.tail1234.ts.net@public`,+ "public",+ "relay",+ ]);+ });++ it("drops a plain HTTP LAN route learned earlier over an HTTPS-paired token", () => {+ const lanOrigin = "http://192.168.1.10:3773";+ const stale = direct(`learned:${ENVIRONMENT_ID}:${lanOrigin}@public`, `${lanOrigin}/`);+ const staleProfile = profileOf(stale) as BearerConnectionProfile;+ const learnedStale: ConnectionRoute = {+ target: stale.target,+ profile: Option.some(new BearerConnectionProfile({ ...staleProfile, learned: true })),+ };+ const routes = mergeLearnedRoutes({+ entry: entryWithRoutes(relayOnly, [learnedStale, PUBLIC, RELAY]),+ activeRoute: PUBLIC,+ reported: [{ kind: "lan", httpBaseUrl: `${lanOrigin}/` }],+ allowInsecure: true,+ });+ expect(ids(routes)).toEqual(["public", "relay"]);+ });++ it("drops a stale plain HTTP route borrowing an HTTPS-paired token while another route is active", () => {+ const lanOrigin = "http://10.0.0.42:3773";+ const stale = learned(`learned:${ENVIRONMENT_ID}:${lanOrigin}@public`, `${lanOrigin}/`);+ const entry = entryWithRoutes(relayOnly, [stale, PUBLIC, RELAY]);+ expect(sendsTokenInClear([stale, PUBLIC, RELAY], stale)).toBe(true);+ expect(ids(usableRoutes(entry))).toEqual(["public", "relay"]);+ const routes = mergeLearnedRoutes({+ entry,+ activeRoute: RELAY,+ reported: [{ kind: "lan", httpBaseUrl: `${lanOrigin}/` }],+ allowInsecure: true,+ });+ // The stale route is gone; the address is learned again with T3 Connect's credential.+ expect(ids(routes)).toEqual([`learned:${ENVIRONMENT_ID}:${lanOrigin}`, "public", "relay"]);+ expect(profileOf(routes![0]!)).toMatchObject({ authorization: "t3-connect" });+ });++ it("keeps plain HTTP routes that don't borrow the active HTTPS-paired token", () => {+ const lanOrigin = "http://10.0.0.42:3773";+ const overLan = learned(`learned:${ENVIRONMENT_ID}:${lanOrigin}@lan`, `${lanOrigin}/`);+ const routes = mergeLearnedRoutes({+ entry: entryWithRoutes(relayOnly, [overLan, LAN, PUBLIC, RELAY]),+ activeRoute: PUBLIC,+ reported: [{ kind: "lan", httpBaseUrl: `${lanOrigin}/` }],+ allowInsecure: true,+ });+ expect(routes).toBeNull();+ });++ it("learns plain HTTP LAN addresses over a token paired over plain HTTP", () => {+ const entry = entryWithRoutes(relayOnly, [LAN, RELAY]);+ const routes = mergeLearnedRoutes({+ entry,+ activeRoute: LAN,+ reported: [{ kind: "lan", httpBaseUrl: "http://10.0.0.42:3773/" }],+ allowInsecure: true,+ });+ expect(ids(routes)).toEqual([+ "lan",+ `learned:${ENVIRONMENT_ID}:http://10.0.0.42:3773@lan`,+ "relay",+ ]);+ });+it("skips plain HTTP from an HTTPS page and never learns loopback", () => {expect(mergeLearnedRoutes({diff --git a/packages/client-runtime/src/connection/routes.ts b/packages/client-runtime/src/connection/routes.tsindex 3467677ff76..9d70ea8c844 100644--- a/packages/client-runtime/src/connection/routes.ts+++ b/packages/client-runtime/src/connection/routes.ts@@ -218,7 +218,6 @@ export function mergeLearnedRoutes(input: {authorization === undefined && active._tag === "BearerConnectionTarget"? credentialConnectionId(active.connectionId): undefined;-const reported = new Map<string, URL>();const tailscaleOrigins = new Set<string>();for (const endpoint of input.reported) {@@ -252,12 +251,21 @@ export function mergeLearnedRoutes(input: {];}if (url === null || !reported.has(normalized(url)) || known.has(normalized(url))) return [];+ if (sendsTokenInClear(saved, route, tailscaleOrigins.has(normalized(url)))) return [];known.add(normalized(url));return [withNetwork(route, tailscaleOrigins.has(normalized(url)))];});let next: ReadonlyArray<ConnectionRoute> = kept;for (const url of reported.values()) {if (known.has(url.origin)) continue;+ if (+ url.protocol === "http:" &&+ sharedCredential !== undefined &&+ !tailscaleOrigins.has(url.origin) &&+ !tokenAllowsPlainHttp(saved, sharedCredential)+ ) {+ continue;+ }const httpBaseUrl = `${url.origin}/`;const connectionId = learnedConnectionId(entry.target.environmentId,@@ -294,6 +302,51 @@ export function mergeLearnedRoutes(input: {return signature(saved) === signature(next) ? null : next;}+// A paired token goes to a plain HTTP address outside the tailnet only when+// it was paired that way, so a token paired over HTTPS, loopback, or the+// tailnet keeps to the transports it was issued for.+function tokenAllowsPlainHttp(+ routes: ReadonlyArray<ConnectionRoute>,+ credentialId: string,+): boolean {+ const credentialRoute = routes.find((route) => connectionRouteId(route.target) === credentialId);+ return (+ credentialRoute !== undefined &&+ routeHttpBaseUrl(credentialRoute)?.startsWith("http:") === true &&+ (connectionRouteKind(credentialRoute) === "lan" ||+ connectionRouteKind(credentialRoute) === "public")+ );+}++/**+ * Whether connecting over `route` would send a paired token over plain HTTP+ * that it wasn't paired over. Checked against the token the route borrows,+ * so a route learned before this rule existed is refused too.+ */+export function sendsTokenInClear(+ routes: ReadonlyArray<ConnectionRoute>,+ route: ConnectionRoute,+ tailscale?: boolean,+): boolean {+ const profile = Option.getOrNull(route.profile);+ if (profile?._tag !== "BearerConnectionProfile" || profile.authorization === "t3-connect") {+ return false;+ }+ if ((tailscale ?? profile.network === "tailscale") || !profile.httpBaseUrl.startsWith("http:")) {+ return false;+ }+ const credentialId = credentialConnectionId(connectionRouteId(route.target));+ return (+ credentialId !== connectionRouteId(route.target) && !tokenAllowsPlainHttp(routes, credentialId)+ );+}++/** Routes a connect may use: none sends a paired token over plain HTTP it wasn't paired over. */+export function usableRoutes(entry: ConnectionCatalogEntry): ReadonlyArray<ConnectionRoute> {+ const routes = connectionRoutes(entry);+ return routes.filter((route) => !sendsTokenInClear(routes, route));+}+export interface ReportedEndpoint {readonly httpBaseUrl: string;readonly kind?: string;diff --git a/packages/client-runtime/src/platform/capabilities.ts b/packages/client-runtime/src/platform/capabilities.tsindex 62dd304c846..8ccc3541584 100644--- a/packages/client-runtime/src/platform/capabilities.ts+++ b/packages/client-runtime/src/platform/capabilities.ts@@ -65,10 +65,17 @@ export class SshEnvironmentGateway extends Context.Service<target: DesktopSshEnvironmentTarget,expectedEnvironmentId?: EnvironmentId,) => Effect.Effect<ProvisionedSshEnvironment, ConnectionAttemptError>;+ /**+ * Starts or reuses the remote server for a saved connection. Returns+ * `bearerToken`, the token this client saved from an earlier pairing, while+ * the host still accepts it with the standard scopes, and pairs again only+ * when it does not, so a reconnect adds no session on the host.+ */readonly prepare: (input: {readonly connectionId: string;readonly expectedEnvironmentId: EnvironmentId;readonly target: DesktopSshEnvironmentTarget;+ readonly bearerToken?: string;}) => Effect.Effect<PreparedSshEnvironment, ConnectionAttemptError>;readonly disconnect: (target: DesktopSshEnvironmentTarget,diff --git a/packages/client-runtime/src/platform/storageDocument.test.ts b/packages/client-runtime/src/platform/storageDocument.test.tsindex f1ffa1493c7..d0140f4c309 100644--- a/packages/client-runtime/src/platform/storageDocument.test.ts+++ b/packages/client-runtime/src/platform/storageDocument.test.ts@@ -387,7 +387,7 @@ describe("ConnectionCatalogDocument", () => {);});- it("persists the normalized SSH profile beside its target", () => {+ it("persists the normalized SSH profile and its paired token beside its target", () => {const target = new SshConnectionTarget({environmentId: ENVIRONMENT_ID,label: "SSH",@@ -406,12 +406,16 @@ describe("ConnectionCatalogDocument", () => {});const document = registerConnectionInCatalog(EMPTY_CONNECTION_CATALOG_DOCUMENT,- new SshConnectionRegistration({ target, profile }),+ new SshConnectionRegistration({ target, profile, credential: BEARER_CREDENTIAL }),);expect(document.targets).toEqual([target]);expect(document.profiles).toEqual([profile]);- expect(document.credentials).toEqual([]);+ expect(document.credentials).toEqual([+ { connectionId: target.connectionId, credential: BEARER_CREDENTIAL },+ ]);+ // Removing the route forgets its token too.+ expect(removeConnectionFromCatalog(document, ENVIRONMENT_ID).credentials).toEqual([]);});it("keeps every route of an environment and drops only a removed route's records", () => {diff --git a/packages/client-runtime/src/platform/storageDocument.ts b/packages/client-runtime/src/platform/storageDocument.tsindex 7fb29993b17..8fe8533b3c5 100644--- a/packages/client-runtime/src/platform/storageDocument.ts+++ b/packages/client-runtime/src/platform/storageDocument.ts@@ -133,6 +133,7 @@ export function registerConnectionInCatalog(case "RelayConnectionRegistration":return next;case "BearerConnectionRegistration":+ case "SshConnectionRegistration":return {...next,profiles: replaceCatalogValue(@@ -145,15 +146,6 @@ export function registerConnectionInCatalog(credential: registration.credential,}),};- case "SshConnectionRegistration":- return {- ...next,- profiles: replaceCatalogValue(- next.profiles,- (value) => value.connectionId,- registration.profile,- ),- };}}