Add remote SSH environment launch support

- Discover SSH hosts and persist SSH targets
- Bootstrap tunneled SSH sessions with desktop password prompts
- Extend IPC and storage tests for SSH metadata
This commit is contained in:
Julius Marminge authored and Julius Marminge committed 2026-04-27 18:14:50 -07:00
1 parent 596a25fefa
commit 399264836a
20 files changed
+2864 -171

No files matched your search

@@ -70,6 +70,12 @@ const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: "2026-04-09T01:00:00.000Z",
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
};
describe("clientPersistence", () => {
+12 -3
View File
@@ -57,6 +57,12 @@ function isPersistedSavedEnvironmentStorageRecord(
typeof value.wsBaseUrl === "string" &&
typeof value.createdAt === "string" &&
(value.lastConnectedAt === null || typeof value.lastConnectedAt === "string") &&
(value.desktopSsh === undefined ||
(Predicate.isObject(value.desktopSsh) &&
typeof value.desktopSsh.alias === "string" &&
typeof value.desktopSsh.hostname === "string" &&
(value.desktopSsh.username === null || typeof value.desktopSsh.username === "string") &&
(value.desktopSsh.port === null || typeof value.desktopSsh.port === "number"))) &&
(value.encryptedBearerToken === undefined || typeof value.encryptedBearerToken === "string")
);
}
@@ -77,7 +83,7 @@ function readSavedEnvironmentRegistryDocument(filePath: string): SavedEnvironmen
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentStorageRecord,
): PersistedSavedEnvironmentRecord {
return {
const nextRecord = {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
@@ -85,6 +91,7 @@ function toPersistedSavedEnvironmentRecord(
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
}
export function readClientSettings(settingsPath: string): ClientSettings | null {
@@ -134,6 +141,7 @@ export function writeSavedEnvironmentRegistry(
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
encryptedBearerToken,
}
: record;
@@ -189,7 +197,7 @@ export function writeSavedEnvironmentSecret(input: {
const encryptedBearerToken = input.secretStorage
.encryptString(input.secret)
.toString("base64");
return {
const nextRecord = {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
@@ -197,7 +205,8 @@ export function writeSavedEnvironmentSecret(input: {
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
encryptedBearerToken,
} satisfies PersistedSavedEnvironmentStorageRecord;
};
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
}),
} satisfies SavedEnvironmentRegistryDocument);
return found;
+297
View File
@@ -20,7 +20,13 @@ import {
} from "electron";
import type { MenuItemConstructorOptions, OpenDialogOptions } from "electron";
import type {
AuthBearerBootstrapResult,
AuthSessionState,
AuthWebSocketTokenResult,
ClientSettings,
DesktopSshPasswordPromptRequest,
ExecutionEnvironmentDescriptor,
DesktopSshEnvironmentTarget,
DesktopTheme,
DesktopAppBranding,
DesktopServerExposureMode,
@@ -59,6 +65,7 @@ import {
resolveDesktopCoreAdvertisedEndpoints,
resolveDesktopServerExposure,
} from "./serverExposure.ts";
import { DesktopSshEnvironmentManager } from "./sshEnvironment.ts";
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState.ts";
@@ -104,6 +111,14 @@ const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-re
const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
const FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL = "desktop:fetch-ssh-environment-descriptor";
const BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL = "desktop:bootstrap-ssh-bearer-session";
const FETCH_SSH_SESSION_STATE_CHANNEL = "desktop:fetch-ssh-session-state";
const ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL = "desktop:issue-ssh-websocket-token";
const SSH_PASSWORD_PROMPT_CHANNEL = "desktop:ssh-password-prompt";
const RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL = "desktop:resolve-ssh-password-prompt";
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
@@ -162,6 +177,7 @@ function resolvePickFolderDefaultPath(rawOptions: unknown): string | undefined {
}
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_REQUIRED_PORT_PROBE_HOSTS = ["0.0.0.0", "::"] as const;
const SSH_PASSWORD_PROMPT_TIMEOUT_MS = 3 * 60 * 1000;
const TITLEBAR_HEIGHT = 40;
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
@@ -206,6 +222,12 @@ type LinuxDesktopNamedApp = Electron.App & {
setDesktopName?: (desktopName: string) => void;
};
interface PendingSshPasswordPrompt {
readonly resolve: (password: string | null) => void;
readonly reject: (error: Error) => void;
readonly timeout: ReturnType<typeof setTimeout>;
}
let mainWindow: BrowserWindow | null = null;
let backendProcess: ChildProcess.ChildProcess | null = null;
let backendPort = 0;
@@ -229,6 +251,7 @@ let restoreStdIoCapture: (() => void) | null = null;
let backendObservabilitySettings = readPersistedBackendObservabilitySettings();
let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH, app.getVersion());
let desktopServerExposureMode: DesktopServerExposureMode = desktopSettings.serverExposureMode;
const pendingSshPasswordPrompts = new Map<string, PendingSshPasswordPrompt>();
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
const expectedBackendExitChildren = new WeakSet<ChildProcess.ChildProcess>();
@@ -405,6 +428,7 @@ function relaunchDesktopApp(reason: string): void {
`desktop relaunch backend shutdown warning message=${formatErrorMessage(error)}`,
);
})
.then(() => desktopSshEnvironmentManager.dispose().catch(() => undefined))
.finally(() => {
restoreStdIoCapture?.();
if (isDevelopment) {
@@ -467,6 +491,128 @@ function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
return null;
}
function getSafeDesktopSshTarget(rawTarget: unknown): DesktopSshEnvironmentTarget | null {
if (typeof rawTarget !== "object" || rawTarget === null) {
return null;
}
const target = rawTarget as Partial<DesktopSshEnvironmentTarget>;
if (typeof target.alias !== "string" || typeof target.hostname !== "string") {
return null;
}
if (
target.username !== null &&
target.username !== undefined &&
typeof target.username !== "string"
) {
return null;
}
if (target.port !== null && target.port !== undefined && !Number.isInteger(target.port)) {
return null;
}
return {
alias: target.alias.trim(),
hostname: target.hostname.trim(),
username: target.username?.trim() || null,
port: target.port ?? null,
};
}
function isLoopbackHostname(hostname: string): boolean {
const normalized = hostname
.trim()
.toLowerCase()
.replace(/^\[(.*)\]$/, "$1");
return normalized === "127.0.0.1" || normalized === "::1" || normalized === "localhost";
}
function resolveLoopbackSshHttpUrl(rawHttpBaseUrl: unknown, pathname: string): URL {
if (typeof rawHttpBaseUrl !== "string" || rawHttpBaseUrl.trim().length === 0) {
throw new Error("Invalid SSH forwarded http base URL.");
}
let baseUrl: URL;
try {
baseUrl = new URL(rawHttpBaseUrl);
} catch {
throw new Error("Invalid SSH forwarded http base URL.");
}
if (!isLoopbackHostname(baseUrl.hostname)) {
throw new Error("SSH desktop bridge only supports loopback forwarded URLs.");
}
const url = new URL(baseUrl.toString());
url.pathname = pathname;
url.search = "";
url.hash = "";
return url;
}
async function readRemoteFetchErrorMessage(
response: Response,
fallbackMessage: string,
): Promise<string> {
const text = await response.text();
if (!text) {
return fallbackMessage;
}
try {
const parsed = JSON.parse(text) as { readonly error?: string };
if (typeof parsed.error === "string" && parsed.error.trim().length > 0) {
return parsed.error;
}
} catch {
// Fall back to the raw text below.
}
return text;
}
async function fetchLoopbackSshJson<T>(input: {
readonly httpBaseUrl: unknown;
readonly pathname: string;
readonly method?: "GET" | "POST";
readonly bearerToken?: unknown;
readonly body?: unknown;
}): Promise<T> {
const requestUrl = resolveLoopbackSshHttpUrl(input.httpBaseUrl, input.pathname).toString();
const bearerToken =
typeof input.bearerToken === "string" && input.bearerToken.trim().length > 0
? input.bearerToken
: null;
let response: Response;
try {
response = await fetch(requestUrl, {
method: input.method ?? "GET",
headers: {
...(input.body !== undefined ? { "content-type": "application/json" } : {}),
...(bearerToken ? { authorization: `Bearer ${bearerToken}` } : {}),
},
...(input.body !== undefined ? { body: JSON.stringify(input.body) } : {}),
});
} catch (error) {
throw new Error(
`Failed to reach SSH forwarded endpoint ${requestUrl} (${error instanceof Error ? error.message : String(error)}).`,
{ cause: error },
);
}
if (!response.ok) {
throw new Error(
await readRemoteFetchErrorMessage(
response,
`SSH forwarded request failed (${response.status}).`,
),
);
}
return (await response.json()) as T;
}
async function waitForBackendHttpReady(
baseUrl: string,
options?: Parameters<typeof waitForHttpReady>[1],
@@ -661,6 +807,56 @@ let updateInstallInFlight = false;
let updaterConfigured = false;
let updateState: DesktopUpdateState = initialUpdateState();
function rejectPendingSshPasswordPrompts(message: string): void {
for (const [requestId, pending] of pendingSshPasswordPrompts) {
clearTimeout(pending.timeout);
pendingSshPasswordPrompts.delete(requestId);
pending.reject(new Error(message));
}
}
async function requestSshPasswordFromRenderer(input: {
readonly destination: string;
readonly username: string | null;
readonly prompt: string;
}): Promise<string | null> {
const window = mainWindow;
if (!window || window.isDestroyed()) {
throw new Error("T3 Code window is not available for SSH authentication.");
}
const request: DesktopSshPasswordPromptRequest = {
requestId: Crypto.randomUUID(),
destination: input.destination,
username: input.username,
prompt: input.prompt,
};
return await new Promise<string | null>((resolve, reject) => {
const timeout = setTimeout(() => {
pendingSshPasswordPrompts.delete(request.requestId);
reject(new Error(`SSH authentication timed out for ${input.destination}.`));
}, SSH_PASSWORD_PROMPT_TIMEOUT_MS);
timeout.unref();
pendingSshPasswordPrompts.set(request.requestId, {
resolve,
reject,
timeout,
});
window.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, request);
if (window.isMinimized()) {
window.restore();
}
window.focus();
});
}
const desktopSshEnvironmentManager = new DesktopSshEnvironmentManager({
passwordProvider: requestSshPasswordFromRenderer,
});
function resolveUpdaterErrorContext(): DesktopUpdateErrorContext {
if (updateInstallInFlight) return "install";
if (updateDownloadInFlight) return "download";
@@ -1679,6 +1875,101 @@ function registerIpcHandlers(): void {
},
);
ipcMain.removeHandler(DISCOVER_SSH_HOSTS_CHANNEL);
ipcMain.handle(DISCOVER_SSH_HOSTS_CHANNEL, async () =>
desktopSshEnvironmentManager.discoverHosts(),
);
ipcMain.removeHandler(ENSURE_SSH_ENVIRONMENT_CHANNEL);
ipcMain.handle(
ENSURE_SSH_ENVIRONMENT_CHANNEL,
async (_event, rawTarget: unknown, rawOptions: unknown) => {
const target = getSafeDesktopSshTarget(rawTarget);
if (!target) {
throw new Error("Invalid desktop SSH target.");
}
const issuePairingToken =
typeof rawOptions === "object" &&
rawOptions !== null &&
"issuePairingToken" in rawOptions &&
(rawOptions as { issuePairingToken?: unknown }).issuePairingToken === true;
return await desktopSshEnvironmentManager.ensureEnvironment(target, {
issuePairingToken,
});
},
);
ipcMain.removeHandler(FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL);
ipcMain.handle(
FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL,
async (_event, rawHttpBaseUrl: unknown) =>
fetchLoopbackSshJson<ExecutionEnvironmentDescriptor>({
httpBaseUrl: rawHttpBaseUrl,
pathname: "/.well-known/t3/environment",
}),
);
ipcMain.removeHandler(BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL);
ipcMain.handle(
BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL,
async (_event, rawHttpBaseUrl: unknown, rawCredential: unknown) =>
fetchLoopbackSshJson<AuthBearerBootstrapResult>({
httpBaseUrl: rawHttpBaseUrl,
pathname: "/api/auth/bootstrap/bearer",
method: "POST",
body: {
credential: rawCredential,
},
}),
);
ipcMain.removeHandler(FETCH_SSH_SESSION_STATE_CHANNEL);
ipcMain.handle(
FETCH_SSH_SESSION_STATE_CHANNEL,
async (_event, rawHttpBaseUrl: unknown, rawBearerToken: unknown) =>
fetchLoopbackSshJson<AuthSessionState>({
httpBaseUrl: rawHttpBaseUrl,
pathname: "/api/auth/session",
bearerToken: rawBearerToken,
}),
);
ipcMain.removeHandler(ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL);
ipcMain.handle(
ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL,
async (_event, rawHttpBaseUrl: unknown, rawBearerToken: unknown) =>
fetchLoopbackSshJson<AuthWebSocketTokenResult>({
httpBaseUrl: rawHttpBaseUrl,
pathname: "/api/auth/ws-token",
method: "POST",
bearerToken: rawBearerToken,
}),
);
ipcMain.removeHandler(RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL);
ipcMain.handle(
RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL,
async (_event, rawRequestId: unknown, rawPassword: unknown) => {
if (typeof rawRequestId !== "string" || rawRequestId.trim().length === 0) {
throw new Error("Invalid SSH password prompt id.");
}
if (rawPassword !== null && typeof rawPassword !== "string") {
throw new Error("Invalid SSH password prompt response.");
}
const pending = pendingSshPasswordPrompts.get(rawRequestId);
if (!pending) {
throw new Error("SSH password prompt is no longer pending.");
}
clearTimeout(pending.timeout);
pendingSshPasswordPrompts.delete(rawRequestId);
pending.resolve(rawPassword);
},
);
ipcMain.removeHandler(GET_SERVER_EXPOSURE_STATE_CHANNEL);
ipcMain.handle(GET_SERVER_EXPOSURE_STATE_CHANNEL, async () => getDesktopServerExposureState());
@@ -2054,6 +2345,9 @@ function createWindow(): BrowserWindow {
}
window.on("closed", () => {
rejectPendingSshPasswordPrompts(
"SSH authentication was cancelled because the app window closed.",
);
if (mainWindow === window) {
mainWindow = null;
}
@@ -2145,6 +2439,7 @@ app.on("before-quit", () => {
clearUpdatePollTimer();
cancelBackendReadinessWait();
stopBackend();
void desktopSshEnvironmentManager.dispose().catch(() => undefined);
restoreStdIoCapture?.();
});
@@ -2194,6 +2489,7 @@ if (process.platform !== "win32") {
clearUpdatePollTimer();
cancelBackendReadinessWait();
stopBackend();
void desktopSshEnvironmentManager.dispose().catch(() => undefined);
restoreStdIoCapture?.();
app.quit();
});
@@ -2204,6 +2500,7 @@ if (process.platform !== "win32") {
writeDesktopLogHeader("SIGTERM received");
clearUpdatePollTimer();
stopBackend();
void desktopSshEnvironmentManager.dispose().catch(() => undefined);
restoreStdIoCapture?.();
app.quit();
});
+32
View File
@@ -22,6 +22,14 @@ const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-re
const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
const FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL = "desktop:fetch-ssh-environment-descriptor";
const BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL = "desktop:bootstrap-ssh-bearer-session";
const FETCH_SSH_SESSION_STATE_CHANNEL = "desktop:fetch-ssh-session-state";
const ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL = "desktop:issue-ssh-websocket-token";
const SSH_PASSWORD_PROMPT_CHANNEL = "desktop:ssh-password-prompt";
const RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL = "desktop:resolve-ssh-password-prompt";
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
@@ -52,6 +60,30 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId, secret),
removeSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
discoverSshHosts: () => ipcRenderer.invoke(DISCOVER_SSH_HOSTS_CHANNEL),
ensureSshEnvironment: (target, options) =>
ipcRenderer.invoke(ENSURE_SSH_ENVIRONMENT_CHANNEL, target, options),
fetchSshEnvironmentDescriptor: (httpBaseUrl) =>
ipcRenderer.invoke(FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL, httpBaseUrl),
bootstrapSshBearerSession: (httpBaseUrl, credential) =>
ipcRenderer.invoke(BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL, httpBaseUrl, credential),
fetchSshSessionState: (httpBaseUrl, bearerToken) =>
ipcRenderer.invoke(FETCH_SSH_SESSION_STATE_CHANNEL, httpBaseUrl, bearerToken),
issueSshWebSocketToken: (httpBaseUrl, bearerToken) =>
ipcRenderer.invoke(ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL, httpBaseUrl, bearerToken),
onSshPasswordPrompt: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, request: unknown) => {
if (typeof request !== "object" || request === null) return;
listener(request as Parameters<typeof listener>[0]);
};
ipcRenderer.on(SSH_PASSWORD_PROMPT_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(SSH_PASSWORD_PROMPT_CHANNEL, wrappedListener);
};
},
resolveSshPasswordPrompt: (requestId, password) =>
ipcRenderer.invoke(RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL, requestId, password),
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
getAdvertisedEndpoints: () => ipcRenderer.invoke(GET_ADVERTISED_ENDPOINTS_CHANNEL),
+196
View File
@@ -0,0 +1,196 @@
import * as FS from "node:fs";
import * as OS from "node:os";
import * as Path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { __test, discoverDesktopSshHosts } from "./sshEnvironment";
const tempDirectories: string[] = [];
afterEach(() => {
for (const directory of tempDirectories.splice(0)) {
FS.rmSync(directory, { recursive: true, force: true });
}
});
function makeTempHomeDir(): string {
const directory = FS.mkdtempSync(Path.join(OS.tmpdir(), "t3-ssh-env-test-"));
tempDirectories.push(directory);
return directory;
}
describe("sshEnvironment", () => {
it("discovers ssh config hosts across included files", async () => {
const homeDir = makeTempHomeDir();
const sshDir = Path.join(homeDir, ".ssh");
FS.mkdirSync(Path.join(sshDir, "config.d"), { recursive: true });
FS.writeFileSync(
Path.join(sshDir, "config"),
["Host devbox", " HostName devbox.example.com", "Include config.d/*.conf", ""].join("\n"),
"utf8",
);
FS.writeFileSync(
Path.join(sshDir, "config.d", "team.conf"),
[
"Host staging",
" HostName staging.example.com",
"Host *",
" ServerAliveInterval 30",
"",
].join("\n"),
"utf8",
);
FS.writeFileSync(
Path.join(sshDir, "known_hosts"),
[
"known.example.com ssh-ed25519 AAAA",
"|1|hashed|entry ssh-ed25519 AAAA",
"[bastion.example.com]:2222 ssh-ed25519 AAAA",
"",
].join("\n"),
"utf8",
);
await expect(discoverDesktopSshHosts({ homeDir })).resolves.toEqual([
{
alias: "bastion.example.com",
hostname: "bastion.example.com",
username: null,
port: null,
source: "known-hosts",
},
{
alias: "devbox",
hostname: "devbox",
username: null,
port: null,
source: "ssh-config",
},
{
alias: "known.example.com",
hostname: "known.example.com",
username: null,
port: null,
source: "known-hosts",
},
{
alias: "staging",
hostname: "staging",
username: null,
port: null,
source: "ssh-config",
},
]);
});
it("parses known_hosts entries without returning hashed hosts", () => {
expect(
__test.parseKnownHostsHostnames(
[
"github.com ssh-ed25519 AAAA",
"gitlab.com,gitlab-alias ssh-ed25519 BBBB",
"|1|hashed|entry ssh-ed25519 CCCC",
"@cert-authority *.example.com ssh-ed25519 DDDD",
"[ssh.example.com]:2200 ssh-ed25519 EEEE",
"",
].join("\n"),
),
).toEqual(["github.com", "gitlab-alias", "gitlab.com", "ssh.example.com"]);
});
it("parses resolved ssh config output into a target", () => {
expect(
__test.parseSshResolveOutput(
"devbox",
["hostname devbox.example.com", "user julius", "port 2222", ""].join("\n"),
),
).toEqual({
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
});
});
it("builds interactive ssh args without forcing batch mode", () => {
expect(
__test.baseSshArgs(
{
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
},
{ batchMode: "no" },
),
).toEqual(["-o", "BatchMode=no", "-o", "ConnectTimeout=10", "-p", "2222"]);
});
it("creates askpass env for desktop ssh prompts", () => {
const askpassDirectory = Path.join(makeTempHomeDir(), "askpass");
const env = __test.buildSshChildEnvironment({
authSecret: "super-secret",
interactiveAuth: true,
askpassDirectory,
platform: "linux",
baseEnv: {},
});
expect(env.SSH_ASKPASS).toBe(Path.join(askpassDirectory, "ssh-askpass.sh"));
expect(env.SSH_ASKPASS_REQUIRE).toBe("force");
expect(env.T3_SSH_AUTH_SECRET).toBe("super-secret");
expect(env.DISPLAY).toBe("t3code");
expect(FS.existsSync(Path.join(askpassDirectory, "ssh-askpass.sh"))).toBe(true);
expect(FS.readFileSync(Path.join(askpassDirectory, "ssh-askpass.sh"), "utf8")).toContain(
'printf "%s\\n" "$T3_SSH_AUTH_SECRET"',
);
});
it("builds a windows askpass launcher pair", () => {
const descriptor = __test.buildSshAskpassHelperDescriptor({
directory: "C:\\temp\\t3code-ssh-askpass",
platform: "win32",
});
expect(descriptor.launcherPath).toBe("C:\\temp\\t3code-ssh-askpass\\ssh-askpass.cmd");
expect(descriptor.files.map((file) => Path.win32.basename(file.path))).toEqual([
"ssh-askpass.cmd",
"ssh-askpass.ps1",
]);
});
it("builds a remote t3 runner with npx and npm fallbacks", () => {
const script = __test.buildRemoteT3RunnerScript();
expect(script).toContain('exec t3 "$@"');
expect(script).toContain('exec npx --yes t3 "$@"');
expect(script).toContain('exec npm exec --yes t3 -- "$@"');
expect(script).toContain("could not find npx or npm on PATH");
});
it("uses the remote t3 runner for launch and pairing scripts", () => {
const target = {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
} as const;
expect(__test.buildRemoteLaunchScript()).toContain('"$RUNNER_FILE" serve --host 127.0.0.1');
expect(__test.buildRemotePairingScript(target)).toContain(
'"$RUNNER_FILE" auth pairing create --base-dir "$SERVER_HOME" --json',
);
});
it("detects ssh auth failures from common permission denied messages", () => {
expect(
__test.isSshAuthFailure(
new Error(
"[email protected]: Permission denied (publickey,password,keyboard-interactive).",
),
),
).toBe(true);
expect(__test.isSshAuthFailure(new Error("Connection timed out"))).toBe(false);
});
});
File diff suppressed because it is too large. Load diff
@@ -10,6 +10,12 @@ const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: null,
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
};
function createLocalStorageStub(): Storage {
+14 -3
View File
@@ -19,6 +19,14 @@ const BrowserSavedEnvironmentRecordSchema = Schema.Struct({
wsBaseUrl: Schema.String,
createdAt: Schema.String,
lastConnectedAt: Schema.NullOr(Schema.String),
desktopSsh: Schema.optionalKey(
Schema.Struct({
alias: Schema.String,
hostname: Schema.String,
username: Schema.NullOr(Schema.String),
port: Schema.NullOr(Schema.Number),
}),
),
bearerToken: Schema.optionalKey(Schema.String),
});
type BrowserSavedEnvironmentRecord = typeof BrowserSavedEnvironmentRecordSchema.Type;
@@ -37,7 +45,7 @@ function hasWindow(): boolean {
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentRecord,
): PersistedSavedEnvironmentRecord {
return {
const nextRecord = {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
@@ -45,6 +53,7 @@ function toPersistedSavedEnvironmentRecord(
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
}
export function readBrowserClientSettings(): ClientSettings | null {
@@ -135,6 +144,7 @@ export function writeBrowserSavedEnvironmentRegistry(
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
bearerToken,
}
: toPersistedSavedEnvironmentRecord(record);
@@ -166,7 +176,7 @@ export function writeBrowserSavedEnvironmentSecret(
return record;
}
found = true;
return {
const nextRecord = {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
@@ -174,7 +184,8 @@ export function writeBrowserSavedEnvironmentSecret(
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
bearerToken: secret,
} satisfies BrowserSavedEnvironmentRecord;
};
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
}),
});
return found;
@@ -0,0 +1,114 @@
import type { DesktopSshPasswordPromptRequest } from "@t3tools/contracts";
import { useEffect, useRef, useState } from "react";
import { Button } from "../ui/button";
import {
Dialog,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "../ui/dialog";
import { Input } from "../ui/input";
function describeSshTarget(request: DesktopSshPasswordPromptRequest): string {
return request.username ? `${request.username}@${request.destination}` : request.destination;
}
export function SshPasswordPromptDialog() {
const [queue, setQueue] = useState<readonly DesktopSshPasswordPromptRequest[]>([]);
const [password, setPassword] = useState("");
const currentRequest = queue[0] ?? null;
const inputRef = useRef<HTMLInputElement | null>(null);
useEffect(() => {
const bridge = window.desktopBridge;
if (!bridge?.onSshPasswordPrompt) {
return;
}
return bridge.onSshPasswordPrompt((request) => {
setQueue((currentQueue) => [...currentQueue, request]);
});
}, []);
useEffect(() => {
setPassword("");
if (!currentRequest) {
return;
}
const frame = window.requestAnimationFrame(() => {
inputRef.current?.focus();
inputRef.current?.select();
});
return () => {
window.cancelAnimationFrame(frame);
};
}, [currentRequest]);
const respond = async (nextPassword: string | null) => {
if (!currentRequest) {
return;
}
const requestId = currentRequest.requestId;
setQueue((currentQueue) => currentQueue.slice(1));
setPassword("");
try {
await window.desktopBridge?.resolveSshPasswordPrompt(requestId, nextPassword);
} catch (error) {
console.error("Failed to resolve SSH password prompt.", error);
}
};
const target = currentRequest ? describeSshTarget(currentRequest) : null;
return (
<Dialog
open={currentRequest !== null}
onOpenChange={(open) => {
if (!open) {
void respond(null);
}
}}
>
<DialogPopup className="max-w-md" showCloseButton={false}>
<DialogHeader>
<DialogTitle>SSH Password Required</DialogTitle>
<DialogDescription>
T3 needs your SSH password to connect to{" "}
{target ? <code>{target}</code> : "the remote host"}. The password is passed to the
local SSH process for this connection attempt and is not saved by T3 Code.
</DialogDescription>
</DialogHeader>
<DialogPanel className="space-y-3" scrollFade={false}>
<div className="space-y-2">
<p className="text-sm font-medium text-foreground">{currentRequest?.prompt}</p>
<Input
ref={inputRef}
autoComplete="current-password"
name="ssh-password"
type="password"
value={password}
onChange={(event) => setPassword(event.target.value)}
/>
</div>
<p className="text-sm text-muted-foreground">
Use SSH keys to avoid repeated password prompts on new SSH sessions.
</p>
</DialogPanel>
<DialogFooter>
<Button variant="outline" onClick={() => void respond(null)}>
Cancel
</Button>
<Button onClick={() => void respond(password)} type="button">
Continue
</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
);
}
@@ -1,9 +1,11 @@
import { ChevronDownIcon, PlusIcon, QrCodeIcon } from "lucide-react";
import { ChevronDownIcon, PlusIcon, QrCodeIcon, RefreshCwIcon } from "lucide-react";
import { type ReactNode, memo, useCallback, useEffect, useMemo, useState } from "react";
import {
type AuthClientSession,
type AuthPairingLink,
type AdvertisedEndpoint,
type DesktopDiscoveredSshHost,
type DesktopSshEnvironmentTarget,
type DesktopServerExposureState,
type EnvironmentId,
} from "@t3tools/contracts";
@@ -30,6 +32,7 @@ import {
DialogTitle,
DialogTrigger,
} from "../ui/dialog";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "../ui/collapsible";
import {
AlertDialog,
AlertDialogClose,
@@ -67,6 +70,7 @@ import {
useSavedEnvironmentRegistryStore,
useSavedEnvironmentRuntimeStore,
addSavedEnvironment,
connectDesktopSshEnvironment,
getPrimaryEnvironmentConnection,
reconnectSavedEnvironment,
removeSavedEnvironment,
@@ -165,6 +169,69 @@ function getSavedBackendStatusTooltip(
: "Not connected yet.";
}
function formatDesktopSshTarget(target: NonNullable<SavedEnvironmentRecord["desktopSsh"]>): string {
const authority = target.username ? `${target.username}@${target.hostname}` : target.hostname;
return target.port ? `${authority}:${target.port}` : authority;
}
function parseManualDesktopSshTarget(input: {
readonly host: string;
readonly username: string;
readonly port: string;
}): DesktopSshEnvironmentTarget {
const rawHost = input.host.trim();
if (rawHost.length === 0) {
throw new Error("SSH host or alias is required.");
}
let hostname = rawHost;
let username = input.username.trim() || null;
let port: number | null = null;
const atIndex = hostname.lastIndexOf("@");
if (atIndex > 0) {
const inlineUsername = hostname.slice(0, atIndex).trim();
hostname = hostname.slice(atIndex + 1).trim();
if (!username && inlineUsername.length > 0) {
username = inlineUsername;
}
}
const bracketedHostMatch = /^\[([^\]]+)\](?::(\d+))?$/u.exec(hostname);
if (bracketedHostMatch) {
hostname = bracketedHostMatch[1]!.trim();
if (bracketedHostMatch[2]) {
port = Number.parseInt(bracketedHostMatch[2], 10);
}
} else {
const colonSegments = hostname.split(":");
if (colonSegments.length === 2 && /^\d+$/u.test(colonSegments[1] ?? "")) {
hostname = colonSegments[0]!.trim();
port = Number.parseInt(colonSegments[1]!, 10);
}
}
const rawPort = input.port.trim();
if (rawPort.length > 0) {
port = Number.parseInt(rawPort, 10);
}
if (hostname.length === 0) {
throw new Error("SSH host or alias is required.");
}
if (port !== null && (!Number.isInteger(port) || port <= 0 || port > 65_535)) {
throw new Error("SSH port must be between 1 and 65535.");
}
return {
alias: hostname,
hostname,
username,
port,
};
}
/** Direct row in the card – same pattern as the Provider / ACP-agent list rows. */
const ITEM_ROW_CLASSNAME = "border-t border-border/60 px-4 py-4 first:border-t-0 sm:px-5";
const ENDPOINT_ROW_CLASSNAME = "border-t border-border/60 px-4 py-2.5 first:border-t-0 sm:px-5";
@@ -933,6 +1000,7 @@ function SavedBackendListRow({
const descriptorLabel = runtime?.descriptor?.label ?? null;
const statusTooltip = getSavedBackendStatusTooltip(runtime, record, nowMs);
const metadataBits = [
record.desktopSsh ? `SSH ${formatDesktopSshTarget(record.desktopSsh)}` : null,
roleLabel,
record.lastConnectedAt
? `Last connected ${formatAccessTimestamp(record.lastConnectedAt)}`
@@ -983,6 +1051,59 @@ function SavedBackendListRow({
);
}
interface DesktopSshHostRowProps {
target: DesktopDiscoveredSshHost;
savedRecord: SavedEnvironmentRecord | null;
connectingHostAlias: string | null;
onConnect: (target: DesktopDiscoveredSshHost) => void;
}
const DesktopSshHostRow = memo(function DesktopSshHostRow({
target,
savedRecord,
connectingHostAlias,
onConnect,
}: DesktopSshHostRowProps) {
const address = formatDesktopSshTarget(target);
const secondaryBits = [target.source === "ssh-config" ? "SSH config" : "Known hosts", address];
const buttonLabel =
connectingHostAlias === target.alias ? "Connecting…" : savedRecord ? "Reconnect" : "Connect";
return (
<div className={ITEM_ROW_CLASSNAME}>
<div className={ITEM_ROW_INNER_CLASSNAME}>
<div className="min-w-0 flex-1 space-y-1">
<div className="flex min-h-5 items-center gap-1.5">
<h3 className="text-sm font-medium text-foreground">{target.alias}</h3>
</div>
<p className="text-xs text-muted-foreground">{secondaryBits.join(" · ")}</p>
{savedRecord ? (
<p className="text-xs text-muted-foreground">
Saved as {savedRecord.label}
{savedRecord.lastConnectedAt
? ` · Last connected ${formatAccessTimestamp(savedRecord.lastConnectedAt)}`
: ""}
</p>
) : null}
</div>
<div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
<Button
size="xs"
variant="outline"
disabled={connectingHostAlias === target.alias}
onClick={() => onConnect(target)}
>
{connectingHostAlias === target.alias ? (
<RefreshCwIcon className="size-3 animate-spin" />
) : null}
{buttonLabel}
</Button>
</div>
</div>
</div>
);
});
export function ConnectionsSettings() {
const desktopBridge = window.desktopBridge;
const [currentSessionRole, setCurrentSessionRole] = useState<"owner" | "client" | null>(
@@ -999,6 +1120,26 @@ export function ConnectionsSettings() {
.map((record) => record.environmentId),
[savedEnvironmentsById],
);
const savedDesktopSshEnvironmentsByAlias = useMemo(
() =>
Object.values(savedEnvironmentsById).reduce<Record<string, SavedEnvironmentRecord>>(
(accumulator, record) => {
if (record.desktopSsh?.alias) {
accumulator[record.desktopSsh.alias] = record;
}
return accumulator;
},
{},
),
[savedEnvironmentsById],
);
const [discoveredSshHosts, setDiscoveredSshHosts] = useState<
ReadonlyArray<DesktopDiscoveredSshHost>
>([]);
const [hasLoadedDiscoveredSshHosts, setHasLoadedDiscoveredSshHosts] = useState(false);
const [isLoadingDiscoveredSshHosts, setIsLoadingDiscoveredSshHosts] = useState(false);
const [discoveredSshHostsError, setDiscoveredSshHostsError] = useState<string | null>(null);
const [connectingSshHostAlias, setConnectingSshHostAlias] = useState<string | null>(null);
const [desktopServerExposureState, setDesktopServerExposureState] =
useState<DesktopServerExposureState | null>(null);
@@ -1024,13 +1165,17 @@ export function ConnectionsSettings() {
>(null);
const [isRevokingOtherDesktopClients, setIsRevokingOtherDesktopClients] = useState(false);
const [addBackendDialogOpen, setAddBackendDialogOpen] = useState(false);
const [savedBackendMode, setSavedBackendMode] = useState<"pairing-url" | "host-code">(
const [savedBackendMode, setSavedBackendMode] = useState<"pairing-url" | "host-code" | "ssh">(
"pairing-url",
);
const [savedBackendLabel, setSavedBackendLabel] = useState("");
const [savedBackendPairingUrl, setSavedBackendPairingUrl] = useState("");
const [savedBackendHost, setSavedBackendHost] = useState("");
const [savedBackendPairingCode, setSavedBackendPairingCode] = useState("");
const [savedBackendSshHost, setSavedBackendSshHost] = useState("");
const [savedBackendSshUsername, setSavedBackendSshUsername] = useState("");
const [savedBackendSshPort, setSavedBackendSshPort] = useState("");
const [isManualSshFormOpen, setIsManualSshFormOpen] = useState(false);
const [savedBackendError, setSavedBackendError] = useState<string | null>(null);
const [isAddingSavedBackend, setIsAddingSavedBackend] = useState(false);
const [reconnectingSavedEnvironmentId, setReconnectingSavedEnvironmentId] =
@@ -1158,6 +1303,47 @@ export function ConnectionsSettings() {
}, []);
const handleAddSavedBackend = useCallback(async () => {
if (savedBackendMode === "ssh") {
setIsAddingSavedBackend(true);
setSavedBackendError(null);
try {
const target = parseManualDesktopSshTarget({
host: savedBackendSshHost,
username: savedBackendSshUsername,
port: savedBackendSshPort,
});
const record = await connectDesktopSshEnvironment(target, {
label: savedBackendLabel,
});
setSavedBackendLabel("");
setSavedBackendPairingUrl("");
setSavedBackendHost("");
setSavedBackendPairingCode("");
setSavedBackendSshHost("");
setSavedBackendSshUsername("");
setSavedBackendSshPort("");
setIsManualSshFormOpen(false);
setAddBackendDialogOpen(false);
toastManager.add({
type: "success",
title: "Environment connected",
description: `${record.label} is ready over an SSH-managed tunnel.`,
});
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to connect SSH host.";
setIsManualSshFormOpen(true);
setSavedBackendError(message);
toastManager.add({
type: "error",
title: "Could not connect SSH host",
description: message,
});
} finally {
setIsAddingSavedBackend(false);
}
return;
}
setIsAddingSavedBackend(true);
setSavedBackendError(null);
try {
@@ -1174,6 +1360,10 @@ export function ConnectionsSettings() {
setSavedBackendPairingUrl("");
setSavedBackendHost("");
setSavedBackendPairingCode("");
setSavedBackendSshHost("");
setSavedBackendSshUsername("");
setSavedBackendSshPort("");
setIsManualSshFormOpen(false);
setAddBackendDialogOpen(false);
toastManager.add({
type: "success",
@@ -1199,6 +1389,9 @@ export function ConnectionsSettings() {
savedBackendMode,
savedBackendPairingCode,
savedBackendPairingUrl,
savedBackendSshHost,
savedBackendSshPort,
savedBackendSshUsername,
]);
const handleReconnectSavedBackend = useCallback(async (environmentId: EnvironmentId) => {
@@ -1241,6 +1434,90 @@ export function ConnectionsSettings() {
}
}, []);
const loadDiscoveredSshHosts = useCallback(async () => {
if (!desktopBridge) {
setDiscoveredSshHosts([]);
setHasLoadedDiscoveredSshHosts(false);
setDiscoveredSshHostsError(null);
return;
}
setIsLoadingDiscoveredSshHosts(true);
setDiscoveredSshHostsError(null);
try {
const hosts = await desktopBridge.discoverSshHosts();
setDiscoveredSshHosts(hosts);
setHasLoadedDiscoveredSshHosts(true);
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to discover SSH hosts.";
setDiscoveredSshHostsError(message);
setHasLoadedDiscoveredSshHosts(true);
} finally {
setIsLoadingDiscoveredSshHosts(false);
}
}, [desktopBridge]);
const handleConnectSshHost = useCallback(
async (target: DesktopSshEnvironmentTarget, label?: string) => {
setConnectingSshHostAlias(target.alias);
if (savedBackendMode === "ssh") {
setSavedBackendError(null);
} else {
setDiscoveredSshHostsError(null);
}
try {
const record = await connectDesktopSshEnvironment(
target,
label === undefined ? undefined : { label },
);
setSavedBackendLabel("");
setSavedBackendSshHost("");
setSavedBackendSshUsername("");
setSavedBackendSshPort("");
setAddBackendDialogOpen(false);
toastManager.add({
type: "success",
title: savedDesktopSshEnvironmentsByAlias[target.alias]
? "Environment reconnected"
: "Environment connected",
description: `${record.label} is ready over an SSH-managed tunnel.`,
});
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to connect SSH host.";
if (savedBackendMode === "ssh") {
setSavedBackendError(message);
} else {
setDiscoveredSshHostsError(message);
}
toastManager.add({
type: "error",
title: "Could not connect SSH host",
description: message,
});
} finally {
setConnectingSshHostAlias(null);
}
},
[savedBackendMode, savedDesktopSshEnvironmentsByAlias],
);
useEffect(() => {
if (!desktopBridge || !addBackendDialogOpen || savedBackendMode !== "ssh") {
return;
}
if (hasLoadedDiscoveredSshHosts || isLoadingDiscoveredSshHosts) {
return;
}
void loadDiscoveredSshHosts();
}, [
addBackendDialogOpen,
desktopBridge,
hasLoadedDiscoveredSshHosts,
isLoadingDiscoveredSshHosts,
loadDiscoveredSshHosts,
savedBackendMode,
]);
useEffect(() => {
if (desktopBridge) {
setCurrentSessionRole("owner");
@@ -1598,6 +1875,7 @@ export function ConnectionsSettings() {
setAddBackendDialogOpen(open);
if (!open) {
setSavedBackendError(null);
setIsManualSshFormOpen(false);
}
}}
>
@@ -1609,7 +1887,7 @@ export function ConnectionsSettings() {
</Button>
}
/>
<DialogPopup>
<DialogPopup className="sm:max-w-3xl">
<DialogHeader>
<DialogTitle>Add Environment</DialogTitle>
<DialogDescription>Pair another environment to this client.</DialogDescription>
@@ -1640,6 +1918,21 @@ export function ConnectionsSettings() {
>
Host + code
</button>
{desktopBridge ? (
<button
type="button"
className={cn(
"flex-1 rounded-md px-3 py-1.5 text-xs font-medium transition-colors",
savedBackendMode === "ssh"
? "bg-background text-foreground shadow-xs"
: "text-muted-foreground hover:text-foreground",
)}
disabled={isAddingSavedBackend}
onClick={() => setSavedBackendMode("ssh")}
>
SSH
</button>
) : null}
</div>
</DialogHeader>
<DialogPanel>
@@ -1648,25 +1941,30 @@ export function ConnectionsSettings() {
<p className="text-xs text-muted-foreground">
Enter the full pairing URL from the environment you want to connect to.
</p>
) : (
) : savedBackendMode === "host-code" ? (
<p className="text-xs text-muted-foreground">
Enter the backend host and pairing code separately.
</p>
) : (
<p className="text-xs text-muted-foreground">
Connect over SSH using an existing alias from <code>~/.ssh/config</code> or
enter a host directly. T3 uses your current SSH agent and config.
</p>
)}
<div className="space-y-3">
<label className="block">
<span className="mb-1.5 block text-xs font-medium text-foreground">
Label
</span>
<Input
value={savedBackendLabel}
onChange={(event) => setSavedBackendLabel(event.target.value)}
placeholder="My backend (optional)"
disabled={isAddingSavedBackend}
spellCheck={false}
/>
</label>
{savedBackendMode === "pairing-url" ? (
{savedBackendMode === "pairing-url" ? (
<div className="space-y-3">
<label className="block">
<span className="mb-1.5 block text-xs font-medium text-foreground">
Label
</span>
<Input
value={savedBackendLabel}
onChange={(event) => setSavedBackendLabel(event.target.value)}
placeholder="My backend (optional)"
disabled={isAddingSavedBackend}
spellCheck={false}
/>
</label>
<label className="block">
<span className="mb-1.5 block text-xs font-medium text-foreground">
Pairing URL
@@ -1682,47 +1980,206 @@ export function ConnectionsSettings() {
The full URL including the pairing token.
</span>
</label>
) : (
<>
<label className="block">
<span className="mb-1.5 block text-xs font-medium text-foreground">
Host
</span>
<Input
value={savedBackendHost}
onChange={(event) => setSavedBackendHost(event.target.value)}
placeholder="https://backend.example.com"
disabled={isAddingSavedBackend}
spellCheck={false}
</div>
) : savedBackendMode === "host-code" ? (
<div className="space-y-3">
<label className="block">
<span className="mb-1.5 block text-xs font-medium text-foreground">
Label
</span>
<Input
value={savedBackendLabel}
onChange={(event) => setSavedBackendLabel(event.target.value)}
placeholder="My backend (optional)"
disabled={isAddingSavedBackend}
spellCheck={false}
/>
</label>
<label className="block">
<span className="mb-1.5 block text-xs font-medium text-foreground">
Host
</span>
<Input
value={savedBackendHost}
onChange={(event) => setSavedBackendHost(event.target.value)}
placeholder="https://backend.example.com"
disabled={isAddingSavedBackend}
spellCheck={false}
/>
</label>
<label className="block">
<span className="mb-1.5 block text-xs font-medium text-foreground">
Pairing code
</span>
<Input
value={savedBackendPairingCode}
onChange={(event) => setSavedBackendPairingCode(event.target.value)}
placeholder="Pairing code"
disabled={isAddingSavedBackend}
spellCheck={false}
/>
</label>
</div>
) : (
<div className="space-y-4">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<h3 className="text-sm font-medium text-foreground">Discovered hosts</h3>
<p className="text-xs text-muted-foreground">
From <code>~/.ssh/config</code> and <code>known_hosts</code>.
</p>
</div>
<Button
size="xs"
variant="outline"
disabled={isLoadingDiscoveredSshHosts}
onClick={() => void loadDiscoveredSshHosts()}
>
{isLoadingDiscoveredSshHosts ? (
<RefreshCwIcon className="size-3 animate-spin" />
) : (
<RefreshCwIcon className="size-3" />
)}
Refresh
</Button>
</div>
{discoveredSshHostsError ? (
<p className="text-xs text-destructive">{discoveredSshHostsError}</p>
) : null}
<div>
{discoveredSshHosts.map((target) => (
<DesktopSshHostRow
key={`${target.alias}:${target.hostname}:${target.port ?? ""}`}
target={target}
savedRecord={savedDesktopSshEnvironmentsByAlias[target.alias] ?? null}
connectingHostAlias={connectingSshHostAlias}
onConnect={(nextTarget) => void handleConnectSshHost(nextTarget)}
/>
</label>
<label className="block">
<span className="mb-1.5 block text-xs font-medium text-foreground">
Pairing code
</span>
<Input
value={savedBackendPairingCode}
onChange={(event) => setSavedBackendPairingCode(event.target.value)}
placeholder="Pairing code"
disabled={isAddingSavedBackend}
spellCheck={false}
))}
{hasLoadedDiscoveredSshHosts &&
!isLoadingDiscoveredSshHosts &&
discoveredSshHosts.length === 0 ? (
<div className={ITEM_ROW_CLASSNAME}>
<p className="text-xs text-muted-foreground">
No SSH hosts were discovered from <code>~/.ssh/config</code> or{" "}
<code>known_hosts</code>.
</p>
</div>
) : null}
</div>
{savedBackendError ? (
<p className="text-xs text-destructive">{savedBackendError}</p>
) : null}
<Collapsible open={isManualSshFormOpen} onOpenChange={setIsManualSshFormOpen}>
<CollapsibleTrigger
className={cn(
"flex w-full items-center justify-between gap-3 rounded-md border border-border/60 px-4 py-3 text-left transition-colors hover:bg-muted/35",
isManualSshFormOpen && "bg-muted/20",
)}
>
<div className="min-w-0">
<p className="text-sm font-medium text-foreground">
Enter a host manually
</p>
<p className="text-xs text-muted-foreground">
Use an alias or enter host, username, and port directly.
</p>
</div>
<ChevronDownIcon
className={cn(
"size-4 shrink-0 text-muted-foreground transition-transform duration-200",
isManualSshFormOpen && "rotate-180",
)}
/>
</label>
</>
)}
</div>
{savedBackendError ? (
</CollapsibleTrigger>
<CollapsibleContent className="pt-4">
<div className="space-y-3">
<label className="block">
<span className="mb-1.5 block text-xs font-medium text-foreground">
Label
</span>
<Input
value={savedBackendLabel}
onChange={(event) => setSavedBackendLabel(event.target.value)}
placeholder="My backend (optional)"
disabled={isAddingSavedBackend}
spellCheck={false}
/>
</label>
<label className="block">
<span className="mb-1.5 block text-xs font-medium text-foreground">
SSH host or alias
</span>
<Input
value={savedBackendSshHost}
onChange={(event) => setSavedBackendSshHost(event.target.value)}
placeholder="devbox or devbox.example.com"
disabled={isAddingSavedBackend}
spellCheck={false}
/>
</label>
<div className="grid gap-3 sm:grid-cols-2">
<label className="block">
<span className="mb-1.5 block text-xs font-medium text-foreground">
Username
</span>
<Input
value={savedBackendSshUsername}
onChange={(event) =>
setSavedBackendSshUsername(event.target.value)
}
placeholder="julius"
disabled={isAddingSavedBackend}
spellCheck={false}
/>
</label>
<label className="block">
<span className="mb-1.5 block text-xs font-medium text-foreground">
Port
</span>
<Input
value={savedBackendSshPort}
onChange={(event) => setSavedBackendSshPort(event.target.value)}
placeholder="22"
inputMode="numeric"
disabled={isAddingSavedBackend}
spellCheck={false}
/>
</label>
</div>
<span className="block text-[11px] text-muted-foreground">
Uses your existing SSH keys, agent, and config. Password and
keyboard-interactive prompts open through your system SSH dialog when
needed.
</span>
<Button
variant="outline"
className="w-full"
disabled={isAddingSavedBackend}
onClick={() => void handleAddSavedBackend()}
>
<PlusIcon className="size-3.5" />
{isAddingSavedBackend ? "Connecting…" : "Connect SSH host"}
</Button>
</div>
</CollapsibleContent>
</Collapsible>
</div>
)}
{savedBackendMode !== "ssh" && savedBackendError ? (
<p className="text-xs text-destructive">{savedBackendError}</p>
) : null}
<Button
variant="outline"
className="w-full"
disabled={isAddingSavedBackend}
onClick={() => void handleAddSavedBackend()}
>
<PlusIcon className="size-3.5" />
{isAddingSavedBackend ? "Adding…" : "Add Backend"}
</Button>
{savedBackendMode !== "ssh" ? (
<Button
variant="outline"
className="w-full"
disabled={isAddingSavedBackend}
onClick={() => void handleAddSavedBackend()}
>
<PlusIcon className="size-3.5" />
{isAddingSavedBackend ? "Adding…" : "Add Backend"}
</Button>
) : null}
</div>
</DialogPanel>
</DialogPopup>
@@ -114,6 +114,8 @@ const authAccessHarness = vi.hoisted(() => {
};
});
const mockConnectDesktopSshEnvironment = vi.fn();
vi.mock("../../environments/runtime", () => {
const primaryConnection = {
kind: "primary" as const,
@@ -151,6 +153,7 @@ vi.mock("../../environments/runtime", () => {
new URL(path, "http://localhost:3000").toString(),
waitForSavedEnvironmentRegistryHydration: async () => undefined,
addSavedEnvironment: vi.fn(),
connectDesktopSshEnvironment: mockConnectDesktopSshEnvironment,
disconnectSavedEnvironment: vi.fn(),
ensureEnvironmentConnectionBootstrapped: async () => undefined,
getPrimaryEnvironmentConnection: () => primaryConnection,
@@ -258,6 +261,7 @@ function makeClientSession(input: {
}
const createDesktopBridgeStub = (overrides?: {
readonly discoverSshHosts?: DesktopBridge["discoverSshHosts"];
readonly serverExposureState?: Awaited<ReturnType<DesktopBridge["getServerExposureState"]>>;
readonly advertisedEndpoints?: Awaited<ReturnType<DesktopBridge["getAdvertisedEndpoints"]>>;
readonly setServerExposureMode?: DesktopBridge["setServerExposureMode"];
@@ -295,6 +299,50 @@ const createDesktopBridgeStub = (overrides?: {
getSavedEnvironmentSecret: vi.fn().mockResolvedValue(null),
setSavedEnvironmentSecret: vi.fn().mockResolvedValue(true),
removeSavedEnvironmentSecret: vi.fn().mockResolvedValue(undefined),
discoverSshHosts: overrides?.discoverSshHosts ?? vi.fn().mockResolvedValue([]),
ensureSshEnvironment: vi.fn().mockImplementation(async (target) => ({
target,
httpBaseUrl: "http://127.0.0.1:3774/",
wsBaseUrl: "ws://127.0.0.1:3774/",
pairingToken: "ssh-pairing-token",
})),
fetchSshEnvironmentDescriptor: vi.fn().mockResolvedValue({
environmentId: "environment-ssh",
label: "SSH environment",
platform: {
os: "linux",
arch: "x64",
},
serverVersion: "0.0.0-test",
capabilities: {
repositoryIdentity: true,
},
}),
bootstrapSshBearerSession: vi.fn().mockResolvedValue({
authenticated: true,
role: "owner",
sessionMethod: "bearer-session-token",
expiresAt: "2026-05-01T12:00:00.000Z",
sessionToken: "ssh-bearer-token",
}),
fetchSshSessionState: vi.fn().mockResolvedValue({
authenticated: true,
auth: {
policy: "remote-reachable",
bootstrapMethods: ["one-time-token"],
sessionMethods: ["browser-session-cookie", "bearer-session-token"],
sessionCookieName: "t3_session",
},
role: "owner",
sessionMethod: "bearer-session-token",
expiresAt: "2026-05-01T12:00:00.000Z",
}),
issueSshWebSocketToken: vi.fn().mockResolvedValue({
token: "ssh-ws-token",
expiresAt: "2026-05-01T12:05:00.000Z",
}),
onSshPasswordPrompt: vi.fn(() => () => {}),
resolveSshPasswordPrompt: vi.fn().mockResolvedValue(undefined),
getServerExposureState: vi.fn().mockResolvedValue(
overrides?.serverExposureState ?? {
mode: "local-only",
@@ -348,6 +396,7 @@ describe("GeneralSettingsPanel observability", () => {
localStorage.clear();
useUiStateStore.setState({ defaultAdvertisedEndpointKey: null });
authAccessHarness.reset();
mockConnectDesktopSshEnvironment.mockReset();
});
afterEach(async () => {
@@ -852,6 +901,70 @@ describe("GeneralSettingsPanel observability", () => {
.toBeInTheDocument();
});
it("adds desktop ssh environments from the add-environment dialog", async () => {
const discoverSshHosts = vi.fn().mockResolvedValue([
{
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
source: "ssh-config" as const,
},
]);
window.desktopBridge = createDesktopBridgeStub({
discoverSshHosts,
});
mockConnectDesktopSshEnvironment.mockResolvedValue({
environmentId: EnvironmentId.make("environment-devbox"),
label: "Build box",
wsBaseUrl: "ws://127.0.0.1:3774/",
httpBaseUrl: "http://127.0.0.1:3774/",
createdAt: "2036-04-07T00:00:00.000Z",
lastConnectedAt: "2036-04-07T00:00:00.000Z",
desktopSsh: {
alias: "devbox.example.com",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
},
});
setServerConfigSnapshot(createBaseServerConfig());
mounted = await render(
<AppAtomRegistryProvider>
<ConnectionsSettings />
</AppAtomRegistryProvider>,
);
await page.getByRole("button", { name: "Add environment", exact: true }).click();
await expect.element(page.getByText("Add Environment")).toBeInTheDocument();
await page.getByRole("button", { name: "SSH", exact: true }).click();
await vi.waitFor(() => {
expect(discoverSshHosts).toHaveBeenCalledTimes(1);
});
await expect.element(page.getByText("devbox")).toBeInTheDocument();
await page.getByText("Enter a host manually").click();
await page.getByLabelText("Label").fill("Build box");
await page.getByLabelText("SSH host or alias").fill("devbox.example.com");
await page.getByLabelText("Username").fill("julius");
await page.getByLabelText("Port").fill("2222");
await page.getByRole("button", { name: "Connect SSH host", exact: true }).click();
await vi.waitFor(() => {
expect(mockConnectDesktopSshEnvironment).toHaveBeenCalledWith(
{
alias: "devbox.example.com",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
},
{ label: "Build box" },
);
});
});
it("opens the logs folder in the preferred editor", async () => {
const openInEditor = vi.fn<LocalApi["shell"]["openInEditor"]>().mockResolvedValue(undefined);
window.nativeApi = {
+2 -2
View File
@@ -24,7 +24,7 @@ function DialogBackdrop({ className, ...props }: DialogPrimitive.Backdrop.Props)
return (
<DialogPrimitive.Backdrop
className={cn(
"fixed inset-0 z-50 bg-black/32 backdrop-blur-sm transition-all duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0",
"fixed inset-0 z-50 transition-all duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0",
className,
)}
data-slot="dialog-backdrop"
@@ -37,7 +37,7 @@ function DialogViewport({ className, ...props }: DialogPrimitive.Viewport.Props)
return (
<DialogPrimitive.Viewport
className={cn(
"fixed inset-0 z-50 grid grid-rows-[1fr_auto_3fr] justify-items-center p-4",
"fixed inset-0 z-50 grid grid-rows-[1fr_auto_3fr] justify-items-center bg-white/48 p-4 backdrop-blur-[2px] dark:bg-black/28",
className,
)}
data-slot="dialog-viewport"
+6
View File
@@ -15,6 +15,12 @@ class RemoteEnvironmentAuthHttpError extends Error {
}
}
export function isRemoteEnvironmentAuthHttpError(
error: unknown,
): error is RemoteEnvironmentAuthHttpError {
return error instanceof RemoteEnvironmentAuthHttpError;
}
function remoteEndpointUrl(httpBaseUrl: string, pathname: string): string {
const url = new URL(httpBaseUrl);
url.pathname = pathname;
@@ -18,6 +18,7 @@ export interface SavedEnvironmentRecord {
readonly httpBaseUrl: string;
readonly createdAt: string;
readonly lastConnectedAt: string | null;
readonly desktopSsh?: PersistedSavedEnvironmentRecord["desktopSsh"];
}
interface SavedEnvironmentRegistryState {
@@ -44,6 +45,7 @@ function toPersistedSavedEnvironmentRecord(
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
};
}
@@ -16,6 +16,7 @@ export {
export {
addSavedEnvironment,
connectDesktopSshEnvironment,
disconnectSavedEnvironment,
ensureEnvironmentConnectionBootstrapped,
getPrimaryEnvironmentConnection,
@@ -4,11 +4,15 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const mockResolveRemotePairingTarget = vi.fn();
const mockFetchRemoteEnvironmentDescriptor = vi.fn();
const mockBootstrapRemoteBearerSession = vi.fn();
const mockBootstrapSshBearerSession = vi.fn();
const mockPersistSavedEnvironmentRecord = vi.fn();
const mockWriteSavedEnvironmentBearerToken = vi.fn();
const mockSetSavedEnvironmentRegistry = vi.fn();
const mockUpsert = vi.fn();
const mockListSavedEnvironmentRecords = vi.fn();
const mockEnsureSshEnvironment = vi.fn();
const mockFetchSshEnvironmentDescriptor = vi.fn();
const mockCreateEnvironmentConnection = vi.fn();
vi.mock("../remote/target", () => ({
resolveRemotePairingTarget: mockResolveRemotePairingTarget,
@@ -18,6 +22,7 @@ vi.mock("../remote/api", () => ({
bootstrapRemoteBearerSession: mockBootstrapRemoteBearerSession,
fetchRemoteEnvironmentDescriptor: mockFetchRemoteEnvironmentDescriptor,
fetchRemoteSessionState: vi.fn(),
isRemoteEnvironmentAuthHttpError: vi.fn(() => false),
resolveRemoteWebSocketConnectionUrl: vi.fn(),
}));
@@ -55,18 +60,37 @@ vi.mock("./catalog", () => ({
}));
vi.mock("./connection", () => ({
createEnvironmentConnection: vi.fn(),
createEnvironmentConnection: mockCreateEnvironmentConnection,
}));
describe("addSavedEnvironment", () => {
beforeEach(() => {
vi.resetModules();
vi.clearAllMocks();
mockResolveRemotePairingTarget.mockReturnValue({
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
credential: "pairing-code",
vi.stubGlobal("window", {
desktopBridge: {
ensureSshEnvironment: mockEnsureSshEnvironment,
fetchSshEnvironmentDescriptor: mockFetchSshEnvironmentDescriptor,
bootstrapSshBearerSession: mockBootstrapSshBearerSession,
fetchSshSessionState: vi.fn(),
issueSshWebSocketToken: vi.fn(),
},
});
mockResolveRemotePairingTarget.mockImplementation(
(input: { host?: string; pairingCode?: string }) => ({
httpBaseUrl: input.host
? input.host.endsWith("/")
? input.host
: `${input.host}/`
: "https://remote.example.com/",
wsBaseUrl: input.host
? input.host.replace(/^http/u, "ws").endsWith("/")
? input.host.replace(/^http/u, "ws")
: `${input.host.replace(/^http/u, "ws")}/`
: "wss://remote.example.com/",
credential: input.pairingCode ?? "pairing-code",
}),
);
mockFetchRemoteEnvironmentDescriptor.mockResolvedValue({
environmentId: EnvironmentId.make("environment-1"),
label: "Remote environment",
@@ -75,10 +99,40 @@ describe("addSavedEnvironment", () => {
sessionToken: "bearer-token",
role: "owner",
});
mockFetchSshEnvironmentDescriptor.mockResolvedValue({
environmentId: EnvironmentId.make("environment-1"),
label: "Remote environment",
});
mockBootstrapSshBearerSession.mockResolvedValue({
sessionToken: "ssh-bearer-token",
role: "owner",
});
mockPersistSavedEnvironmentRecord.mockResolvedValue(undefined);
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(false);
mockSetSavedEnvironmentRegistry.mockResolvedValue(undefined);
mockListSavedEnvironmentRecords.mockReturnValue([]);
mockCreateEnvironmentConnection.mockImplementation(
(input: { knownEnvironment: { environmentId: EnvironmentId }; client: unknown }) => ({
kind: "saved",
environmentId: input.knownEnvironment.environmentId,
knownEnvironment: input.knownEnvironment,
client: input.client,
ensureBootstrapped: async () => undefined,
reconnect: async () => undefined,
dispose: async () => undefined,
}),
);
mockEnsureSshEnvironment.mockResolvedValue({
target: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
httpBaseUrl: "http://127.0.0.1:3774/",
wsBaseUrl: "ws://127.0.0.1:3774/",
pairingToken: "ssh-pairing-code",
});
});
it("rolls back persisted metadata when bearer token persistence fails", async () => {
@@ -102,4 +156,46 @@ describe("addSavedEnvironment", () => {
await resetEnvironmentServiceForTests();
});
it("bootstraps a desktop ssh environment through the desktop bridge", async () => {
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
const { connectDesktopSshEnvironment, resetEnvironmentServiceForTests } =
await import("./service");
await expect(
connectDesktopSshEnvironment({
alias: "devbox",
hostname: "devbox",
username: null,
port: null,
}),
).rejects.toThrow();
expect(mockEnsureSshEnvironment).toHaveBeenCalledWith(
{
alias: "devbox",
hostname: "devbox",
username: null,
port: null,
},
{ issuePairingToken: true },
);
expect(mockResolveRemotePairingTarget).toHaveBeenCalledWith({
host: "http://127.0.0.1:3774/",
pairingCode: "ssh-pairing-code",
});
expect(mockFetchSshEnvironmentDescriptor).toHaveBeenCalledWith("http://127.0.0.1:3774/");
expect(mockBootstrapSshBearerSession).toHaveBeenCalledWith(
"http://127.0.0.1:3774/",
"ssh-pairing-code",
);
expect(mockFetchRemoteEnvironmentDescriptor).not.toHaveBeenCalled();
expect(mockBootstrapRemoteBearerSession).not.toHaveBeenCalled();
expect(mockUpsert.mock.invocationCallOrder[0]).toBeLessThan(
mockCreateEnvironmentConnection.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
);
await resetEnvironmentServiceForTests();
});
});
+369 -102
View File
@@ -1,5 +1,7 @@
import {
type AuthSessionRole,
type DesktopSshEnvironmentBootstrap,
type DesktopSshEnvironmentTarget,
type EnvironmentId,
type OrchestrationEvent,
type OrchestrationShellSnapshot,
@@ -33,6 +35,7 @@ import {
bootstrapRemoteBearerSession,
fetchRemoteEnvironmentDescriptor,
fetchRemoteSessionState,
isRemoteEnvironmentAuthHttpError,
resolveRemoteWebSocketConnectionUrl,
} from "../remote/api";
import { resolveRemotePairingTarget } from "../remote/target";
@@ -85,6 +88,7 @@ type ThreadDetailSubscriptionEntry = {
};
const environmentConnections = new Map<EnvironmentId, EnvironmentConnection>();
const pendingSavedEnvironmentConnections = new Map<EnvironmentId, Promise<EnvironmentConnection>>();
const environmentConnectionListeners = new Set<() => void>();
const threadDetailSubscriptions = new Map<string, ThreadDetailSubscriptionEntry>();
const lastAppliedProjectionVersionByEnvironment = new Map<
@@ -491,6 +495,163 @@ function isoNow(): string {
return new Date().toISOString();
}
function serializeSavedEnvironmentRecord(record: SavedEnvironmentRecord) {
return {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
} as const;
}
function isDesktopSshTargetEqual(
left: DesktopSshEnvironmentTarget | undefined,
right: DesktopSshEnvironmentTarget | undefined,
): boolean {
if (!left || !right) {
return false;
}
return (
left.alias === right.alias &&
left.hostname === right.hostname &&
left.username === right.username &&
left.port === right.port
);
}
function findSavedEnvironmentRecordByDesktopSshTarget(
target: DesktopSshEnvironmentTarget | undefined,
): SavedEnvironmentRecord | null {
if (!target) {
return null;
}
return (
listSavedEnvironmentRecords().find((record) =>
isDesktopSshTargetEqual(record.desktopSsh, target),
) ?? null
);
}
async function persistSavedEnvironmentRegistryRollback(): Promise<void> {
await ensureLocalApi().persistence.setSavedEnvironmentRegistry(
listSavedEnvironmentRecords().map((entry) => serializeSavedEnvironmentRecord(entry)),
);
}
async function resolveDesktopSshEnvironmentBootstrap(
target: DesktopSshEnvironmentTarget,
options?: { readonly issuePairingToken?: boolean },
): Promise<DesktopSshEnvironmentBootstrap> {
const desktopBridge = window.desktopBridge;
if (!desktopBridge) {
throw new Error("SSH launch is only available in the desktop app.");
}
return await desktopBridge.ensureSshEnvironment(target, options);
}
function getDesktopSshBridge() {
const desktopBridge = window.desktopBridge;
if (!desktopBridge) {
throw new Error("SSH launch is only available in the desktop app.");
}
return desktopBridge;
}
async function fetchDesktopSshEnvironmentDescriptor(httpBaseUrl: string) {
return await getDesktopSshBridge().fetchSshEnvironmentDescriptor(httpBaseUrl);
}
async function bootstrapDesktopSshBearerSession(httpBaseUrl: string, credential: string) {
return await getDesktopSshBridge().bootstrapSshBearerSession(httpBaseUrl, credential);
}
async function fetchDesktopSshSessionState(httpBaseUrl: string, bearerToken: string) {
return await getDesktopSshBridge().fetchSshSessionState(httpBaseUrl, bearerToken);
}
async function resolveDesktopSshWebSocketConnectionUrl(
wsBaseUrl: string,
httpBaseUrl: string,
bearerToken: string,
) {
const issued = await getDesktopSshBridge().issueSshWebSocketToken(httpBaseUrl, bearerToken);
const url = new URL(wsBaseUrl, window.location.origin);
url.searchParams.set("wsToken", issued.token);
return url.toString();
}
async function prepareSavedEnvironmentRecordForConnection(
record: SavedEnvironmentRecord,
options?: { readonly issuePairingToken?: boolean },
): Promise<{
readonly record: SavedEnvironmentRecord;
readonly pairingToken: string | null;
}> {
if (!record.desktopSsh) {
return { record, pairingToken: null };
}
const bootstrap = await resolveDesktopSshEnvironmentBootstrap(record.desktopSsh, options);
const nextRecord: SavedEnvironmentRecord = {
...record,
httpBaseUrl: bootstrap.httpBaseUrl,
wsBaseUrl: bootstrap.wsBaseUrl,
desktopSsh: bootstrap.target,
};
if (
nextRecord.httpBaseUrl !== record.httpBaseUrl ||
nextRecord.wsBaseUrl !== record.wsBaseUrl ||
!isDesktopSshTargetEqual(nextRecord.desktopSsh, record.desktopSsh)
) {
await persistSavedEnvironmentRecord(nextRecord);
useSavedEnvironmentRegistryStore.getState().upsert(nextRecord);
}
return {
record: nextRecord,
pairingToken: bootstrap.pairingToken,
};
}
async function issueDesktopSshBearerSession(record: SavedEnvironmentRecord): Promise<{
readonly record: SavedEnvironmentRecord;
readonly bearerToken: string;
readonly role: AuthSessionRole | null;
}> {
const prepared = await prepareSavedEnvironmentRecordForConnection(record, {
issuePairingToken: true,
});
if (!prepared.pairingToken) {
throw new Error("Desktop SSH launch did not return a pairing token.");
}
const bearerSession = await bootstrapDesktopSshBearerSession(
prepared.record.httpBaseUrl,
prepared.pairingToken,
);
const didPersistBearerToken = await writeSavedEnvironmentBearerToken(
prepared.record.environmentId,
bearerSession.sessionToken,
);
if (!didPersistBearerToken) {
await persistSavedEnvironmentRegistryRollback();
throw new Error("Unable to persist saved environment credentials.");
}
return {
record: prepared.record,
bearerToken: bearerSession.sessionToken,
role: bearerSession.role ?? null,
};
}
function setRuntimeConnecting(environmentId: EnvironmentId) {
useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
connectionState: "connecting",
@@ -802,35 +963,46 @@ function createPrimaryEnvironmentClient(
}
function createSavedEnvironmentClient(
record: SavedEnvironmentRecord,
environmentId: EnvironmentId,
bearerToken: string,
): WsRpcClient {
useSavedEnvironmentRuntimeStore.getState().ensure(record.environmentId);
useSavedEnvironmentRuntimeStore.getState().ensure(environmentId);
return createWsRpcClient(
new WsTransport(
() =>
resolveRemoteWebSocketConnectionUrl({
wsBaseUrl: record.wsBaseUrl,
httpBaseUrl: record.httpBaseUrl,
bearerToken,
}),
async () => {
const record = getSavedEnvironmentRecord(environmentId);
if (!record) {
throw new Error(`Saved environment ${environmentId} not found.`);
}
return record.desktopSsh
? await resolveDesktopSshWebSocketConnectionUrl(
record.wsBaseUrl,
record.httpBaseUrl,
bearerToken,
)
: await resolveRemoteWebSocketConnectionUrl({
wsBaseUrl: record.wsBaseUrl,
httpBaseUrl: record.httpBaseUrl,
bearerToken,
});
},
{
onAttempt: () => {
setRuntimeConnecting(record.environmentId);
setRuntimeConnecting(environmentId);
},
onOpen: () => {
setRuntimeConnected(record.environmentId);
setRuntimeConnected(environmentId);
},
onError: (message: string) => {
useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
connectionState: "error",
lastError: message,
lastErrorAt: isoNow(),
});
},
onClose: (details: { readonly code: number; readonly reason: string }) => {
setRuntimeDisconnected(record.environmentId, details.reason);
setRuntimeDisconnected(environmentId, details.reason);
},
},
),
@@ -838,18 +1010,25 @@ function createSavedEnvironmentClient(
}
async function refreshSavedEnvironmentMetadata(
record: SavedEnvironmentRecord,
environmentId: EnvironmentId,
bearerToken: string,
client: WsRpcClient,
roleHint?: AuthSessionRole | null,
configHint?: ServerConfig | null,
): Promise<void> {
const record = getSavedEnvironmentRecord(environmentId);
if (!record) {
throw new Error(`Saved environment ${environmentId} not found.`);
}
const [serverConfig, sessionState] = await Promise.all([
configHint ? Promise.resolve(configHint) : client.server.getConfig(),
fetchRemoteSessionState({
httpBaseUrl: record.httpBaseUrl,
bearerToken,
}),
record.desktopSsh
? fetchDesktopSshSessionState(record.httpBaseUrl, bearerToken)
: fetchRemoteSessionState({
httpBaseUrl: record.httpBaseUrl,
bearerToken,
}),
]);
useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
@@ -923,69 +1102,124 @@ async function ensureSavedEnvironmentConnection(
return existing;
}
const bearerToken =
options?.bearerToken ?? (await readSavedEnvironmentBearerToken(record.environmentId));
if (!bearerToken) {
useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
authState: "requires-auth",
role: null,
connectionState: "disconnected",
lastError: "Saved environment is missing its saved credential. Pair it again.",
lastErrorAt: isoNow(),
const pending = pendingSavedEnvironmentConnections.get(record.environmentId);
if (pending) {
return pending;
}
const nextConnection = (async () => {
let activeRecord = record;
let roleHint = options?.role ?? null;
let bearerToken =
options?.bearerToken ?? (await readSavedEnvironmentBearerToken(record.environmentId));
if (!bearerToken) {
if (record.desktopSsh) {
const issued = await issueDesktopSshBearerSession(record);
activeRecord = issued.record;
bearerToken = issued.bearerToken;
roleHint = issued.role;
} else {
useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
authState: "requires-auth",
role: null,
connectionState: "disconnected",
lastError: "Saved environment is missing its saved credential. Pair it again.",
lastErrorAt: isoNow(),
});
throw new Error("Saved environment is missing its saved credential.");
}
} else {
const prepared = await prepareSavedEnvironmentRecordForConnection(record);
activeRecord = prepared.record;
}
const activeBearerToken = bearerToken;
const client =
options?.client ??
createSavedEnvironmentClient(activeRecord.environmentId, activeBearerToken);
const knownEnvironment = createKnownEnvironment({
id: activeRecord.environmentId,
label: activeRecord.label,
source: "manual",
target: {
httpBaseUrl: activeRecord.httpBaseUrl,
wsBaseUrl: activeRecord.wsBaseUrl,
},
});
throw new Error("Saved environment is missing its saved credential.");
}
const client = options?.client ?? createSavedEnvironmentClient(record, bearerToken);
const knownEnvironment = createKnownEnvironment({
id: record.environmentId,
label: record.label,
source: "manual",
target: {
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
},
});
const connection = createEnvironmentConnection({
kind: "saved",
knownEnvironment: {
...knownEnvironment,
environmentId: record.environmentId,
},
client,
refreshMetadata: async () => {
await refreshSavedEnvironmentMetadata(record, bearerToken, client);
},
onConfigSnapshot: (config) => {
useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
descriptor: config.environment,
serverConfig: config,
});
},
onWelcome: (payload) => {
useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
descriptor: payload.environment,
});
},
...createEnvironmentConnectionHandlers(),
});
registerConnection(connection);
try {
await refreshSavedEnvironmentMetadata(
record,
bearerToken,
const connection = createEnvironmentConnection({
kind: "saved",
knownEnvironment: {
...knownEnvironment,
environmentId: activeRecord.environmentId,
},
client,
options?.role ?? null,
options?.serverConfig ?? null,
);
return connection;
} catch (error) {
setRuntimeError(record.environmentId, error);
await removeConnection(record.environmentId).catch(() => false);
throw error;
}
refreshMetadata: async () => {
await refreshSavedEnvironmentMetadata(
activeRecord.environmentId,
activeBearerToken,
client,
);
},
onConfigSnapshot: (config) => {
useSavedEnvironmentRuntimeStore.getState().patch(activeRecord.environmentId, {
descriptor: config.environment,
serverConfig: config,
});
},
onWelcome: (payload) => {
useSavedEnvironmentRuntimeStore.getState().patch(activeRecord.environmentId, {
descriptor: payload.environment,
});
},
...createEnvironmentConnectionHandlers(),
});
registerConnection(connection);
try {
try {
await refreshSavedEnvironmentMetadata(
activeRecord.environmentId,
activeBearerToken,
client,
roleHint,
options?.serverConfig ?? null,
);
} catch (error) {
if (
!record.desktopSsh ||
!isRemoteEnvironmentAuthHttpError(error) ||
error.status !== 401
) {
throw error;
}
const issued = await issueDesktopSshBearerSession(activeRecord);
activeRecord = issued.record;
bearerToken = issued.bearerToken;
roleHint = issued.role;
await removeConnection(activeRecord.environmentId).catch(() => false);
pendingSavedEnvironmentConnections.delete(activeRecord.environmentId);
return await ensureSavedEnvironmentConnection(activeRecord, {
bearerToken,
role: roleHint,
serverConfig: options?.serverConfig ?? null,
});
}
return connection;
} catch (error) {
setRuntimeError(activeRecord.environmentId, error);
await removeConnection(activeRecord.environmentId).catch(() => false);
throw error;
}
})();
pendingSavedEnvironmentConnections.set(record.environmentId, nextConnection);
return await nextConnection.finally(() => {
if (pendingSavedEnvironmentConnections.get(record.environmentId) === nextConnection) {
pendingSavedEnvironmentConnections.delete(record.environmentId);
}
});
}
async function syncSavedEnvironmentConnections(
@@ -1063,8 +1297,22 @@ export async function reconnectSavedEnvironment(environmentId: EnvironmentId): P
setRuntimeConnecting(environmentId);
try {
if (record.desktopSsh) {
await prepareSavedEnvironmentRecordForConnection(record);
}
await connection.reconnect();
} catch (error) {
if (record.desktopSsh) {
const issued = await issueDesktopSshBearerSession(
getSavedEnvironmentRecord(environmentId) ?? record,
);
await removeConnection(environmentId).catch(() => false);
await ensureSavedEnvironmentConnection(issued.record, {
bearerToken: issued.bearerToken,
role: issued.role,
});
return;
}
setRuntimeError(environmentId, error);
throw error;
}
@@ -1081,33 +1329,40 @@ export async function addSavedEnvironment(input: {
readonly pairingUrl?: string;
readonly host?: string;
readonly pairingCode?: string;
readonly desktopSsh?: DesktopSshEnvironmentTarget;
}): Promise<SavedEnvironmentRecord> {
const resolvedTarget = resolveRemotePairingTarget({
...(input.pairingUrl !== undefined ? { pairingUrl: input.pairingUrl } : {}),
...(input.host !== undefined ? { host: input.host } : {}),
...(input.pairingCode !== undefined ? { pairingCode: input.pairingCode } : {}),
});
const descriptor = await fetchRemoteEnvironmentDescriptor({
httpBaseUrl: resolvedTarget.httpBaseUrl,
});
const descriptor = input.desktopSsh
? await fetchDesktopSshEnvironmentDescriptor(resolvedTarget.httpBaseUrl)
: await fetchRemoteEnvironmentDescriptor({
httpBaseUrl: resolvedTarget.httpBaseUrl,
});
const environmentId = descriptor.environmentId;
const existingRecord =
getSavedEnvironmentRecord(environmentId) ??
findSavedEnvironmentRecordByDesktopSshTarget(input.desktopSsh);
if (environmentConnections.has(environmentId)) {
throw new Error("This environment is already connected.");
}
const bearerSession = await bootstrapRemoteBearerSession({
httpBaseUrl: resolvedTarget.httpBaseUrl,
credential: resolvedTarget.credential,
});
const bearerSession = input.desktopSsh
? await bootstrapDesktopSshBearerSession(resolvedTarget.httpBaseUrl, resolvedTarget.credential)
: await bootstrapRemoteBearerSession({
httpBaseUrl: resolvedTarget.httpBaseUrl,
credential: resolvedTarget.credential,
});
const record: SavedEnvironmentRecord = {
environmentId,
label: input.label.trim() || descriptor.label,
label: input.label.trim() || existingRecord?.label || descriptor.label,
wsBaseUrl: resolvedTarget.wsBaseUrl,
httpBaseUrl: resolvedTarget.httpBaseUrl,
createdAt: isoNow(),
createdAt: existingRecord?.createdAt ?? isoNow(),
lastConnectedAt: isoNow(),
...((input.desktopSsh ?? existingRecord?.desktopSsh)
? { desktopSsh: input.desktopSsh ?? existingRecord?.desktopSsh }
: {}),
};
await persistSavedEnvironmentRecord(record);
@@ -1116,26 +1371,37 @@ export async function addSavedEnvironment(input: {
bearerSession.sessionToken,
);
if (!didPersistBearerToken) {
await ensureLocalApi().persistence.setSavedEnvironmentRegistry(
listSavedEnvironmentRecords().map((entry) => ({
environmentId: entry.environmentId,
label: entry.label,
httpBaseUrl: entry.httpBaseUrl,
wsBaseUrl: entry.wsBaseUrl,
createdAt: entry.createdAt,
lastConnectedAt: entry.lastConnectedAt,
})),
);
await persistSavedEnvironmentRegistryRollback();
throw new Error("Unable to persist saved environment credentials.");
}
useSavedEnvironmentRegistryStore.getState().upsert(record);
await removeConnection(environmentId).catch(() => false);
await ensureSavedEnvironmentConnection(record, {
bearerToken: bearerSession.sessionToken,
role: bearerSession.role,
});
useSavedEnvironmentRegistryStore.getState().upsert(record);
return record;
}
export async function connectDesktopSshEnvironment(
target: DesktopSshEnvironmentTarget,
options?: { label?: string },
): Promise<SavedEnvironmentRecord> {
const bootstrap = await resolveDesktopSshEnvironmentBootstrap(target, {
issuePairingToken: true,
});
if (!bootstrap.pairingToken) {
throw new Error("Desktop SSH launch did not return a pairing token.");
}
return await addSavedEnvironment({
label: options?.label?.trim() || bootstrap.target.alias,
host: bootstrap.httpBaseUrl,
pairingCode: bootstrap.pairingToken,
desktopSsh: bootstrap.target,
});
}
export async function ensureEnvironmentConnectionBootstrapped(
environmentId: EnvironmentId,
): Promise<void> {
@@ -1211,6 +1477,7 @@ export function startEnvironmentConnectionService(queryClient: QueryClient): ()
export async function resetEnvironmentServiceForTests(): Promise<void> {
stopActiveService();
lastAppliedProjectionVersionByEnvironment.clear();
pendingSavedEnvironmentConnections.clear();
for (const key of Array.from(threadDetailSubscriptions.keys())) {
disposeThreadDetailSubscriptionByKey(key);
}
+18
View File
@@ -169,6 +169,24 @@ function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): DesktopBridg
getSavedEnvironmentSecret: async () => null,
setSavedEnvironmentSecret: async () => true,
removeSavedEnvironmentSecret: async () => undefined,
discoverSshHosts: async () => [],
ensureSshEnvironment: async () => {
throw new Error("ensureSshEnvironment not implemented in test");
},
fetchSshEnvironmentDescriptor: async () => {
throw new Error("fetchSshEnvironmentDescriptor not implemented in test");
},
bootstrapSshBearerSession: async () => {
throw new Error("bootstrapSshBearerSession not implemented in test");
},
fetchSshSessionState: async () => {
throw new Error("fetchSshSessionState not implemented in test");
},
issueSshWebSocketToken: async () => {
throw new Error("issueSshWebSocketToken not implemented in test");
},
onSshPasswordPrompt: () => () => undefined,
resolveSshPasswordPrompt: async () => undefined,
getServerExposureState: async () => ({
mode: "local-only",
endpointUrl: null,
+2
View File
@@ -13,6 +13,7 @@ import { QueryClient, useQueryClient } from "@tanstack/react-query";
import { APP_DISPLAY_NAME } from "../branding";
import { AppSidebarLayout } from "../components/AppSidebarLayout";
import { CommandPalette } from "../components/CommandPalette";
import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
import {
SlowRpcAckToastCoordinator,
WebSocketConnectionCoordinator,
@@ -145,6 +146,7 @@ function RootRouteView() {
{primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
{primaryEnvironmentAuthenticated ? <ServerStateBootstrap /> : null}
<EnvironmentConnectionManagerBootstrap />
<SshPasswordPromptDialog />
<HostedStaticEnvironmentBootstrap />
{primaryEnvironmentAuthenticated ? <EventRouter /> : null}
{primaryEnvironmentAuthenticated ? <WebSocketConnectionCoordinator /> : null}
+48 -1
View File
@@ -52,9 +52,11 @@ import type {
OrchestrationThreadStreamItem,
} from "./orchestration.ts";
import type { EnvironmentId } from "./baseSchemas.ts";
import type { AuthBearerBootstrapResult, AuthSessionState, AuthWebSocketTokenResult } from "./auth.ts";
import type { AdvertisedEndpoint } from "./remoteAccess.ts";
import { EditorId } from "./editor.ts";
import { ServerSettings, type ClientSettings, type ServerSettingsPatch } from "./settings.ts";
import type { ExecutionEnvironmentDescriptor } from "./environment.ts";
import { ClientSettings, ServerSettings, ServerSettingsPatch } from "./settings.ts";
export interface ContextMenuItem<T extends string = string> {
id: T;
@@ -126,6 +128,33 @@ export interface DesktopEnvironmentBootstrap {
bootstrapToken?: string;
}
export interface DesktopSshEnvironmentTarget {
alias: string;
hostname: string;
username: string | null;
port: number | null;
}
export type DesktopSshHostSource = "ssh-config" | "known-hosts";
export interface DesktopDiscoveredSshHost extends DesktopSshEnvironmentTarget {
source: DesktopSshHostSource;
}
export interface DesktopSshEnvironmentBootstrap {
target: DesktopSshEnvironmentTarget;
httpBaseUrl: string;
wsBaseUrl: string;
pairingToken: string | null;
}
export interface DesktopSshPasswordPromptRequest {
requestId: string;
destination: string;
username: string | null;
prompt: string;
}
export interface PersistedSavedEnvironmentRecord {
environmentId: EnvironmentId;
label: string;
@@ -133,6 +162,7 @@ export interface PersistedSavedEnvironmentRecord {
httpBaseUrl: string;
createdAt: string;
lastConnectedAt: string | null;
desktopSsh?: DesktopSshEnvironmentTarget;
}
export type DesktopServerExposureMode = "local-only" | "network-accessible";
@@ -159,6 +189,23 @@ export interface DesktopBridge {
getSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise<string | null>;
setSavedEnvironmentSecret: (environmentId: EnvironmentId, secret: string) => Promise<boolean>;
removeSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise<void>;
discoverSshHosts: () => Promise<readonly DesktopDiscoveredSshHost[]>;
ensureSshEnvironment: (
target: DesktopSshEnvironmentTarget,
options?: { issuePairingToken?: boolean },
) => Promise<DesktopSshEnvironmentBootstrap>;
fetchSshEnvironmentDescriptor: (httpBaseUrl: string) => Promise<ExecutionEnvironmentDescriptor>;
bootstrapSshBearerSession: (
httpBaseUrl: string,
credential: string,
) => Promise<AuthBearerBootstrapResult>;
fetchSshSessionState: (httpBaseUrl: string, bearerToken: string) => Promise<AuthSessionState>;
issueSshWebSocketToken: (
httpBaseUrl: string,
bearerToken: string,
) => Promise<AuthWebSocketTokenResult>;
onSshPasswordPrompt: (listener: (request: DesktopSshPasswordPromptRequest) => void) => () => void;
resolveSshPasswordPrompt: (requestId: string, password: string | null) => Promise<void>;
getServerExposureState: () => Promise<DesktopServerExposureState>;
setServerExposureMode: (mode: DesktopServerExposureMode) => Promise<DesktopServerExposureState>;
getAdvertisedEndpoints: () => Promise<readonly AdvertisedEndpoint[]>;