Harden remote SSH environment recovery
- Validate SSH targets and known-host parsing more strictly - Retry desktop SSH session refresh on auth failures - Preserve saved registry state when bearer persistence fails
This commit is contained in:
1 parent
399264836a
commit
2ab77a2255
7 files changed
+359
-59
No files matched your search
@@ -511,9 +511,15 @@ function getSafeDesktopSshTarget(rawTarget: unknown): DesktopSshEnvironmentTarge
|
||||
return null;
|
||||
}
|
||||
|
||||
const alias = target.alias.trim();
|
||||
const hostname = target.hostname.trim();
|
||||
if (alias.length === 0 || hostname.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
alias: target.alias.trim(),
|
||||
hostname: target.hostname.trim(),
|
||||
alias,
|
||||
hostname,
|
||||
username: target.username?.trim() || null,
|
||||
port: target.port ?? null,
|
||||
};
|
||||
@@ -602,12 +608,11 @@ async function fetchLoopbackSshJson<T>(input: {
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
await readRemoteFetchErrorMessage(
|
||||
response,
|
||||
`SSH forwarded request failed (${response.status}).`,
|
||||
),
|
||||
const message = await readRemoteFetchErrorMessage(
|
||||
response,
|
||||
`SSH forwarded request failed (${response.status}).`,
|
||||
);
|
||||
throw new Error(`[ssh_http:${response.status}] ${message}`);
|
||||
}
|
||||
|
||||
return (await response.json()) as T;
|
||||
|
||||
@@ -93,10 +93,19 @@ describe("sshEnvironment", () => {
|
||||
"|1|hashed|entry ssh-ed25519 CCCC",
|
||||
"@cert-authority *.example.com ssh-ed25519 DDDD",
|
||||
"[ssh.example.com]:2200 ssh-ed25519 EEEE",
|
||||
"::1 ssh-ed25519 FFFF",
|
||||
"2001:db8::1 ssh-ed25519 GGGG",
|
||||
"",
|
||||
].join("\n"),
|
||||
),
|
||||
).toEqual(["github.com", "gitlab-alias", "gitlab.com", "ssh.example.com"]);
|
||||
).toEqual([
|
||||
"::1",
|
||||
"2001:db8::1",
|
||||
"github.com",
|
||||
"gitlab-alias",
|
||||
"gitlab.com",
|
||||
"ssh.example.com",
|
||||
]);
|
||||
});
|
||||
|
||||
it("parses resolved ssh config output into a target", () => {
|
||||
@@ -177,12 +186,23 @@ describe("sshEnvironment", () => {
|
||||
port: 2222,
|
||||
} as const;
|
||||
|
||||
expect(__test.buildRemoteLaunchScript()).toContain(
|
||||
'[ -n "$REMOTE_PID" ] && [ -n "$REMOTE_PORT" ] && kill -0 "$REMOTE_PID" 2>/dev/null',
|
||||
);
|
||||
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("reads the last non-empty ssh output line", () => {
|
||||
expect(
|
||||
__test.getLastNonEmptyOutputLine(
|
||||
["Welcome to the host", "", '{"credential":"pairing-token"}', ""].join("\n"),
|
||||
),
|
||||
).toBe('{"credential":"pairing-token"}');
|
||||
});
|
||||
|
||||
it("detects ssh auth failures from common permission denied messages", () => {
|
||||
expect(
|
||||
__test.isSshAuthFailure(
|
||||
|
||||
@@ -180,8 +180,10 @@ function parseKnownHostsHostnames(raw: string): ReadonlyArray<string> {
|
||||
}
|
||||
|
||||
for (const rawHost of hostField.split(",")) {
|
||||
const host =
|
||||
/^\[([^\]]+)\]:(\d+)$/u.exec(rawHost)?.[1] ?? rawHost.replace(/:.*$/u, "").trim();
|
||||
const bracketMatch = /^\[([^\]]+)\]:(\d+)$/u.exec(rawHost);
|
||||
const host = (
|
||||
bracketMatch?.[1] ?? (rawHost.includes(":") ? rawHost : rawHost.replace(/:.*$/u, ""))
|
||||
).trim();
|
||||
if (host.length === 0 || hasSshPattern(host)) {
|
||||
continue;
|
||||
}
|
||||
@@ -640,7 +642,7 @@ NODE
|
||||
}
|
||||
REMOTE_PID="$(cat "$PID_FILE" 2>/dev/null || true)"
|
||||
REMOTE_PORT="$(cat "$PORT_FILE" 2>/dev/null || true)"
|
||||
if [ -n "$REMOTE_PID" ] && kill -0 "$REMOTE_PID" 2>/dev/null; then
|
||||
if [ -n "$REMOTE_PID" ] && [ -n "$REMOTE_PORT" ] && kill -0 "$REMOTE_PID" 2>/dev/null; then
|
||||
:
|
||||
else
|
||||
REMOTE_PORT="$(pick_port)"
|
||||
@@ -653,6 +655,16 @@ printf '{"remotePort":%s}\\n' "$REMOTE_PORT"
|
||||
`.trimStart();
|
||||
}
|
||||
|
||||
function getLastNonEmptyOutputLine(stdout: string): string | null {
|
||||
return (
|
||||
stdout
|
||||
.trim()
|
||||
.split(/\r?\n/u)
|
||||
.map((entry) => entry.trim())
|
||||
.findLast((entry) => entry.length > 0) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
function buildRemoteT3RunnerScript(): string {
|
||||
return [
|
||||
"#!/bin/sh",
|
||||
@@ -698,11 +710,7 @@ async function launchOrReuseRemoteServer(
|
||||
...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }),
|
||||
...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
|
||||
});
|
||||
const line = result.stdout
|
||||
.trim()
|
||||
.split(/\r?\n/u)
|
||||
.map((entry) => entry.trim())
|
||||
.findLast((entry) => entry.length > 0);
|
||||
const line = getLastNonEmptyOutputLine(result.stdout);
|
||||
if (!line) {
|
||||
throw new Error("SSH launch did not return a remote port.");
|
||||
}
|
||||
@@ -725,7 +733,12 @@ async function issueRemotePairingToken(
|
||||
...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }),
|
||||
...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
|
||||
});
|
||||
const parsed = JSON.parse(result.stdout) as { credential?: unknown };
|
||||
const line = getLastNonEmptyOutputLine(result.stdout);
|
||||
if (!line) {
|
||||
throw new Error("SSH pairing did not return a credential.");
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(line) as { credential?: unknown };
|
||||
if (typeof parsed.credential !== "string" || parsed.credential.trim().length === 0) {
|
||||
throw new Error("SSH pairing command returned an invalid credential.");
|
||||
}
|
||||
@@ -1006,6 +1019,7 @@ export const __test = {
|
||||
buildRemoteT3RunnerScript,
|
||||
buildSshAskpassHelperDescriptor,
|
||||
buildSshChildEnvironment,
|
||||
getLastNonEmptyOutputLine,
|
||||
isSshAuthFailure,
|
||||
collectSshConfigAliasesFromFile,
|
||||
parseKnownHostsHostnames,
|
||||
|
||||
@@ -114,7 +114,7 @@ const authAccessHarness = vi.hoisted(() => {
|
||||
};
|
||||
});
|
||||
|
||||
const mockConnectDesktopSshEnvironment = vi.fn();
|
||||
const mockConnectDesktopSshEnvironment = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("../../environments/runtime", () => {
|
||||
const primaryConnection = {
|
||||
|
||||
@@ -35,7 +35,7 @@ interface SavedEnvironmentRegistryStore extends SavedEnvironmentRegistryState {
|
||||
let savedEnvironmentRegistryHydrated = false;
|
||||
let savedEnvironmentRegistryHydrationPromise: Promise<void> | null = null;
|
||||
|
||||
function toPersistedSavedEnvironmentRecord(
|
||||
export function toPersistedSavedEnvironmentRecord(
|
||||
record: SavedEnvironmentRecord,
|
||||
): PersistedSavedEnvironmentRecord {
|
||||
return {
|
||||
|
||||
@@ -1,18 +1,51 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
let mockSavedRecords: Array<Record<string, unknown>> = [];
|
||||
|
||||
const mockResolveRemotePairingTarget = vi.fn();
|
||||
const mockFetchRemoteEnvironmentDescriptor = vi.fn();
|
||||
const mockBootstrapRemoteBearerSession = vi.fn();
|
||||
const mockBootstrapSshBearerSession = vi.fn();
|
||||
const mockFetchSshSessionState = vi.fn();
|
||||
const mockPersistSavedEnvironmentRecord = vi.fn();
|
||||
const mockWriteSavedEnvironmentBearerToken = vi.fn();
|
||||
const mockSetSavedEnvironmentRegistry = vi.fn();
|
||||
const mockUpsert = vi.fn();
|
||||
const mockListSavedEnvironmentRecords = vi.fn();
|
||||
const mockGetSavedEnvironmentRecord = vi.fn((environmentId: EnvironmentId) => {
|
||||
return mockSavedRecords.find((record) => record.environmentId === environmentId) ?? null;
|
||||
});
|
||||
const mockReadSavedEnvironmentBearerToken = vi.fn();
|
||||
const mockRemoveSavedEnvironmentBearerToken = vi.fn();
|
||||
const mockPatchRuntime = vi.fn();
|
||||
const mockClearRuntime = vi.fn();
|
||||
const mockRegistrySetState = vi.fn((next: { byId: Record<string, Record<string, unknown>> }) => {
|
||||
mockSavedRecords = Object.values(next.byId);
|
||||
});
|
||||
const mockRemove = vi.fn((environmentId: EnvironmentId) => {
|
||||
mockSavedRecords = mockSavedRecords.filter((record) => record.environmentId !== environmentId);
|
||||
});
|
||||
const mockMarkConnected = vi.fn((environmentId: EnvironmentId, connectedAt: string) => {
|
||||
mockSavedRecords = mockSavedRecords.map((record) =>
|
||||
record.environmentId === environmentId ? { ...record, lastConnectedAt: connectedAt } : record,
|
||||
);
|
||||
});
|
||||
const mockUpsert = vi.fn((record: Record<string, unknown>) => {
|
||||
mockSavedRecords = [
|
||||
...mockSavedRecords.filter((entry) => entry.environmentId !== record.environmentId),
|
||||
record,
|
||||
];
|
||||
});
|
||||
const mockListSavedEnvironmentRecords = vi.fn(() => mockSavedRecords);
|
||||
const mockEnsureSshEnvironment = vi.fn();
|
||||
const mockFetchSshEnvironmentDescriptor = vi.fn();
|
||||
const mockToPersistedSavedEnvironmentRecord = vi.fn((record) => record);
|
||||
const mockCreateEnvironmentConnection = vi.fn();
|
||||
const mockClientGetConfig = vi.fn(async () => ({
|
||||
environment: {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
label: "Remote environment",
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../remote/target", () => ({
|
||||
resolveRemotePairingTarget: mockResolveRemotePairingTarget,
|
||||
@@ -35,24 +68,27 @@ vi.mock("~/localApi", () => ({
|
||||
}));
|
||||
|
||||
vi.mock("./catalog", () => ({
|
||||
getSavedEnvironmentRecord: vi.fn(),
|
||||
getSavedEnvironmentRecord: mockGetSavedEnvironmentRecord,
|
||||
hasSavedEnvironmentRegistryHydrated: vi.fn(),
|
||||
listSavedEnvironmentRecords: mockListSavedEnvironmentRecords,
|
||||
persistSavedEnvironmentRecord: mockPersistSavedEnvironmentRecord,
|
||||
readSavedEnvironmentBearerToken: vi.fn(),
|
||||
removeSavedEnvironmentBearerToken: vi.fn(),
|
||||
readSavedEnvironmentBearerToken: mockReadSavedEnvironmentBearerToken,
|
||||
removeSavedEnvironmentBearerToken: mockRemoveSavedEnvironmentBearerToken,
|
||||
toPersistedSavedEnvironmentRecord: mockToPersistedSavedEnvironmentRecord,
|
||||
useSavedEnvironmentRegistryStore: {
|
||||
getState: () => ({
|
||||
upsert: mockUpsert,
|
||||
remove: vi.fn(),
|
||||
markConnected: vi.fn(),
|
||||
remove: mockRemove,
|
||||
markConnected: mockMarkConnected,
|
||||
}),
|
||||
setState: mockRegistrySetState,
|
||||
subscribe: vi.fn(() => () => {}),
|
||||
},
|
||||
useSavedEnvironmentRuntimeStore: {
|
||||
getState: () => ({
|
||||
ensure: vi.fn(),
|
||||
patch: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
patch: mockPatchRuntime,
|
||||
clear: mockClearRuntime,
|
||||
}),
|
||||
},
|
||||
waitForSavedEnvironmentRegistryHydration: vi.fn(),
|
||||
@@ -63,16 +99,32 @@ vi.mock("./connection", () => ({
|
||||
createEnvironmentConnection: mockCreateEnvironmentConnection,
|
||||
}));
|
||||
|
||||
vi.mock("../../rpc/wsRpcClient", () => ({
|
||||
createWsRpcClient: vi.fn(() => ({
|
||||
server: {
|
||||
getConfig: mockClientGetConfig,
|
||||
},
|
||||
orchestration: {
|
||||
subscribeThread: vi.fn(() => () => {}),
|
||||
},
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("../../rpc/wsTransport", () => ({
|
||||
WsTransport: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("addSavedEnvironment", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
vi.clearAllMocks();
|
||||
mockSavedRecords = [];
|
||||
vi.stubGlobal("window", {
|
||||
desktopBridge: {
|
||||
ensureSshEnvironment: mockEnsureSshEnvironment,
|
||||
fetchSshEnvironmentDescriptor: mockFetchSshEnvironmentDescriptor,
|
||||
bootstrapSshBearerSession: mockBootstrapSshBearerSession,
|
||||
fetchSshSessionState: vi.fn(),
|
||||
fetchSshSessionState: mockFetchSshSessionState,
|
||||
issueSshWebSocketToken: vi.fn(),
|
||||
},
|
||||
});
|
||||
@@ -110,7 +162,12 @@ describe("addSavedEnvironment", () => {
|
||||
mockPersistSavedEnvironmentRecord.mockResolvedValue(undefined);
|
||||
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(false);
|
||||
mockSetSavedEnvironmentRegistry.mockResolvedValue(undefined);
|
||||
mockListSavedEnvironmentRecords.mockReturnValue([]);
|
||||
mockReadSavedEnvironmentBearerToken.mockResolvedValue(null);
|
||||
mockRemoveSavedEnvironmentBearerToken.mockResolvedValue(undefined);
|
||||
mockFetchSshSessionState.mockResolvedValue({
|
||||
authenticated: true,
|
||||
role: "owner",
|
||||
});
|
||||
mockCreateEnvironmentConnection.mockImplementation(
|
||||
(input: { knownEnvironment: { environmentId: EnvironmentId }; client: unknown }) => ({
|
||||
kind: "saved",
|
||||
@@ -122,6 +179,12 @@ describe("addSavedEnvironment", () => {
|
||||
dispose: async () => undefined,
|
||||
}),
|
||||
);
|
||||
mockClientGetConfig.mockResolvedValue({
|
||||
environment: {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
label: "Remote environment",
|
||||
},
|
||||
});
|
||||
mockEnsureSshEnvironment.mockResolvedValue({
|
||||
target: {
|
||||
alias: "devbox",
|
||||
@@ -157,6 +220,165 @@ describe("addSavedEnvironment", () => {
|
||||
await resetEnvironmentServiceForTests();
|
||||
});
|
||||
|
||||
it("removes an older ssh record when the same target returns a new environment id", async () => {
|
||||
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
|
||||
mockFetchSshEnvironmentDescriptor.mockResolvedValue({
|
||||
environmentId: EnvironmentId.make("environment-2"),
|
||||
label: "Remote environment",
|
||||
});
|
||||
mockSavedRecords = [
|
||||
{
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
label: "Old ssh environment",
|
||||
httpBaseUrl: "http://127.0.0.1:3774/",
|
||||
wsBaseUrl: "ws://127.0.0.1:3774/",
|
||||
createdAt: "2026-04-14T00:00:00.000Z",
|
||||
lastConnectedAt: null,
|
||||
desktopSsh: {
|
||||
alias: "devbox",
|
||||
hostname: "devbox.example.com",
|
||||
username: "julius",
|
||||
port: 22,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const { addSavedEnvironment, resetEnvironmentServiceForTests } = await import("./service");
|
||||
|
||||
await expect(
|
||||
addSavedEnvironment({
|
||||
label: "Remote environment",
|
||||
host: "http://127.0.0.1:3774/",
|
||||
pairingCode: "ssh-pairing-code",
|
||||
desktopSsh: {
|
||||
alias: "devbox",
|
||||
hostname: "devbox.example.com",
|
||||
username: "julius",
|
||||
port: 22,
|
||||
},
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
environmentId: EnvironmentId.make("environment-2"),
|
||||
});
|
||||
|
||||
expect(mockUpsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
environmentId: EnvironmentId.make("environment-2"),
|
||||
}),
|
||||
);
|
||||
expect(mockRemove).toHaveBeenCalledWith(EnvironmentId.make("environment-1"));
|
||||
expect(mockRemoveSavedEnvironmentBearerToken).toHaveBeenCalledWith(
|
||||
EnvironmentId.make("environment-1"),
|
||||
);
|
||||
|
||||
await resetEnvironmentServiceForTests();
|
||||
});
|
||||
|
||||
it("retries desktop ssh session refresh when the forwarded endpoint returns ssh_http 401", async () => {
|
||||
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
|
||||
mockBootstrapSshBearerSession
|
||||
.mockResolvedValueOnce({
|
||||
sessionToken: "ssh-bearer-token",
|
||||
role: "owner",
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
sessionToken: "ssh-bearer-token-2",
|
||||
role: "owner",
|
||||
});
|
||||
mockFetchSshSessionState
|
||||
.mockRejectedValueOnce(new Error("[ssh_http:401] Unauthorized"))
|
||||
.mockResolvedValueOnce({
|
||||
authenticated: true,
|
||||
role: "owner",
|
||||
});
|
||||
|
||||
const { connectDesktopSshEnvironment, resetEnvironmentServiceForTests } =
|
||||
await import("./service");
|
||||
|
||||
await expect(
|
||||
connectDesktopSshEnvironment({
|
||||
alias: "devbox",
|
||||
hostname: "devbox",
|
||||
username: null,
|
||||
port: null,
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
});
|
||||
|
||||
expect(mockEnsureSshEnvironment).toHaveBeenCalled();
|
||||
expect(mockBootstrapSshBearerSession).toHaveBeenCalledTimes(2);
|
||||
expect(mockFetchSshSessionState).toHaveBeenCalledTimes(2);
|
||||
|
||||
await resetEnvironmentServiceForTests();
|
||||
});
|
||||
|
||||
it("marks desktop ssh reconnect failures as runtime errors when bearer recovery fails", async () => {
|
||||
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
|
||||
|
||||
const connection = {
|
||||
kind: "saved" as const,
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
knownEnvironment: {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
},
|
||||
client: {},
|
||||
ensureBootstrapped: async () => undefined,
|
||||
reconnect: vi.fn(async () => {
|
||||
throw new Error("socket closed");
|
||||
}),
|
||||
dispose: async () => undefined,
|
||||
};
|
||||
mockCreateEnvironmentConnection.mockReturnValue(connection);
|
||||
|
||||
const { addSavedEnvironment, reconnectSavedEnvironment, resetEnvironmentServiceForTests } =
|
||||
await import("./service");
|
||||
|
||||
await addSavedEnvironment({
|
||||
label: "Remote environment",
|
||||
host: "http://127.0.0.1:3774/",
|
||||
pairingCode: "ssh-pairing-code",
|
||||
desktopSsh: {
|
||||
alias: "devbox",
|
||||
hostname: "devbox.example.com",
|
||||
username: "julius",
|
||||
port: 22,
|
||||
},
|
||||
});
|
||||
|
||||
mockSavedRecords = [
|
||||
{
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
label: "Remote environment",
|
||||
httpBaseUrl: "http://127.0.0.1:3774/",
|
||||
wsBaseUrl: "ws://127.0.0.1:3774/",
|
||||
createdAt: "2026-04-14T00:00:00.000Z",
|
||||
lastConnectedAt: null,
|
||||
desktopSsh: {
|
||||
alias: "devbox",
|
||||
hostname: "devbox.example.com",
|
||||
username: "julius",
|
||||
port: 22,
|
||||
},
|
||||
},
|
||||
];
|
||||
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(false);
|
||||
|
||||
await expect(reconnectSavedEnvironment(EnvironmentId.make("environment-1"))).rejects.toThrow(
|
||||
"Unable to persist saved environment credentials.",
|
||||
);
|
||||
|
||||
expect(mockPatchRuntime).toHaveBeenCalledWith(
|
||||
EnvironmentId.make("environment-1"),
|
||||
expect.objectContaining({
|
||||
connectionState: "error",
|
||||
lastError: "Unable to persist saved environment credentials.",
|
||||
}),
|
||||
);
|
||||
|
||||
await resetEnvironmentServiceForTests();
|
||||
});
|
||||
|
||||
it("bootstraps a desktop ssh environment through the desktop bridge", async () => {
|
||||
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
|
||||
|
||||
@@ -170,7 +392,9 @@ describe("addSavedEnvironment", () => {
|
||||
username: null,
|
||||
port: null,
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
).resolves.toMatchObject({
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
});
|
||||
|
||||
expect(mockEnsureSshEnvironment).toHaveBeenCalledWith(
|
||||
{
|
||||
|
||||
@@ -47,6 +47,7 @@ import {
|
||||
readSavedEnvironmentBearerToken,
|
||||
removeSavedEnvironmentBearerToken,
|
||||
type SavedEnvironmentRecord,
|
||||
toPersistedSavedEnvironmentRecord,
|
||||
useSavedEnvironmentRegistryStore,
|
||||
useSavedEnvironmentRuntimeStore,
|
||||
waitForSavedEnvironmentRegistryHydration,
|
||||
@@ -112,6 +113,7 @@ let needsProviderInvalidation = false;
|
||||
const THREAD_DETAIL_SUBSCRIPTION_IDLE_EVICTION_MS = 15 * 60 * 1000;
|
||||
const MAX_CACHED_THREAD_DETAIL_SUBSCRIPTIONS = 32;
|
||||
const NOOP = () => undefined;
|
||||
const SSH_HTTP_STATUS_RE = /^\[ssh_http:(\d+)\]\s/u;
|
||||
|
||||
function compareAppliedProjectionVersion(
|
||||
left: { readonly sequence: number; readonly updatedAt: string | null },
|
||||
@@ -495,16 +497,22 @@ 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 readSshHttpErrorStatus(error: unknown): number | null {
|
||||
if (!(error instanceof Error)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const match = SSH_HTTP_STATUS_RE.exec(error.message);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsed = Number.parseInt(match[1] ?? "", 10);
|
||||
return Number.isInteger(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
function isSshHttpAuthError(error: unknown, status: number): boolean {
|
||||
return readSshHttpErrorStatus(error) === status;
|
||||
}
|
||||
|
||||
function isDesktopSshTargetEqual(
|
||||
@@ -537,10 +545,28 @@ function findSavedEnvironmentRecordByDesktopSshTarget(
|
||||
);
|
||||
}
|
||||
|
||||
async function persistSavedEnvironmentRegistryRollback(): Promise<void> {
|
||||
function buildSavedEnvironmentRegistryById(
|
||||
records: ReadonlyArray<SavedEnvironmentRecord>,
|
||||
): Record<EnvironmentId, SavedEnvironmentRecord> {
|
||||
return Object.fromEntries(records.map((record) => [record.environmentId, record])) as Record<
|
||||
EnvironmentId,
|
||||
SavedEnvironmentRecord
|
||||
>;
|
||||
}
|
||||
|
||||
function snapshotSavedEnvironmentRegistry(): ReadonlyArray<SavedEnvironmentRecord> {
|
||||
return listSavedEnvironmentRecords();
|
||||
}
|
||||
|
||||
async function persistSavedEnvironmentRegistryRollback(
|
||||
records: ReadonlyArray<SavedEnvironmentRecord>,
|
||||
): Promise<void> {
|
||||
await ensureLocalApi().persistence.setSavedEnvironmentRegistry(
|
||||
listSavedEnvironmentRecords().map((entry) => serializeSavedEnvironmentRecord(entry)),
|
||||
records.map((entry) => toPersistedSavedEnvironmentRecord(entry)),
|
||||
);
|
||||
useSavedEnvironmentRegistryStore.setState({
|
||||
byId: buildSavedEnvironmentRegistryById(records),
|
||||
});
|
||||
}
|
||||
|
||||
async function resolveDesktopSshEnvironmentBootstrap(
|
||||
@@ -625,6 +651,7 @@ async function issueDesktopSshBearerSession(record: SavedEnvironmentRecord): Pro
|
||||
readonly bearerToken: string;
|
||||
readonly role: AuthSessionRole | null;
|
||||
}> {
|
||||
const registrySnapshot = snapshotSavedEnvironmentRegistry();
|
||||
const prepared = await prepareSavedEnvironmentRecordForConnection(record, {
|
||||
issuePairingToken: true,
|
||||
});
|
||||
@@ -641,7 +668,7 @@ async function issueDesktopSshBearerSession(record: SavedEnvironmentRecord): Pro
|
||||
bearerSession.sessionToken,
|
||||
);
|
||||
if (!didPersistBearerToken) {
|
||||
await persistSavedEnvironmentRegistryRollback();
|
||||
await persistSavedEnvironmentRegistryRollback(registrySnapshot);
|
||||
throw new Error("Unable to persist saved environment credentials.");
|
||||
}
|
||||
|
||||
@@ -1186,11 +1213,10 @@ async function ensureSavedEnvironmentConnection(
|
||||
options?.serverConfig ?? null,
|
||||
);
|
||||
} catch (error) {
|
||||
if (
|
||||
!record.desktopSsh ||
|
||||
!isRemoteEnvironmentAuthHttpError(error) ||
|
||||
error.status !== 401
|
||||
) {
|
||||
const isAuthError = activeRecord.desktopSsh
|
||||
? isSshHttpAuthError(error, 401)
|
||||
: isRemoteEnvironmentAuthHttpError(error) && error.status === 401;
|
||||
if (!isAuthError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
@@ -1303,15 +1329,20 @@ export async function reconnectSavedEnvironment(environmentId: EnvironmentId): P
|
||||
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;
|
||||
try {
|
||||
const issued = await issueDesktopSshBearerSession(
|
||||
getSavedEnvironmentRecord(environmentId) ?? record,
|
||||
);
|
||||
await removeConnection(environmentId).catch(() => false);
|
||||
await ensureSavedEnvironmentConnection(issued.record, {
|
||||
bearerToken: issued.bearerToken,
|
||||
role: issued.role,
|
||||
});
|
||||
return;
|
||||
} catch (recoveryError) {
|
||||
setRuntimeError(environmentId, recoveryError);
|
||||
throw recoveryError;
|
||||
}
|
||||
}
|
||||
setRuntimeError(environmentId, error);
|
||||
throw error;
|
||||
@@ -1342,9 +1373,12 @@ export async function addSavedEnvironment(input: {
|
||||
httpBaseUrl: resolvedTarget.httpBaseUrl,
|
||||
});
|
||||
const environmentId = descriptor.environmentId;
|
||||
const registrySnapshot = snapshotSavedEnvironmentRegistry();
|
||||
const existingRecord =
|
||||
getSavedEnvironmentRecord(environmentId) ??
|
||||
findSavedEnvironmentRecordByDesktopSshTarget(input.desktopSsh);
|
||||
const staleDesktopSshRecord =
|
||||
existingRecord && existingRecord.environmentId !== environmentId ? existingRecord : null;
|
||||
|
||||
const bearerSession = input.desktopSsh
|
||||
? await bootstrapDesktopSshBearerSession(resolvedTarget.httpBaseUrl, resolvedTarget.credential)
|
||||
@@ -1371,10 +1405,13 @@ export async function addSavedEnvironment(input: {
|
||||
bearerSession.sessionToken,
|
||||
);
|
||||
if (!didPersistBearerToken) {
|
||||
await persistSavedEnvironmentRegistryRollback();
|
||||
await persistSavedEnvironmentRegistryRollback(registrySnapshot);
|
||||
throw new Error("Unable to persist saved environment credentials.");
|
||||
}
|
||||
useSavedEnvironmentRegistryStore.getState().upsert(record);
|
||||
if (staleDesktopSshRecord) {
|
||||
await removeSavedEnvironment(staleDesktopSshRecord.environmentId);
|
||||
}
|
||||
await removeConnection(environmentId).catch(() => false);
|
||||
await ensureSavedEnvironmentConnection(record, {
|
||||
bearerToken: bearerSession.sessionToken,
|
||||
|
||||
Reference in new issue
Block a user