TypeScript
fix(web): preserve usernames in remote editor links (#18092)
Jake Leventhal6c3c31d5e5d8
diff --git a/apps/desktop/src/electron/ElectronShell.test.ts b/apps/desktop/src/electron/ElectronShell.test.tsindex 580a8b95684..7e75d999814 100644--- a/apps/desktop/src/electron/ElectronShell.test.ts+++ b/apps/desktop/src/electron/ElectronShell.test.ts@@ -78,12 +78,12 @@ describe("ElectronShell", () => {const electronShell = yield* ElectronShell.ElectronShell;const result = yield* electronShell.openExternal(- "vscode://vscode-remote/ssh-remote+example.com/home/user/project",+ "vscode://vscode-remote/ssh-remote+user%40example.com/home/user/project",);assert.equal(result, true);assert.deepEqual(openExternalMock.mock.calls, [- ["vscode://vscode-remote/ssh-remote+example.com/home/user/project"],+ ["vscode://vscode-remote/ssh-remote+user%40example.com/home/user/project"],]);}).pipe(Effect.provide(ElectronShell.layer)),);@@ -94,13 +94,13 @@ describe("ElectronShell", () => {const electronShell = yield* ElectronShell.ElectronShell;const results = yield* Effect.all([- electronShell.openExternal("zed://ssh/example.com/home/user/project"),+ electronShell.openExternal("zed://ssh/[email protected]/home/user/project"),electronShell.openExternal("zed://ssh/example.com/"),]);assert.deepEqual(results, [true, true]);assert.deepEqual(openExternalMock.mock.calls, [- ["zed://ssh/example.com/home/user/project"],+ ["zed://ssh/[email protected]/home/user/project"],["zed://ssh/example.com/"],]);}).pipe(Effect.provide(ElectronShell.layer)),@@ -111,7 +111,7 @@ describe("ElectronShell", () => {openExternalMock.mockResolvedValue(undefined);const url =- "jetbrains://gateway/ssh/environment?h=example.com&launchIde=true&ideHint=IU&projectHint=%2Fhome%2Fuser%2Fproject";+ "jetbrains://gateway/ssh/environment?h=example.com&launchIde=true&ideHint=IU&projectHint=%2Fhome%2Fuser%2Fproject&u=user";const electronShell = yield* ElectronShell.ElectronShell;const result = yield* electronShell.openExternal(url);@@ -150,7 +150,7 @@ describe("ElectronShell", () => {electronShell.openExternal("vscode://:secret@vscode-remote/ssh-remote+example.com/home/user/project",),- electronShell.openExternal("zed://ssh/[email protected]/home/user/project"),+ electronShell.openExternal("zed://ssh/user:[email protected]/home/user/project"),electronShell.openExternal("jetbrains://user@gateway/ssh/environment?h=example.com"),]);diff --git a/apps/desktop/src/electron/ElectronShell.ts b/apps/desktop/src/electron/ElectronShell.tsindex d6832c79eb8..0216d7b2c7d 100644--- a/apps/desktop/src/electron/ElectronShell.ts+++ b/apps/desktop/src/electron/ElectronShell.ts@@ -22,8 +22,8 @@ const REMOTE_EDITOR_PROTOCOLS = new Set(}),);-// Zed's host sits in the first path segment, so it needs its own userinfo ban.-const ZED_SSH_PATHNAME = /^\/[^/@:]+\/.*$/;+// Zed embeds [user@]host in the path; reject passwords and ports there.+const ZED_SSH_PATHNAME = /^\/(?:[^/@:]+@)?[^/@:]+\/.*$/;const isRemoteEditorUrl = (url: URL) =>REMOTE_EDITOR_PROTOCOLS.has(url.protocol) &&diff --git a/apps/server/src/environment/RemoteOpenTargets.test.ts b/apps/server/src/environment/RemoteOpenTargets.test.tsindex 4868b79eb81..de3d0db034d 100644--- a/apps/server/src/environment/RemoteOpenTargets.test.ts+++ b/apps/server/src/environment/RemoteOpenTargets.test.ts@@ -1,3 +1,6 @@+// @effect-diagnostics nodeBuiltinImport:off -- replace the native OS lookup and sync its ESM bindings.+import * as NodeModule from "node:module";+import type * as NodeOS from "node:os";import { it } from "@effect/vitest";import * as HostProcess from "@t3tools/shared/HostProcess";import * as NetService from "@t3tools/shared/Net";@@ -7,10 +10,17 @@ import * as Sink from "effect/Sink";import * as Stream from "effect/Stream";import * as ChildProcess from "effect/process/ChildProcess";import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";-import { describe, expect } from "vite-plus/test";+import { afterEach, describe, expect, vi } from "vite-plus/test";import * as RemoteOpenTargets from "./RemoteOpenTargets.ts";+const mutableOs = NodeModule.createRequire(import.meta.url)("node:os") as typeof NodeOS;++afterEach(() => {+ vi.restoreAllMocks();+ NodeModule.syncBuiltinESMExports();+});+const encoder = new TextEncoder();const TAILSCALE_STATUS_JSON = JSON.stringify({@@ -59,8 +69,11 @@ const resolveTargets = (input: {readonly sshd: { readonly ipv4: boolean; readonly ipv6: boolean };readonly tailscale: { readonly status: CommandResult; readonly prefs: CommandResult };readonly hostname: string;-}) =>- Effect.flatMap(RemoteOpenTargets.RemoteOpenTargets, (service) => service.resolveTargets()).pipe(+ readonly username?: string | null;+}) => {+ const resolve = Effect.flatMap(RemoteOpenTargets.RemoteOpenTargets, (service) =>+ service.resolveTargets(),+ ).pipe(Effect.provideService(HostProcess.Hostname, input.hostname),Effect.provide(RemoteOpenTargets.layer.pipe(@@ -69,6 +82,11 @@ const resolveTargets = (input: {),);+ return input.username === undefined+ ? resolve+ : resolve.pipe(Effect.provideService(HostProcess.Username, input.username));+};+const prefsJson = (prefs: { readonly RunSSH: boolean; readonly WantRunning: boolean }) => ({exitCode: 0,stdout: JSON.stringify(@@ -90,6 +108,7 @@ describe("RemoteOpenTargets", () => {sshd: { ipv4: false, ipv6: false },tailscale: TAILSCALE_UP,hostname: "bb-1",+ username: "t3-user",});expect(targets).toEqual([]);}),@@ -101,8 +120,11 @@ describe("RemoteOpenTargets", () => {sshd: { ipv4: false, ipv6: false },tailscale: TAILSCALE_SSH,hostname: "bb-1",+ username: "t3-user",});- expect(targets).toEqual([{ kind: "tailscale", host: "bb-1.tail1234.ts.net" }]);+ expect(targets).toEqual([+ { kind: "tailscale", host: "bb-1.tail1234.ts.net", username: "t3-user" },+ ]);}),);@@ -112,6 +134,7 @@ describe("RemoteOpenTargets", () => {sshd: { ipv4: false, ipv6: false },tailscale: { status: STATUS_UP, prefs: prefsJson({ RunSSH: true, WantRunning: false }) },hostname: "bb-1",+ username: null,});expect(targets).toEqual([]);}),@@ -123,10 +146,11 @@ describe("RemoteOpenTargets", () => {sshd: { ipv4: true, ipv6: true },tailscale: TAILSCALE_UP,hostname: "bb-1",+ username: "t3-user",});expect(targets).toEqual([- { kind: "tailscale", host: "bb-1.tail1234.ts.net" },- { kind: "mdns", host: "bb-1.local" },+ { kind: "tailscale", host: "bb-1.tail1234.ts.net", username: "t3-user" },+ { kind: "mdns", host: "bb-1.local", username: "t3-user" },]);}),);@@ -137,8 +161,9 @@ describe("RemoteOpenTargets", () => {sshd: { ipv4: false, ipv6: true },tailscale: TAILSCALE_DOWN,hostname: "bb-1",+ username: "t3-user",});- expect(targets).toEqual([{ kind: "mdns", host: "bb-1.local" }]);+ expect(targets).toEqual([{ kind: "mdns", host: "bb-1.local", username: "t3-user" }]);}),);@@ -148,8 +173,9 @@ describe("RemoteOpenTargets", () => {sshd: { ipv4: true, ipv6: false },tailscale: TAILSCALE_DOWN,hostname: "bb-1",+ username: "t3-user",});- expect(targets).toEqual([{ kind: "mdns", host: "bb-1.local" }]);+ expect(targets).toEqual([{ kind: "mdns", host: "bb-1.local", username: "t3-user" }]);}),);@@ -159,8 +185,28 @@ describe("RemoteOpenTargets", () => {sshd: { ipv4: true, ipv6: true },tailscale: TAILSCALE_DOWN,hostname: "bb-1.example.com",+ username: "t3-user",+ });+ expect(targets).toEqual([{ kind: "mdns", host: "bb-1.local", username: "t3-user" }]);+ }),+ );++ it.effect("still advertises hostname targets when the OS login lookup fails", () =>+ Effect.gen(function* () {+ const userInfo = vi.spyOn(mutableOs, "userInfo").mockImplementation(() => {+ throw new Error("No passwd entry for this UID");});- expect(targets).toEqual([{ kind: "mdns", host: "bb-1.local" }]);+ NodeModule.syncBuiltinESMExports();+ const targets = yield* resolveTargets({+ sshd: { ipv4: true, ipv6: true },+ tailscale: TAILSCALE_UP,+ hostname: "bb-1",+ });+ expect(userInfo).toHaveBeenCalled();+ expect(targets).toEqual([+ { kind: "tailscale", host: "bb-1.tail1234.ts.net" },+ { kind: "mdns", host: "bb-1.local" },+ ]);}),);});diff --git a/apps/server/src/environment/RemoteOpenTargets.ts b/apps/server/src/environment/RemoteOpenTargets.tsindex 2dfbb275ab0..128f17aeff0 100644--- a/apps/server/src/environment/RemoteOpenTargets.ts+++ b/apps/server/src/environment/RemoteOpenTargets.ts@@ -28,6 +28,7 @@ export const make = Effect.gen(function* () {net.hasListenerOnHost(SSH_PORT, "::1"),(ipv4, ipv6) => ipv4 || ipv6,);+ const username = yield* HostProcess.Username;const magicDnsName = yield* readTailscaleStatus.pipe(Effect.map((status) => status.magicDnsName),@@ -47,13 +48,21 @@ export const make = Effect.gen(function* () {Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),))) {- targets.push({ kind: "tailscale", host: magicDnsName });+ targets.push({+ kind: "tailscale",+ host: magicDnsName,+ ...(username === null ? {} : { username }),+ });}return targets;}if (magicDnsName !== null) {- targets.push({ kind: "tailscale", host: magicDnsName });+ targets.push({+ kind: "tailscale",+ host: magicDnsName,+ ...(username === null ? {} : { username }),+ });}// os.hostname() may already be an FQDN (macOS often reports@@ -61,7 +70,11 @@ export const make = Effect.gen(function* () {const hostname = yield* HostProcess.Hostname;const shortHostname = hostname.split(".")[0]?.trim();if (shortHostname !== undefined && shortHostname.length > 0) {- targets.push({ kind: "mdns", host: `${shortHostname}.local` });+ targets.push({+ kind: "mdns",+ host: `${shortHostname}.local`,+ ...(username === null ? {} : { username }),+ });}return targets;diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsxindex 5c6ddc06746..135231fab91 100644--- a/apps/web/src/components/chat/OpenInPicker.tsx+++ b/apps/web/src/components/chat/OpenInPicker.tsx@@ -251,7 +251,7 @@ export const OpenInPicker = memo(function OpenInPicker({if (remote.mode === "remote-links") {const url = buildRemoteOpenUrl({editor,- host: remote.host.host,+ ...remote.host,absolutePath: openInCwd,isFile: openInCwdIsFile,});diff --git a/apps/web/src/remoteOpen.test.ts b/apps/web/src/remoteOpen.test.tsindex 339423a7da0..00f372f51db 100644--- a/apps/web/src/remoteOpen.test.ts+++ b/apps/web/src/remoteOpen.test.ts@@ -29,7 +29,7 @@ describe("resolveRemoteOpenState", () => {expect(resolveRemoteOpenState({target: primaryTarget("http://127.0.0.1:8000"),- sshAlias: null,+ sshTarget: null,isDesktopRenderer: false,remoteOpenTargets: TAILSCALE_TARGETS,}),@@ -40,7 +40,7 @@ describe("resolveRemoteOpenState", () => {expect(resolveRemoteOpenState({target: primaryTarget("https://sol.tail1234.ts.net"),- sshAlias: null,+ sshTarget: null,isDesktopRenderer: false,remoteOpenTargets: TAILSCALE_TARGETS,}),@@ -56,7 +56,7 @@ describe("resolveRemoteOpenState", () => {expect(resolveRemoteOpenState({target: primaryTarget("http://172.29.112.1:14369"),- sshAlias: null,+ sshTarget: null,isDesktopRenderer: true,remoteOpenTargets: TAILSCALE_TARGETS,}),@@ -71,26 +71,79 @@ describe("resolveRemoteOpenState", () => {label: "WSL (Ubuntu)",connectionId: "local:wsl-1",}),- sshAlias: null,+ sshTarget: null,isDesktopRenderer: false,remoteOpenTargets: TAILSCALE_TARGETS,}),).toEqual({ mode: "local-exec" });});- it("prefers the desktop SSH alias over server-advertised hosts", () => {+ it("leaves a bare desktop SSH alias for the editor to resolve through SSH config", () => {+ const state = resolveRemoteOpenState({+ target: new SshConnectionTarget({ environmentId, label: "sol", connectionId: "ssh-1" }),+ sshTarget: { alias: "sol", username: null },+ isDesktopRenderer: true,+ remoteOpenTargets: [+ { kind: "tailscale", host: "sol.tail1234.ts.net", username: "server-user" },+ ],+ });+ expect(state).toEqual({ mode: "remote-links", host: { kind: "ssh-alias", host: "sol" } });+ if (state.mode !== "remote-links") throw new Error("Expected a remote link");expect(- resolveRemoteOpenState({- target: new SshConnectionTarget({- environmentId,- label: "sol",- connectionId: "ssh-1",- }),- sshAlias: "sol",- isDesktopRenderer: true,- remoteOpenTargets: TAILSCALE_TARGETS,- }),- ).toEqual({ mode: "remote-links", host: { kind: "ssh-alias", host: "sol" } });+ buildRemoteOpenUrl({ editor: "vscode", ...state.host, absolutePath: "/work/project" }),+ ).toBe("vscode://vscode-remote/ssh-remote+sol/work/project");+ expect(+ buildRemoteOpenUrl({ editor: "zed", ...state.host, absolutePath: "/work/project" }),+ ).toBe("zed://ssh/sol/work/project");+ expect(+ buildRemoteOpenUrl({ editor: "idea", ...state.host, absolutePath: "/work/project" }),+ ).toBe(+ "jetbrains://gateway/ssh/environment?h=sol&launchIde=true&ideHint=IU&projectHint=%2Fwork%2Fproject",+ );+ });++ it.each([+ { alias: "server", username: "admin-user" },+ { alias: "admin-user@server", username: null },+ { alias: "old-user@server", username: "admin-user" },+ { alias: "admin-user@server", username: "" },+ { alias: "admin-user@server", username: " " },+ ])("keeps one login username in editor links for $alias (username: '$username')", (sshTarget) => {+ const state = resolveRemoteOpenState({+ target: new SshConnectionTarget({ environmentId, label: "server", connectionId: "ssh-1" }),+ sshTarget,+ isDesktopRenderer: true,+ remoteOpenTargets: TAILSCALE_TARGETS,+ });+ expect(state.mode).toBe("remote-links");+ if (state.mode !== "remote-links") throw new Error("Expected a remote link");+ expect(+ buildRemoteOpenUrl({ editor: "vscode", ...state.host, absolutePath: "/work/project" }),+ ).toBe("vscode://vscode-remote/ssh-remote+admin-user%40server/work/project");+ expect(+ buildRemoteOpenUrl({ editor: "zed", ...state.host, absolutePath: "/work/project" }),+ ).toBe("zed://ssh/admin-user@server/work/project");+ expect(+ buildRemoteOpenUrl({ editor: "idea", ...state.host, absolutePath: "/work/project" }),+ ).toBe(+ "jetbrains://gateway/ssh/environment?h=server&launchIde=true&ideHint=IU&projectHint=%2Fwork%2Fproject&u=admin-user",+ );+ });++ it("uses the advertised login username in editor links over a relay", () => {+ const state = resolveRemoteOpenState({+ target: new RelayConnectionTarget({ environmentId, label: "server" }),+ sshTarget: null,+ isDesktopRenderer: false,+ remoteOpenTargets: [+ { kind: "tailscale", host: "server.tail1234.ts.net", username: "admin-user" },+ ],+ });+ expect(state.mode).toBe("remote-links");+ if (state.mode !== "remote-links") throw new Error("Expected a remote link");+ expect(+ buildRemoteOpenUrl({ editor: "cursor", ...state.host, absolutePath: "/work/project" }),+ ).toBe("cursor://vscode-remote/ssh-remote+admin-user%40server.tail1234.ts.net/work/project");});it("reports unavailable when a remote environment advertises no hosts", () => {@@ -98,7 +151,7 @@ describe("resolveRemoteOpenState", () => {expect(resolveRemoteOpenState({target: new RelayConnectionTarget({ environmentId, label: "sol" }),- sshAlias: null,+ sshTarget: null,isDesktopRenderer: false,remoteOpenTargets,}),@@ -110,7 +163,7 @@ describe("resolveRemoteOpenState", () => {expect(resolveRemoteOpenState({target: null,- sshAlias: null,+ sshTarget: null,isDesktopRenderer: false,remoteOpenTargets: undefined,}),diff --git a/apps/web/src/remoteOpen.ts b/apps/web/src/remoteOpen.tsindex a10e39af003..31bdb997023 100644--- a/apps/web/src/remoteOpen.ts+++ b/apps/web/src/remoteOpen.ts@@ -19,6 +19,7 @@ import { environmentPresentations } from "~/state/presentation";export interface RemoteOpenHost {readonly kind: "ssh-alias" | RemoteOpenTarget["kind"];readonly host: string;+ readonly username?: string;}export type RemoteOpenState =@@ -50,7 +51,7 @@ function parseHostname(url: string): string | null {export function resolveRemoteOpenState(input: {readonly target: ConnectionTarget | null;- readonly sshAlias: string | null;+ readonly sshTarget: { readonly alias: string; readonly username: string | null } | null;readonly remoteOpenTargets: ReadonlyArray<RemoteOpenTarget> | undefined;readonly isDesktopRenderer: boolean;}): RemoteOpenState {@@ -72,8 +73,21 @@ export function resolveRemoteOpenState(input: {return LOCAL_EXEC;}- if (input.sshAlias !== null && input.sshAlias.length > 0) {- return { mode: "remote-links", host: { kind: "ssh-alias", host: input.sshAlias } };+ if (input.sshTarget !== null && input.sshTarget.alias.length > 0) {+ const { alias } = input.sshTarget;+ const userSeparator = alias.lastIndexOf("@");+ const host = userSeparator === -1 ? alias : alias.slice(userSeparator + 1);+ const username =+ input.sshTarget.username?.trim() ||+ (userSeparator === -1 ? null : alias.slice(0, userSeparator));+ return {+ mode: "remote-links",+ host: {+ kind: "ssh-alias",+ host,+ ...(username === null ? {} : { username }),+ },+ };}const advertised = input.remoteOpenTargets?.[0];if (advertised !== undefined) {@@ -85,7 +99,11 @@ export function resolveRemoteOpenState(input: {function remoteOpenStatesEqual(previous: RemoteOpenState, next: RemoteOpenState): boolean {if (previous.mode !== next.mode) return false;if (previous.mode !== "remote-links" || next.mode !== "remote-links") return true;- return previous.host.kind === next.host.kind && previous.host.host === next.host.host;+ return (+ previous.host.kind === next.host.kind &&+ previous.host.host === next.host.host &&+ previous.host.username === next.host.username+ );}// The presentation changes with every server config push and reconnect. This@@ -102,8 +120,8 @@ const remoteOpenResolutionAtom = Atom.family((environmentId: EnvironmentId) =>const next: RemoteOpenResolution = {state: resolveRemoteOpenState({target: entry.target,- sshAlias:- profile !== null && profile._tag === "SshConnectionProfile" ? profile.target.alias : null,+ sshTarget:+ profile !== null && profile._tag === "SshConnectionProfile" ? profile.target : null,remoteOpenTargets: presentation?.serverConfig?.remoteOpenTargets,isDesktopRenderer: window.desktopBridge !== undefined,}),diff --git a/packages/contracts/src/editor.ts b/packages/contracts/src/editor.tsindex afdb04dd59f..17662c0c286 100644--- a/packages/contracts/src/editor.ts+++ b/packages/contracts/src/editor.ts@@ -180,6 +180,7 @@ export const remoteSchemeForEditor = (id: EditorId): string | undefined => {export const buildRemoteOpenUrl = (input: {readonly editor: EditorId;readonly host: string;+ readonly username?: string;readonly absolutePath: string;readonly isFile?: boolean;}): string | undefined => {@@ -195,6 +196,9 @@ export const buildRemoteOpenUrl = (input: {ideHint: editor.jetbrainsProductCode,projectHint: input.absolutePath.replaceAll("\\", "/"),});+ if (input.username !== undefined) {+ params.set("u", input.username);+ }return `${scheme}://gateway/ssh/environment?${params.toString()}`;}// Windows server paths (`C:\...`) appear as `/C:/...` in vscode-remote URIs.@@ -208,11 +212,17 @@ export const buildRemoteOpenUrl = (input: {// POSIX path that happens to start with `/C:` is left alone.const zedPath = /^[Cc]:[\\/]/.test(input.absolutePath) ? rootedPath.slice(3) : rootedPath;const encodedZedPath = zedPath.split("/").map(encodeURIComponent).join("/");- return `${scheme}://ssh/${encodedHost}${encodedZedPath}`;+ // Zed reads this segment as ssh URL userinfo, so the `@` stays literal.+ const zedDestination =+ input.username === undefined+ ? encodedHost+ : `${encodeURIComponent(input.username)}@${encodedHost}`;+ return `${scheme}://ssh/${zedDestination}${encodedZedPath}`;}const encodedPath = rootedPath.split("/").map(encodeURIComponent).join("/");+ const destination = input.username === undefined ? input.host : `${input.username}@${input.host}`;// VS Code opens a bare vscode-remote path as a folder; a trailing position makes it open the file.- return `${scheme}://vscode-remote/ssh-remote+${encodedHost}${encodedPath}${input.isFile ? ":1:1" : ""}`;+ return `${scheme}://vscode-remote/ssh-remote+${encodeURIComponent(destination)}${encodedPath}${input.isFile ? ":1:1" : ""}`;};export const RemoteOpenTargetKind = Schema.Literals(["tailscale", "mdns"]);@@ -221,6 +231,7 @@ export type RemoteOpenTargetKind = typeof RemoteOpenTargetKind.Type;export const RemoteOpenTarget = Schema.Struct({kind: RemoteOpenTargetKind,host: TrimmedNonEmptyString,+ username: Schema.optionalKey(TrimmedNonEmptyString),});export type RemoteOpenTarget = typeof RemoteOpenTarget.Type;diff --git a/packages/shared/src/HostProcess.ts b/packages/shared/src/HostProcess.tsindex 79f6dfef15d..13217e7a321 100644--- a/packages/shared/src/HostProcess.ts+++ b/packages/shared/src/HostProcess.ts@@ -19,6 +19,16 @@ export const Hostname = Context.Reference<string>("@t3tools/shared/HostProcess/HdefaultValue: () => NodeOS.hostname(),});+export const Username = Context.Reference<string | null>("@t3tools/shared/HostProcess/Username", {+ defaultValue: () => {+ try {+ return NodeOS.userInfo().username.trim() || null;+ } catch {+ return null;+ }+ },+});+export const HomeDirectory = Context.Reference<string>("@t3tools/shared/HostProcess/HomeDirectory",{