mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-27 10:45:29 +00:00
Revert "Route remote workspace browser tabs through the workspace daemon (#10944)"
This reverts commit 63eb8c0dec.
This commit is contained in:
@@ -24,7 +24,6 @@ export interface AssistantFileLinkResolverConfig {
|
||||
workspaceRoot?: string;
|
||||
relativePathBase?: string;
|
||||
onOpenWorkspaceFile?: (target: InlinePathTarget, disposition: OpenFileDisposition) => void;
|
||||
onOpenBrowserUrl?: (url: string) => void;
|
||||
toast?: ToastApi | null;
|
||||
}
|
||||
|
||||
@@ -58,7 +57,6 @@ export function AssistantFileLinkResolverProvider({
|
||||
workspaceRoot,
|
||||
relativePathBase,
|
||||
onOpenWorkspaceFile,
|
||||
onOpenBrowserUrl,
|
||||
toast,
|
||||
children,
|
||||
}: AssistantFileLinkResolverProviderProps) {
|
||||
@@ -68,7 +66,6 @@ export function AssistantFileLinkResolverProvider({
|
||||
workspaceRoot,
|
||||
relativePathBase,
|
||||
onOpenWorkspaceFile,
|
||||
onOpenBrowserUrl,
|
||||
toast,
|
||||
});
|
||||
configRef.current = {
|
||||
@@ -77,7 +74,6 @@ export function AssistantFileLinkResolverProvider({
|
||||
workspaceRoot,
|
||||
relativePathBase,
|
||||
onOpenWorkspaceFile,
|
||||
onOpenBrowserUrl,
|
||||
toast,
|
||||
};
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
import type { OpenFileDisposition } from "@/workspace/file-open";
|
||||
import { shouldRouteWorkspaceUrlToProxiedBrowser } from "@/desktop/browser/proxy";
|
||||
import { openExternalUrl } from "@/utils/open-external-url";
|
||||
import { formatFileLinkTooltipPath } from "./tooltip-path";
|
||||
import type { InlinePathTarget } from "./parse";
|
||||
@@ -336,14 +335,6 @@ async function dispatchExternalUrl(input: {
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
current.onOpenBrowserUrl &&
|
||||
current.serverId &&
|
||||
shouldRouteWorkspaceUrlToProxiedBrowser({ serverId: current.serverId, url: input.url })
|
||||
) {
|
||||
current.onOpenBrowserUrl(input.url);
|
||||
return;
|
||||
}
|
||||
await openExternalUrl(input.url);
|
||||
}
|
||||
|
||||
|
||||
@@ -71,7 +71,6 @@ export interface TerminalEmulatorProps {
|
||||
target: TerminalLocalFileLinkTarget,
|
||||
disposition: "main" | "side",
|
||||
) => Promise<void> | void;
|
||||
onOpenExternalUrl?: (url: string) => Promise<void> | void;
|
||||
onRendererReadyChange?: (change: TerminalRendererReadyChange) => void;
|
||||
pendingModifiers?: PendingTerminalModifiers;
|
||||
focusRequestToken?: number;
|
||||
|
||||
@@ -142,7 +142,6 @@ interface TerminalEmulatorProps {
|
||||
target: TerminalLocalFileLinkTarget,
|
||||
disposition: "main" | "side",
|
||||
) => Promise<void> | void;
|
||||
onOpenExternalUrl?: (url: string) => Promise<void> | void;
|
||||
onRendererReadyChange?: (change: TerminalRendererReadyChange) => void;
|
||||
onFilePaste?: (file: Promise<TerminalFile | null>) => void;
|
||||
pendingModifiers?: PendingTerminalModifiers;
|
||||
@@ -180,7 +179,6 @@ export default function TerminalEmulator({
|
||||
onInputModeChange,
|
||||
onResolveLocalFileLink,
|
||||
onOpenLocalFileLink,
|
||||
onOpenExternalUrl,
|
||||
onRendererReadyChange,
|
||||
onFilePaste,
|
||||
pendingModifiers = { ctrl: false, shift: false, alt: false },
|
||||
@@ -214,7 +212,6 @@ export default function TerminalEmulator({
|
||||
onInputModeChange,
|
||||
onResolveLocalFileLink,
|
||||
onOpenLocalFileLink,
|
||||
onOpenExternalUrl: onOpenExternalUrl ?? openExternalUrl,
|
||||
onFilePaste,
|
||||
});
|
||||
mountCallbacksRef.current = {
|
||||
@@ -227,7 +224,6 @@ export default function TerminalEmulator({
|
||||
onInputModeChange,
|
||||
onResolveLocalFileLink,
|
||||
onOpenLocalFileLink,
|
||||
onOpenExternalUrl: onOpenExternalUrl ?? openExternalUrl,
|
||||
onFilePaste,
|
||||
};
|
||||
const pendingModifiersRef = useRef(pendingModifiers);
|
||||
@@ -463,6 +459,7 @@ export default function TerminalEmulator({
|
||||
runtime.setCallbacks({
|
||||
callbacks: {
|
||||
...mountCallbacksRef.current,
|
||||
onOpenExternalUrl: openExternalUrl,
|
||||
},
|
||||
});
|
||||
runtime.setPendingModifiers({ pendingModifiers: pendingModifiersRef.current });
|
||||
@@ -499,7 +496,7 @@ export default function TerminalEmulator({
|
||||
onResolveLocalFileLink,
|
||||
onOpenLocalFileLink,
|
||||
onFilePaste,
|
||||
onOpenExternalUrl: onOpenExternalUrl ?? openExternalUrl,
|
||||
onOpenExternalUrl: openExternalUrl,
|
||||
},
|
||||
});
|
||||
}, [
|
||||
@@ -508,7 +505,6 @@ export default function TerminalEmulator({
|
||||
onFindResult,
|
||||
onInput,
|
||||
onInputModeChange,
|
||||
onOpenExternalUrl,
|
||||
onOpenLocalFileLink,
|
||||
onPendingModifiersConsumed,
|
||||
onResolveLocalFileLink,
|
||||
|
||||
@@ -102,8 +102,6 @@ import {
|
||||
type OpenFileDisposition,
|
||||
type WorkspaceFileOpenRequest,
|
||||
} from "@/workspace/file-open";
|
||||
import { shouldRouteWorkspaceUrlToProxiedBrowser } from "@/desktop/browser/proxy";
|
||||
import { openExternalUrl } from "@/utils/open-external-url";
|
||||
|
||||
interface TerminalPaneProps {
|
||||
serverId: string;
|
||||
@@ -113,7 +111,6 @@ interface TerminalPaneProps {
|
||||
isPaneFocused: boolean;
|
||||
onOpenFileExplorer: () => void;
|
||||
onOpenWorkspaceFile: (request: WorkspaceFileOpenRequest) => void;
|
||||
onOpenBrowserUrl?: (url: string) => void;
|
||||
}
|
||||
|
||||
const TERMINAL_REFIT_DELAYS_MS = [0, 48, 144, 320];
|
||||
@@ -268,7 +265,6 @@ export function TerminalPane({
|
||||
isPaneFocused,
|
||||
onOpenFileExplorer,
|
||||
onOpenWorkspaceFile,
|
||||
onOpenBrowserUrl,
|
||||
}: TerminalPaneProps) {
|
||||
const { t } = useTranslation();
|
||||
const retainedPanelActive = useRetainedPanelActive();
|
||||
@@ -1166,17 +1162,6 @@ export function TerminalPane({
|
||||
terminalStreamKey,
|
||||
});
|
||||
|
||||
const handleOpenExternalUrl = useCallback(
|
||||
async (url: string) => {
|
||||
if (onOpenBrowserUrl && shouldRouteWorkspaceUrlToProxiedBrowser({ serverId, url })) {
|
||||
onOpenBrowserUrl(url);
|
||||
return;
|
||||
}
|
||||
await openExternalUrl(url);
|
||||
},
|
||||
[onOpenBrowserUrl, serverId],
|
||||
);
|
||||
|
||||
if (!client || !isConnected) {
|
||||
return (
|
||||
<View style={styles.centerState}>
|
||||
@@ -1218,7 +1203,6 @@ export function TerminalPane({
|
||||
onSelectionChange={handleSelectionChange}
|
||||
onResolveLocalFileLink={handleResolveLocalFileLink}
|
||||
onOpenLocalFileLink={handleOpenLocalFileLink}
|
||||
onOpenExternalUrl={handleOpenExternalUrl}
|
||||
onPendingModifiersConsumed={handlePendingModifiersConsumed}
|
||||
pendingModifiers={modifiers}
|
||||
focusRequestToken={focusRequestToken}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { beforeEach, describe, expect, test } from "vitest";
|
||||
import type { SessionInboundMessage, SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import { createJSONStorage, type StateStorage } from "zustand/middleware";
|
||||
import { mountBrowserAutomationHandler, type BrowserAutomationHandlerOptions } from "./handler";
|
||||
import { mountBrowserAutomationHandler } from "./handler";
|
||||
import type { DesktopHostBridge } from "@/desktop/host";
|
||||
import { useBrowserStore } from "@/desktop/browser/store";
|
||||
import { findPaneById } from "@/stores/workspace-layout-actions";
|
||||
@@ -107,14 +107,12 @@ class FakeResidentBrowser {
|
||||
browserId: string;
|
||||
workspaceId: string;
|
||||
url: string;
|
||||
partition?: string;
|
||||
}> = [];
|
||||
|
||||
public ensure = (input: {
|
||||
browserId: string;
|
||||
workspaceId: string;
|
||||
url: string;
|
||||
partition?: string;
|
||||
}): HTMLElement | null => {
|
||||
this.ensuredWebviews.push(input);
|
||||
return null;
|
||||
@@ -131,8 +129,6 @@ class BrowserAutomationHandlerHarness {
|
||||
input: {
|
||||
serverId?: string;
|
||||
host?: DesktopHostBridge | null;
|
||||
readHostBrowserRouting?: BrowserAutomationHandlerOptions["readHostBrowserRouting"];
|
||||
prepareHostBrowserPartition?: BrowserAutomationHandlerOptions["prepareHostBrowserPartition"];
|
||||
registrationWaitTimeoutMs?: number;
|
||||
registrationPollIntervalMs?: number;
|
||||
} = {},
|
||||
@@ -142,12 +138,6 @@ class BrowserAutomationHandlerHarness {
|
||||
...(input.serverId ? { serverId: input.serverId } : {}),
|
||||
getHost: () => (input.host === undefined ? { browser: this.browser } : input.host),
|
||||
ensureResidentBrowserWebview: this.resident.ensure,
|
||||
...(input.readHostBrowserRouting
|
||||
? { readHostBrowserRouting: input.readHostBrowserRouting }
|
||||
: {}),
|
||||
...(input.prepareHostBrowserPartition
|
||||
? { prepareHostBrowserPartition: input.prepareHostBrowserPartition }
|
||||
: {}),
|
||||
...(input.registrationWaitTimeoutMs !== undefined
|
||||
? { registrationWaitTimeoutMs: input.registrationWaitTimeoutMs }
|
||||
: {}),
|
||||
@@ -175,7 +165,7 @@ function browserAutomationRequest(): BrowserAutomationExecuteRequest {
|
||||
};
|
||||
}
|
||||
|
||||
function browserNewTabRequest(input?: { url?: string }): BrowserAutomationExecuteRequest {
|
||||
function browserNewTabRequest(): BrowserAutomationExecuteRequest {
|
||||
return {
|
||||
type: "browser.automation.execute.request",
|
||||
requestId: "req-new",
|
||||
@@ -183,7 +173,7 @@ function browserNewTabRequest(input?: { url?: string }): BrowserAutomationExecut
|
||||
workspaceId: "wks_workspace_a",
|
||||
command: {
|
||||
command: "new_tab",
|
||||
args: { url: input?.url ?? "https://example.com" },
|
||||
args: { url: "https://example.com" },
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -250,14 +240,11 @@ function currentBrowserTabs() {
|
||||
}));
|
||||
}
|
||||
|
||||
function newTabResultFrom(
|
||||
payload: BrowserAutomationResponsePayload,
|
||||
expectedUrl = "https://example.com",
|
||||
) {
|
||||
function newTabResultFrom(payload: BrowserAutomationResponsePayload) {
|
||||
expect(payload).toMatchObject({
|
||||
requestId: "req-new",
|
||||
ok: true,
|
||||
result: { command: "new_tab", workspaceId: "wks_workspace_a", url: expectedUrl },
|
||||
result: { command: "new_tab", workspaceId: "wks_workspace_a", url: "https://example.com" },
|
||||
});
|
||||
if (!payload.ok || payload.result.command !== "new_tab") {
|
||||
throw new Error("Expected browser_new_tab success payload");
|
||||
@@ -628,70 +615,4 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
expect(browser.browser.executedRequests).toEqual([]);
|
||||
expect(browser.client.sentResponses).toEqual([]);
|
||||
});
|
||||
|
||||
test("remote agent browser_new_tab prepares the host proxy partition and sets routingMode to host", async () => {
|
||||
const browser = new BrowserAutomationHandlerHarness();
|
||||
const preparedServers: string[] = [];
|
||||
browser.mount({
|
||||
serverId: "remote-1",
|
||||
readHostBrowserRouting: () => ({
|
||||
kind: "remote",
|
||||
support: "supported",
|
||||
target: { type: "directTcp", endpoint: "10.0.0.5:6767" },
|
||||
}),
|
||||
prepareHostBrowserPartition: async (serverId) => {
|
||||
preparedServers.push(serverId);
|
||||
return {
|
||||
ok: true,
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
isRemoteHost: true,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
browser.receive(browserNewTabRequest({ url: "http://localhost:5173" }));
|
||||
await flushAsyncWork();
|
||||
|
||||
const result = newTabResultFrom(browser.client.payloadAt(0), "http://localhost:5173");
|
||||
expect(preparedServers).toEqual(["remote-1"]);
|
||||
expect(useBrowserStore.getState().browsersById[result.browserId]?.routingMode).toBe("host");
|
||||
expect(browser.resident.ensuredWebviews).toEqual([
|
||||
{
|
||||
browserId: result.browserId,
|
||||
workspaceId: "wks_workspace_a",
|
||||
url: "http://localhost:5173",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("remote agent browser_new_tab fails closed without creating a webview when host proxy cannot prepare", async () => {
|
||||
const browser = new BrowserAutomationHandlerHarness();
|
||||
browser.mount({
|
||||
serverId: "remote-old",
|
||||
readHostBrowserRouting: () => ({
|
||||
kind: "remote",
|
||||
support: "daemon_update_required",
|
||||
}),
|
||||
prepareHostBrowserPartition: async () => ({
|
||||
ok: false,
|
||||
reason: "daemon_update_required",
|
||||
message: "Update this host daemon to browse through the host proxy.",
|
||||
}),
|
||||
});
|
||||
|
||||
browser.receive(browserNewTabRequest({ url: "http://localhost:5173" }));
|
||||
await flushAsyncWork();
|
||||
|
||||
expect(browser.resident.ensuredWebviews).toEqual([]);
|
||||
expect(browser.client.payloadAt(0)).toEqual({
|
||||
requestId: "req-new",
|
||||
ok: false,
|
||||
error: {
|
||||
code: "browser_unsupported",
|
||||
message: "Update this host daemon to browse through the host proxy.",
|
||||
retryable: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,11 +7,6 @@ import {
|
||||
removeResidentBrowserWebview,
|
||||
resizeResidentBrowserWebview,
|
||||
} from "@/desktop/browser/resident-webviews";
|
||||
import {
|
||||
installBrowserProxyRendererBridge,
|
||||
prepareHostBrowserPartition as prepareHostBrowserPartitionDefault,
|
||||
readHostBrowserRouting as readHostBrowserRoutingDefault,
|
||||
} from "@/desktop/browser/proxy";
|
||||
import {
|
||||
createFixedBrowserViewport,
|
||||
createWorkspaceBrowser,
|
||||
@@ -47,8 +42,6 @@ export interface BrowserAutomationHandlerOptions {
|
||||
serverId?: string;
|
||||
getHost?: () => DesktopHostBridge | null;
|
||||
ensureResidentBrowserWebview?: typeof ensureResidentBrowserWebviewDefault;
|
||||
readHostBrowserRouting?: typeof readHostBrowserRoutingDefault;
|
||||
prepareHostBrowserPartition?: typeof prepareHostBrowserPartitionDefault;
|
||||
registrationWaitTimeoutMs?: number;
|
||||
registrationPollIntervalMs?: number;
|
||||
}
|
||||
@@ -56,7 +49,6 @@ export interface BrowserAutomationHandlerOptions {
|
||||
export function mountBrowserAutomationHandler(
|
||||
options: BrowserAutomationHandlerOptions,
|
||||
): () => void {
|
||||
installBrowserProxyRendererBridge();
|
||||
const getHost = options.getHost ?? getDesktopHost;
|
||||
const unsubscribe = options.client.on("browser.automation.execute.request", (request) => {
|
||||
void handleBrowserAutomationRequest({
|
||||
@@ -66,9 +58,6 @@ export function mountBrowserAutomationHandler(
|
||||
serverId: options.serverId,
|
||||
ensureResidentBrowserWebview:
|
||||
options.ensureResidentBrowserWebview ?? ensureResidentBrowserWebviewDefault,
|
||||
readHostBrowserRouting: options.readHostBrowserRouting ?? readHostBrowserRoutingDefault,
|
||||
prepareHostBrowserPartition:
|
||||
options.prepareHostBrowserPartition ?? prepareHostBrowserPartitionDefault,
|
||||
...(options.registrationWaitTimeoutMs !== undefined
|
||||
? { registrationWaitTimeoutMs: options.registrationWaitTimeoutMs }
|
||||
: {}),
|
||||
@@ -128,8 +117,6 @@ async function handleBrowserAutomationRequest(params: {
|
||||
request: BrowserAutomationExecuteRequest;
|
||||
serverId?: string;
|
||||
ensureResidentBrowserWebview: typeof ensureResidentBrowserWebviewDefault;
|
||||
readHostBrowserRouting: typeof readHostBrowserRoutingDefault;
|
||||
prepareHostBrowserPartition: typeof prepareHostBrowserPartitionDefault;
|
||||
registrationWaitTimeoutMs?: number;
|
||||
registrationPollIntervalMs?: number;
|
||||
}): Promise<void> {
|
||||
@@ -139,8 +126,6 @@ async function handleBrowserAutomationRequest(params: {
|
||||
request,
|
||||
serverId,
|
||||
ensureResidentBrowserWebview,
|
||||
readHostBrowserRouting,
|
||||
prepareHostBrowserPartition,
|
||||
registrationWaitTimeoutMs,
|
||||
registrationPollIntervalMs,
|
||||
} = params;
|
||||
@@ -156,8 +141,6 @@ async function handleBrowserAutomationRequest(params: {
|
||||
serverId,
|
||||
browserHost,
|
||||
ensureResidentBrowserWebview,
|
||||
readHostBrowserRouting,
|
||||
prepareHostBrowserPartition,
|
||||
...(registrationWaitTimeoutMs !== undefined ? { registrationWaitTimeoutMs } : {}),
|
||||
...(registrationPollIntervalMs !== undefined ? { registrationPollIntervalMs } : {}),
|
||||
}),
|
||||
@@ -352,8 +335,6 @@ async function openBrowserTabForRequest(params: {
|
||||
serverId?: string;
|
||||
browserHost: DesktopHostBridge["browser"] | undefined;
|
||||
ensureResidentBrowserWebview: typeof ensureResidentBrowserWebviewDefault;
|
||||
readHostBrowserRouting: typeof readHostBrowserRoutingDefault;
|
||||
prepareHostBrowserPartition: typeof prepareHostBrowserPartitionDefault;
|
||||
registrationWaitTimeoutMs?: number;
|
||||
registrationPollIntervalMs?: number;
|
||||
}): Promise<BrowserAutomationResponsePayload> {
|
||||
@@ -362,8 +343,6 @@ async function openBrowserTabForRequest(params: {
|
||||
serverId,
|
||||
browserHost,
|
||||
ensureResidentBrowserWebview,
|
||||
readHostBrowserRouting,
|
||||
prepareHostBrowserPartition,
|
||||
registrationWaitTimeoutMs,
|
||||
registrationPollIntervalMs,
|
||||
} = params;
|
||||
@@ -380,27 +359,8 @@ async function openBrowserTabForRequest(params: {
|
||||
});
|
||||
}
|
||||
|
||||
const hostRouting = readHostBrowserRouting(serverId);
|
||||
let targetPartition: string | undefined;
|
||||
let routingMode: "host" | "local" | undefined;
|
||||
if (hostRouting.kind === "remote") {
|
||||
const prepared = await prepareHostBrowserPartition(serverId);
|
||||
if (!prepared.ok) {
|
||||
return browserAutomationFailure({
|
||||
requestId: request.requestId,
|
||||
code: "browser_unsupported",
|
||||
message: prepared.message,
|
||||
});
|
||||
}
|
||||
targetPartition = prepared.partition;
|
||||
routingMode = "host";
|
||||
}
|
||||
|
||||
const url = command.args.url ?? "https://example.com";
|
||||
const { browserId, url: normalizedUrl } = createWorkspaceBrowser({
|
||||
initialUrl: url,
|
||||
routingMode,
|
||||
});
|
||||
const { browserId, url: normalizedUrl } = createWorkspaceBrowser({ initialUrl: url });
|
||||
const workspaceKey = buildWorkspaceTabPersistenceKey({ serverId, workspaceId });
|
||||
if (!workspaceKey) {
|
||||
return browserAutomationFailure({
|
||||
@@ -416,12 +376,7 @@ async function openBrowserTabForRequest(params: {
|
||||
});
|
||||
|
||||
if (browserHost?.executeAutomationCommand) {
|
||||
ensureResidentBrowserWebview({
|
||||
browserId,
|
||||
workspaceId,
|
||||
url: normalizedUrl,
|
||||
...(targetPartition ? { partition: targetPartition } : {}),
|
||||
});
|
||||
ensureResidentBrowserWebview({ browserId, workspaceId, url: normalizedUrl });
|
||||
const registered = await waitForBrowserRegistration({
|
||||
request,
|
||||
browserId,
|
||||
|
||||
@@ -10,14 +10,7 @@ import {
|
||||
createElement,
|
||||
} from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import {
|
||||
Pressable,
|
||||
Text,
|
||||
View,
|
||||
type PressableStateCallbackType,
|
||||
type StyleProp,
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import { Pressable, Text, View, type StyleProp, type ViewStyle } from "react-native";
|
||||
import {
|
||||
EditingTextInput as TextInput,
|
||||
type EditingTextInputHandle,
|
||||
@@ -40,9 +33,7 @@ import {
|
||||
import { StyleSheet, useUnistyles, withUnistyles } from "react-native-unistyles";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import * as Clipboard from "expo-clipboard";
|
||||
import { Alert } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
@@ -60,12 +51,7 @@ import {
|
||||
import type { AttachmentMetadata, BrowserElementAttachment } from "@/attachments/types";
|
||||
import { persistAttachmentFromDataUrl } from "@/attachments/service";
|
||||
import { WORKSPACE_SECONDARY_HEADER_HEIGHT } from "@/constants/layout";
|
||||
import { defaultHostAppearance, resolveHostIcon } from "@/hosts/appearance";
|
||||
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
|
||||
import { getOverlayRoot } from "@/lib/overlay-root";
|
||||
import { useHosts } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { STATUS_INDICATOR_FILLED_DOT_SIZE } from "@/utils/status-indicator-geometry";
|
||||
import {
|
||||
getDesktopHost,
|
||||
isElectronRuntime,
|
||||
@@ -80,7 +66,6 @@ import {
|
||||
} from "@/desktop/browser/store";
|
||||
import {
|
||||
applyInactiveBrowserWebviewViewport,
|
||||
getResidentBrowserWebviewPartition,
|
||||
prepareBrowserWebview,
|
||||
presentBrowserWebview,
|
||||
rememberBrowserWebviewSize,
|
||||
@@ -88,7 +73,6 @@ import {
|
||||
removeResidentBrowserWebview,
|
||||
takeResidentBrowserWebview,
|
||||
} from "../resident-webviews";
|
||||
import { useHostBrowserProxy, type BrowserProxyPaneState } from "../proxy";
|
||||
import {
|
||||
createElementSelectorController,
|
||||
type BrowserElementSelection,
|
||||
@@ -492,211 +476,10 @@ const ThemedSmartphone = withUnistyles(Smartphone);
|
||||
const ThemedTablet = withUnistyles(Tablet);
|
||||
const ThemedMonitor = withUnistyles(Monitor);
|
||||
const ThemedChevronDown = withUnistyles(ChevronDown);
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
const deviceMutedIconMapping = (theme: { colors: { foregroundMuted: string } }) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
});
|
||||
|
||||
function BrowserRoutingButton({
|
||||
serverId,
|
||||
state,
|
||||
style,
|
||||
onToggle,
|
||||
}: {
|
||||
serverId: string;
|
||||
state: BrowserProxyPaneState;
|
||||
style: (state: { hovered?: boolean; pressed?: boolean }) => StyleProp<ViewStyle>;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const hosts = useHosts();
|
||||
const host = useMemo(
|
||||
() => hosts.find((entry) => entry.serverId === serverId) ?? null,
|
||||
[hosts, serverId],
|
||||
);
|
||||
const detectedMachineKind = useSessionStore(
|
||||
(store) => store.sessions[serverId]?.serverInfo?.machineKind ?? null,
|
||||
);
|
||||
const hostIcon = useMemo(
|
||||
() =>
|
||||
resolveHostIcon({
|
||||
appearance: host?.appearance ?? defaultHostAppearance(),
|
||||
detectedMachineKind,
|
||||
}),
|
||||
[detectedMachineKind, host?.appearance],
|
||||
);
|
||||
const hostColor = host?.appearance.color ?? "none";
|
||||
|
||||
const isHostRouted = state.effectiveRoutingMode === "host";
|
||||
const tooltipText = isHostRouted
|
||||
? t("workspace.browser.routing.tooltipHost", { hostName: state.hostLabel })
|
||||
: t("workspace.browser.routing.tooltipLocal", { hostName: state.hostLabel });
|
||||
const accessibilityLabel = isHostRouted
|
||||
? t("workspace.browser.routing.switchToLocal", { hostName: state.hostLabel })
|
||||
: t("workspace.browser.routing.switchToHost", { hostName: state.hostLabel });
|
||||
const accessibilityState = useMemo(() => ({ selected: isHostRouted }), [isHostRouted]);
|
||||
|
||||
let dotStyle = styles.routingDotPending;
|
||||
if (state.kind === "ready" && state.proxyStatus === "ready") {
|
||||
dotStyle = styles.routingDotReady;
|
||||
} else if (
|
||||
state.kind === "proxy_error" ||
|
||||
(state.kind === "ready" && state.proxyStatus === "error")
|
||||
) {
|
||||
dotStyle = styles.routingDotError;
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip delayDuration={0} enabledOnDesktop enabledOnMobile={false}>
|
||||
<TooltipTrigger asChild>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
accessibilityState={accessibilityState}
|
||||
onPress={onToggle}
|
||||
style={style}
|
||||
testID="browser-routing-pill"
|
||||
>
|
||||
{({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) =>
|
||||
isHostRouted ? (
|
||||
<View style={styles.routingIconFrame}>
|
||||
<HostIconGlyph icon={hostIcon} color={hostColor} size={16} />
|
||||
<View
|
||||
style={[
|
||||
styles.routingDotHalo,
|
||||
hovered || pressed ? styles.routingDotHaloHovered : styles.routingDotHaloRest,
|
||||
]}
|
||||
>
|
||||
<View style={[styles.routingDot, dotStyle]} />
|
||||
</View>
|
||||
</View>
|
||||
) : (
|
||||
<ThemedMonitor size={16} uniProps={deviceMutedIconMapping} />
|
||||
)
|
||||
}
|
||||
</Pressable>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom" align="center" offset={8}>
|
||||
<Text style={styles.toolbarTooltipText}>{tooltipText}</Text>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function BrowserProxyStatusPanel({
|
||||
state,
|
||||
onBrowseLocally,
|
||||
}: {
|
||||
state: Exclude<BrowserProxyPaneState, { kind: "ready" }>;
|
||||
onBrowseLocally: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (state.kind === "connecting") {
|
||||
const label = state.isReconnecting
|
||||
? t("workspace.browser.proxy.reconnecting", { hostName: state.hostLabel })
|
||||
: t("workspace.browser.proxy.connecting", { hostName: state.hostLabel });
|
||||
return (
|
||||
<View style={styles.proxyStatusContainer} testID="browser-proxy-status">
|
||||
<View style={styles.proxyConnectingCard}>
|
||||
<View style={styles.proxyConnectingRow}>
|
||||
<ThemedLoadingSpinner size={16} uniProps={deviceMutedIconMapping} />
|
||||
<Text style={styles.proxyConnectingText}>{label}</Text>
|
||||
</View>
|
||||
<Button variant="outline" onPress={onBrowseLocally} testID="browser-proxy-browse-locally">
|
||||
{t("workspace.browser.proxy.browseLocally")}
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (state.kind === "daemon_update_required") {
|
||||
return (
|
||||
<View style={styles.proxyStatusContainer} testID="browser-proxy-status">
|
||||
<View style={styles.proxyAlertFrame}>
|
||||
<Alert
|
||||
variant="warning"
|
||||
title={t("workspace.browser.proxy.updateTitle", { hostName: state.hostLabel })}
|
||||
description={t("workspace.browser.proxy.updateDescription")}
|
||||
>
|
||||
<Button
|
||||
variant="outline"
|
||||
onPress={onBrowseLocally}
|
||||
testID="browser-proxy-browse-locally"
|
||||
>
|
||||
{t("workspace.browser.proxy.browseLocally")}
|
||||
</Button>
|
||||
</Alert>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (state.kind === "routed_unsupported") {
|
||||
return (
|
||||
<View style={styles.proxyStatusContainer} testID="browser-proxy-status">
|
||||
<View style={styles.proxyAlertFrame}>
|
||||
<Alert
|
||||
variant="info"
|
||||
title={t("workspace.browser.proxy.routedTitle")}
|
||||
description={t("workspace.browser.proxy.routedDescription")}
|
||||
>
|
||||
<Button
|
||||
variant="outline"
|
||||
onPress={onBrowseLocally}
|
||||
testID="browser-proxy-browse-locally"
|
||||
>
|
||||
{t("workspace.browser.proxy.browseLocally")}
|
||||
</Button>
|
||||
</Alert>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (state.kind === "host_offline") {
|
||||
return (
|
||||
<View style={styles.proxyStatusContainer} testID="browser-proxy-status">
|
||||
<View style={styles.proxyAlertFrame}>
|
||||
<Alert
|
||||
variant="warning"
|
||||
title={t("workspace.browser.proxy.offlineTitle", { hostName: state.hostLabel })}
|
||||
description={t("workspace.browser.proxy.offlineDescription")}
|
||||
>
|
||||
<Button
|
||||
variant="outline"
|
||||
onPress={onBrowseLocally}
|
||||
testID="browser-proxy-browse-locally"
|
||||
>
|
||||
{t("workspace.browser.proxy.browseLocally")}
|
||||
</Button>
|
||||
</Alert>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.proxyStatusContainer} testID="browser-proxy-status">
|
||||
<View style={styles.proxyAlertFrame}>
|
||||
<Alert
|
||||
variant="error"
|
||||
title={t("workspace.browser.proxy.errorTitle")}
|
||||
description={state.message}
|
||||
>
|
||||
<Button variant="secondary" onPress={state.retry} testID="browser-proxy-retry">
|
||||
{t("common.actions.retry")}
|
||||
</Button>
|
||||
<Button variant="outline" onPress={onBrowseLocally} testID="browser-proxy-browse-locally">
|
||||
{t("workspace.browser.proxy.browseLocally")}
|
||||
</Button>
|
||||
</Alert>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function resolveThemedDeviceIcon(icon: LucideIcon): typeof ThemedMaximize {
|
||||
if (icon === Smartphone) return ThemedSmartphone;
|
||||
if (icon === Tablet) return ThemedTablet;
|
||||
@@ -790,32 +573,6 @@ function deviceSizeIdForViewport(viewport: BrowserViewport): DeviceSizeId | null
|
||||
);
|
||||
}
|
||||
|
||||
function acquirePartitionedWebview(input: {
|
||||
browserId: string;
|
||||
workspaceId: string;
|
||||
partition: string;
|
||||
initialUrl: string;
|
||||
}): ElectronWebview {
|
||||
const existingResident = takeResidentBrowserWebview(input.browserId) as ElectronWebview | null;
|
||||
if (
|
||||
existingResident &&
|
||||
getResidentBrowserWebviewPartition(existingResident) === input.partition
|
||||
) {
|
||||
return existingResident;
|
||||
}
|
||||
if (existingResident) {
|
||||
removeResidentBrowserWebview(input.browserId);
|
||||
}
|
||||
const webview = document.createElement("webview") as ElectronWebview;
|
||||
prepareBrowserWebview(webview, {
|
||||
browserId: input.browserId,
|
||||
workspaceId: input.workspaceId,
|
||||
initialUrl: input.initialUrl,
|
||||
partition: input.partition,
|
||||
});
|
||||
return webview;
|
||||
}
|
||||
|
||||
function rememberResolvedBrowserWebviewSize(browserId: string, webview: HTMLElement): void {
|
||||
const bounds = webview.getBoundingClientRect();
|
||||
rememberBrowserWebviewSize({ browserId, width: bounds.width, height: bounds.height });
|
||||
@@ -842,9 +599,6 @@ export function BrowserPane({
|
||||
const browser = useBrowserStore((state) => state.browsersById[browserId] ?? null);
|
||||
const updateBrowser = useBrowserStore((state) => state.updateBrowser);
|
||||
const setBrowserViewport = useBrowserStore((state) => state.setBrowserViewport);
|
||||
const setBrowserRoutingMode = useBrowserStore((state) => state.setBrowserRoutingMode);
|
||||
const proxyState = useHostBrowserProxy({ serverId, routingMode: browser?.routingMode });
|
||||
const activePartition = proxyState.kind === "ready" ? proxyState.partition : null;
|
||||
const browserViewport = browser?.viewport ?? RESPONSIVE_BROWSER_VIEWPORT;
|
||||
const browserViewportRef = useRef(browserViewport);
|
||||
browserViewportRef.current = browserViewport;
|
||||
@@ -972,32 +726,26 @@ export function BrowserPane({
|
||||
|
||||
const host = webviewHostRef.current;
|
||||
const clip = webviewClipRef.current;
|
||||
|
||||
if (!activePartition) {
|
||||
host?.replaceChildren();
|
||||
removeResidentBrowserWebview(browserId);
|
||||
webviewRef.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!host || !clip) {
|
||||
return;
|
||||
}
|
||||
|
||||
host.replaceChildren();
|
||||
|
||||
const currentUrl = browserRef.current?.url ?? initialUrlRef.current;
|
||||
const initialUnsafeNavigationMessage = getUnsafeNavigationMessage(
|
||||
currentUrl,
|
||||
initialUrlRef.current,
|
||||
browserErrorLabelsRef.current,
|
||||
);
|
||||
const webview = acquirePartitionedWebview({
|
||||
browserId,
|
||||
workspaceId,
|
||||
partition: activePartition,
|
||||
initialUrl: initialUnsafeNavigationMessage ? "about:blank" : currentUrl,
|
||||
});
|
||||
const residentWebview = takeResidentBrowserWebview(browserId) as ElectronWebview | null;
|
||||
const webview = residentWebview ?? (document.createElement("webview") as ElectronWebview);
|
||||
webviewRef.current = webview;
|
||||
if (!residentWebview) {
|
||||
prepareBrowserWebview(webview, {
|
||||
browserId,
|
||||
workspaceId,
|
||||
initialUrl: initialUnsafeNavigationMessage ? "about:blank" : initialUrlRef.current,
|
||||
});
|
||||
}
|
||||
releaseResidentBrowserWebview(browserId, webview);
|
||||
if (isPresentedRef.current) {
|
||||
presentBrowserWebview(browserId, webview, host, clip, browserViewportRef.current);
|
||||
@@ -1159,7 +907,7 @@ export function BrowserPane({
|
||||
}
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [activePartition, browserId, onFocusPane, workspaceId]);
|
||||
}, [browserId, onFocusPane]);
|
||||
|
||||
useEffect(() => {
|
||||
const webview = webviewRef.current;
|
||||
@@ -1667,18 +1415,6 @@ export function BrowserPane({
|
||||
[isResponsiveDevice],
|
||||
);
|
||||
|
||||
const handleToggleRoutingMode = useCallback(() => {
|
||||
if (!proxyState.isRemoteHost) {
|
||||
return;
|
||||
}
|
||||
const nextMode = proxyState.effectiveRoutingMode === "host" ? "local" : "host";
|
||||
setBrowserRoutingMode(browserId, nextMode);
|
||||
}, [browserId, proxyState.effectiveRoutingMode, proxyState.isRemoteHost, setBrowserRoutingMode]);
|
||||
|
||||
const handleBrowseLocally = useCallback(() => {
|
||||
setBrowserRoutingMode(browserId, "local");
|
||||
}, [browserId, setBrowserRoutingMode]);
|
||||
|
||||
const setWebviewHostNode = useCallback((node: HTMLDivElement | null) => {
|
||||
webviewHostRef.current = node;
|
||||
}, []);
|
||||
@@ -1728,14 +1464,6 @@ export function BrowserPane({
|
||||
<RotateCw size={16} color={theme.colors.foregroundMuted} />
|
||||
</ToolbarButton>
|
||||
</View>
|
||||
{proxyState.isRemoteHost ? (
|
||||
<BrowserRoutingButton
|
||||
serverId={serverId}
|
||||
state={proxyState}
|
||||
style={baseIconButtonStyle}
|
||||
onToggle={handleToggleRoutingMode}
|
||||
/>
|
||||
) : null}
|
||||
<View style={styles.urlBarWrap}>
|
||||
<TextInput
|
||||
accessibilityLabel={t("workspace.browser.controls.browserUrl")}
|
||||
@@ -1812,24 +1540,18 @@ export function BrowserPane({
|
||||
style={webviewWrapStyle}
|
||||
testID={`browser-webview-clip-${browserId}`}
|
||||
>
|
||||
{proxyState.kind === "ready" ? (
|
||||
<>
|
||||
{createElement("div", {
|
||||
ref: setWebviewHostNode,
|
||||
style: webviewHostStyle,
|
||||
})}
|
||||
{pendingSelection ? (
|
||||
<BrowserElementAnnotationCard
|
||||
anchor={webviewClipRef.current}
|
||||
selection={pendingSelection}
|
||||
onSubmit={submitAnnotation}
|
||||
onCancel={cancelAnnotation}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
<BrowserProxyStatusPanel state={proxyState} onBrowseLocally={handleBrowseLocally} />
|
||||
)}
|
||||
{createElement("div", {
|
||||
ref: setWebviewHostNode,
|
||||
style: webviewHostStyle,
|
||||
})}
|
||||
{pendingSelection ? (
|
||||
<BrowserElementAnnotationCard
|
||||
anchor={webviewClipRef.current}
|
||||
selection={pendingSelection}
|
||||
onSubmit={submitAnnotation}
|
||||
onCancel={cancelAnnotation}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
@@ -2131,65 +1853,4 @@ const styles = StyleSheet.create((theme) => ({
|
||||
unavailableSubtitle: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
routingIconFrame: {
|
||||
position: "relative",
|
||||
width: 18,
|
||||
height: 18,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
routingDotHalo: {
|
||||
position: "absolute",
|
||||
right: -2,
|
||||
bottom: -2,
|
||||
width: STATUS_INDICATOR_FILLED_DOT_SIZE + 3,
|
||||
height: STATUS_INDICATOR_FILLED_DOT_SIZE + 3,
|
||||
borderRadius: theme.borderRadius.full,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
routingDotHaloRest: {
|
||||
backgroundColor: theme.colors.surface0,
|
||||
},
|
||||
routingDotHaloHovered: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
routingDot: {
|
||||
width: STATUS_INDICATOR_FILLED_DOT_SIZE,
|
||||
height: STATUS_INDICATOR_FILLED_DOT_SIZE,
|
||||
borderRadius: theme.borderRadius.full,
|
||||
},
|
||||
routingDotReady: {
|
||||
backgroundColor: theme.colors.statusDotSuccess,
|
||||
},
|
||||
routingDotPending: {
|
||||
backgroundColor: theme.colors.statusDotWarning,
|
||||
},
|
||||
routingDotError: {
|
||||
backgroundColor: theme.colors.statusDotDanger,
|
||||
},
|
||||
proxyStatusContainer: {
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
padding: theme.spacing[6],
|
||||
backgroundColor: theme.colors.surface0,
|
||||
},
|
||||
proxyConnectingCard: {
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
proxyConnectingRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
proxyConnectingText: {
|
||||
fontSize: theme.fontSize.base,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
proxyAlertFrame: {
|
||||
width: "100%",
|
||||
maxWidth: 420,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
export {
|
||||
classifyHostBrowserRouting,
|
||||
extractBrowserProxyTarget,
|
||||
isLocalHostConnection,
|
||||
isLoopbackBrowserUrl,
|
||||
isLoopbackHost,
|
||||
shouldOpenUrlInProxiedWorkspaceBrowser,
|
||||
type ClassifyHostBrowserRoutingInput,
|
||||
type HostBrowserRouting,
|
||||
} from "./internal/classify";
|
||||
export {
|
||||
ensureHostBrowserProxy,
|
||||
installBrowserProxyRendererBridge,
|
||||
prepareHostBrowserPartition,
|
||||
readHostBrowserRouting,
|
||||
shouldRouteWorkspaceUrlToProxiedBrowser,
|
||||
type PrepareHostBrowserPartitionResult,
|
||||
} from "./internal/bridge";
|
||||
export { useHostBrowserProxy, type BrowserProxyPaneState } from "./internal/use-host-browser-proxy";
|
||||
@@ -1,307 +0,0 @@
|
||||
import { getIsElectron } from "@/constants/platform";
|
||||
import {
|
||||
getDesktopHost,
|
||||
type DesktopBrowserProxyStatusSnapshot,
|
||||
type DesktopBrowserProxyTicketRequestEvent,
|
||||
} from "@/desktop/host";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import {
|
||||
classifyHostBrowserRouting,
|
||||
shouldOpenUrlInProxiedWorkspaceBrowser,
|
||||
type HostBrowserRouting,
|
||||
} from "./classify";
|
||||
|
||||
const statusByServerId = new Map<string, DesktopBrowserProxyStatusSnapshot>();
|
||||
const statusListenersByServerId = new Map<string, Set<() => void>>();
|
||||
const trackedHostIds = new Set<string>();
|
||||
const lastHostConnectionStatus = new Map<string, string>();
|
||||
let bridgeInstalled = false;
|
||||
|
||||
function notifyStatusListeners(serverId: string): void {
|
||||
const listeners = statusListenersByServerId.get(serverId);
|
||||
if (!listeners) return;
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
function setCachedStatus(snapshot: DesktopBrowserProxyStatusSnapshot): void {
|
||||
const existing = statusByServerId.get(snapshot.serverId);
|
||||
if (
|
||||
existing &&
|
||||
existing.status === snapshot.status &&
|
||||
existing.error === snapshot.error &&
|
||||
existing.partition === snapshot.partition &&
|
||||
existing.socksPort === snapshot.socksPort
|
||||
) {
|
||||
return;
|
||||
}
|
||||
statusByServerId.set(snapshot.serverId, snapshot);
|
||||
notifyStatusListeners(snapshot.serverId);
|
||||
}
|
||||
|
||||
function isStatusSnapshot(value: unknown): value is DesktopBrowserProxyStatusSnapshot {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
||||
const record = value as Record<string, unknown>;
|
||||
return (
|
||||
typeof record.serverId === "string" &&
|
||||
typeof record.partition === "string" &&
|
||||
typeof record.status === "string"
|
||||
);
|
||||
}
|
||||
|
||||
function isTicketRequestEvent(value: unknown): value is DesktopBrowserProxyTicketRequestEvent {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
||||
const record = value as Record<string, unknown>;
|
||||
return typeof record.requestId === "string" && typeof record.serverId === "string";
|
||||
}
|
||||
|
||||
async function handleTicketRequest(event: DesktopBrowserProxyTicketRequestEvent): Promise<void> {
|
||||
const deliver = getDesktopHost()?.browser?.deliverProxyTicket;
|
||||
if (typeof deliver !== "function") return;
|
||||
|
||||
const snapshot = getHostRuntimeStore().getSnapshot(event.serverId);
|
||||
const client = snapshot?.client ?? null;
|
||||
if (!client || snapshot?.connectionStatus !== "online") {
|
||||
await deliver({
|
||||
requestId: event.requestId,
|
||||
error: i18n.t("workspace.terminal.hostDisconnected"),
|
||||
}).catch(() => {});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await client.createNetworkTunnelTicket();
|
||||
await deliver({ requestId: event.requestId, ticket: result.ticket });
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
await deliver({ requestId: event.requestId, error: message }).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
export function installBrowserProxyRendererBridge(): void {
|
||||
if (bridgeInstalled || !getIsElectron()) {
|
||||
return;
|
||||
}
|
||||
const desktop = getDesktopHost();
|
||||
if (!desktop?.events?.on || !desktop.browser?.ensureHostProxy) {
|
||||
return;
|
||||
}
|
||||
bridgeInstalled = true;
|
||||
|
||||
void desktop.events.on("browser-proxy-ticket-request", (payload) => {
|
||||
if (isTicketRequestEvent(payload)) {
|
||||
void handleTicketRequest(payload);
|
||||
}
|
||||
});
|
||||
|
||||
void desktop.events.on("browser-proxy-status", (payload) => {
|
||||
if (isStatusSnapshot(payload)) {
|
||||
setCachedStatus(payload);
|
||||
}
|
||||
});
|
||||
|
||||
const store = getHostRuntimeStore();
|
||||
store.subscribeAll(() => {
|
||||
const currentHosts = new Set(store.getHosts().map((host) => host.serverId));
|
||||
for (const serverId of trackedHostIds) {
|
||||
if (!currentHosts.has(serverId)) {
|
||||
trackedHostIds.delete(serverId);
|
||||
lastHostConnectionStatus.delete(serverId);
|
||||
statusByServerId.delete(serverId);
|
||||
notifyStatusListeners(serverId);
|
||||
void desktop.browser?.releaseHostProxy?.(serverId).catch(() => {});
|
||||
continue;
|
||||
}
|
||||
const nextConnectionStatus = store.getSnapshot(serverId)?.connectionStatus ?? "offline";
|
||||
const prevConnectionStatus = lastHostConnectionStatus.get(serverId);
|
||||
lastHostConnectionStatus.set(serverId, nextConnectionStatus);
|
||||
|
||||
const routing = readHostBrowserRouting(serverId);
|
||||
if (routing.kind === "remote" && routing.support === "supported") {
|
||||
if (prevConnectionStatus !== undefined && prevConnectionStatus !== "online") {
|
||||
// Control session just recovered after a drop; replace any half-open tunnel socket
|
||||
// immediately while keeping the fixed local SOCKS5 port and mounted webview intact.
|
||||
void ensureHostBrowserProxy({
|
||||
serverId,
|
||||
target: routing.target,
|
||||
forceReconnect: true,
|
||||
}).catch(() => {});
|
||||
} else {
|
||||
void desktop.browser
|
||||
?.updateHostProxyTarget?.({ serverId, target: routing.target })
|
||||
.catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function readHostBrowserRouting(serverId: string): HostBrowserRouting {
|
||||
const runtimeStore = getHostRuntimeStore();
|
||||
const host = runtimeStore.getHosts().find((entry) => entry.serverId === serverId) ?? null;
|
||||
const snapshot = runtimeStore.getSnapshot(serverId);
|
||||
const serverInfo = useSessionStore.getState().sessions[serverId]?.serverInfo ?? null;
|
||||
const supportsNetworkTunnel =
|
||||
serverInfo !== null ? serverInfo.features?.networkTunnel === true : null;
|
||||
|
||||
return classifyHostBrowserRouting({
|
||||
serverId,
|
||||
connections: host?.connections ?? [],
|
||||
activeConnection: snapshot?.activeConnection ?? null,
|
||||
activeConnectionId: snapshot?.activeConnectionId ?? null,
|
||||
connectionStatus: snapshot?.connectionStatus ?? "offline",
|
||||
supportsNetworkTunnel,
|
||||
});
|
||||
}
|
||||
|
||||
export function shouldRouteWorkspaceUrlToProxiedBrowser(input: {
|
||||
serverId: string;
|
||||
url: string;
|
||||
}): boolean {
|
||||
if (!getIsElectron()) {
|
||||
return false;
|
||||
}
|
||||
const routing = readHostBrowserRouting(input.serverId);
|
||||
return shouldOpenUrlInProxiedWorkspaceBrowser({
|
||||
isElectron: true,
|
||||
url: input.url,
|
||||
routing,
|
||||
});
|
||||
}
|
||||
|
||||
export function getCachedBrowserProxyStatus(
|
||||
serverId: string,
|
||||
): DesktopBrowserProxyStatusSnapshot | null {
|
||||
return statusByServerId.get(serverId) ?? null;
|
||||
}
|
||||
|
||||
export function subscribeBrowserProxyStatus(serverId: string, listener: () => void): () => void {
|
||||
let listeners = statusListenersByServerId.get(serverId);
|
||||
if (!listeners) {
|
||||
listeners = new Set();
|
||||
statusListenersByServerId.set(serverId, listeners);
|
||||
}
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners?.delete(listener);
|
||||
if (listeners && listeners.size === 0) {
|
||||
statusListenersByServerId.delete(serverId);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export async function ensureHostBrowserProxy(input: {
|
||||
serverId: string;
|
||||
target: NonNullable<
|
||||
Extract<HostBrowserRouting, { kind: "remote"; support: "supported" }>["target"]
|
||||
>;
|
||||
forceReconnect?: boolean;
|
||||
}): Promise<DesktopBrowserProxyStatusSnapshot | null> {
|
||||
installBrowserProxyRendererBridge();
|
||||
const ensureHostProxy = getDesktopHost()?.browser?.ensureHostProxy;
|
||||
if (typeof ensureHostProxy !== "function") {
|
||||
return null;
|
||||
}
|
||||
trackedHostIds.add(input.serverId);
|
||||
const currentStatus = getHostRuntimeStore().getSnapshot(input.serverId)?.connectionStatus;
|
||||
if (currentStatus) {
|
||||
lastHostConnectionStatus.set(input.serverId, currentStatus);
|
||||
}
|
||||
const snapshot = await ensureHostProxy(input);
|
||||
setCachedStatus(snapshot);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
export type PrepareHostBrowserPartitionResult =
|
||||
| { ok: true; partition: string; isRemoteHost: boolean }
|
||||
| {
|
||||
ok: false;
|
||||
reason:
|
||||
| "daemon_update_required"
|
||||
| "routed_unsupported"
|
||||
| "host_offline"
|
||||
| "host_connecting"
|
||||
| "proxy_error";
|
||||
message: string;
|
||||
};
|
||||
|
||||
export async function prepareHostBrowserPartition(
|
||||
serverId: string,
|
||||
options?: { forceReconnect?: boolean },
|
||||
): Promise<PrepareHostBrowserPartitionResult> {
|
||||
const desktop = getDesktopHost();
|
||||
const localPartition = desktop?.browser?.profilePartition;
|
||||
if (!localPartition) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "proxy_error",
|
||||
message: "Electron browser profile bridge is unavailable",
|
||||
};
|
||||
}
|
||||
|
||||
const routing = readHostBrowserRouting(serverId);
|
||||
if (routing.kind === "local") {
|
||||
return { ok: true, partition: localPartition, isRemoteHost: false };
|
||||
}
|
||||
|
||||
if (routing.support === "daemon_update_required") {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "daemon_update_required",
|
||||
message: "Update this host daemon to browse through the host proxy.",
|
||||
};
|
||||
}
|
||||
if (routing.support === "routed_unsupported") {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "routed_unsupported",
|
||||
message: "Browser proxying is not available for multi-hop routed hosts.",
|
||||
};
|
||||
}
|
||||
if (routing.support === "host_connecting") {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "host_connecting",
|
||||
message: "Host is still connecting.",
|
||||
};
|
||||
}
|
||||
if (routing.support === "host_offline") {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "host_offline",
|
||||
message: "Host is offline.",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const status = await ensureHostBrowserProxy({
|
||||
serverId,
|
||||
target: routing.target,
|
||||
forceReconnect: options?.forceReconnect,
|
||||
});
|
||||
if (!status) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "proxy_error",
|
||||
message: "Browser proxy bridge is unavailable in this desktop build.",
|
||||
};
|
||||
}
|
||||
if (status.status !== "ready") {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "proxy_error",
|
||||
message: status.error ?? "Unable to connect browser proxy.",
|
||||
};
|
||||
}
|
||||
return { ok: true, partition: status.partition, isRemoteHost: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "proxy_error",
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,238 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { HostConnection } from "@/types/host-connection";
|
||||
import {
|
||||
classifyHostBrowserRouting,
|
||||
extractBrowserProxyTarget,
|
||||
isLoopbackBrowserUrl,
|
||||
isLoopbackHost,
|
||||
shouldOpenUrlInProxiedWorkspaceBrowser,
|
||||
} from "./classify";
|
||||
|
||||
describe("loopback URL classification", () => {
|
||||
it("recognizes localhost, *.localhost, 127.x, and ::1 hosts", () => {
|
||||
expect(isLoopbackHost("localhost")).toBe(true);
|
||||
expect(isLoopbackHost("LOCALHOST")).toBe(true);
|
||||
expect(isLoopbackHost("web.localhost")).toBe(true);
|
||||
expect(isLoopbackHost("api.v2.localhost")).toBe(true);
|
||||
expect(isLoopbackHost("127.0.0.1")).toBe(true);
|
||||
expect(isLoopbackHost("127.0.0.2")).toBe(true);
|
||||
expect(isLoopbackHost("::1")).toBe(true);
|
||||
expect(isLoopbackHost("[::1]")).toBe(true);
|
||||
|
||||
expect(isLoopbackHost("example.com")).toBe(false);
|
||||
expect(isLoopbackHost("localhost.example.com")).toBe(false);
|
||||
expect(isLoopbackHost("192.168.1.5")).toBe(false);
|
||||
expect(isLoopbackHost("10.0.0.1")).toBe(false);
|
||||
});
|
||||
|
||||
it("matches only http/https loopback URLs", () => {
|
||||
expect(isLoopbackBrowserUrl("http://localhost:5173")).toBe(true);
|
||||
expect(isLoopbackBrowserUrl("https://app.localhost:6767/dashboard")).toBe(true);
|
||||
expect(isLoopbackBrowserUrl("http://127.0.0.1:3000/api")).toBe(true);
|
||||
expect(isLoopbackBrowserUrl("http://[::1]:8080")).toBe(true);
|
||||
|
||||
expect(isLoopbackBrowserUrl("https://github.com/getpaseo/paseo")).toBe(false);
|
||||
expect(isLoopbackBrowserUrl("http://10.0.0.5:3000")).toBe(false);
|
||||
expect(isLoopbackBrowserUrl("ws://localhost:3000")).toBe(false);
|
||||
expect(isLoopbackBrowserUrl("not-a-url")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("classifyHostBrowserRouting", () => {
|
||||
const remoteTcp: HostConnection = {
|
||||
id: "direct:10.0.0.5:6767",
|
||||
type: "directTcp",
|
||||
endpoint: "10.0.0.5:6767",
|
||||
};
|
||||
const localTcp: HostConnection = {
|
||||
id: "direct:127.0.0.1:6767",
|
||||
type: "directTcp",
|
||||
endpoint: "127.0.0.1:6767",
|
||||
};
|
||||
const localSocket: HostConnection = {
|
||||
id: "socket:/tmp/paseo.sock",
|
||||
type: "directSocket",
|
||||
path: "/tmp/paseo.sock",
|
||||
};
|
||||
const remoteSsh: HostConnection = {
|
||||
id: "ssh:devbox",
|
||||
type: "remoteSsh",
|
||||
host: "devbox",
|
||||
sshPort: 2222,
|
||||
daemonPort: 6767,
|
||||
};
|
||||
const relayConn: HostConnection = {
|
||||
id: "relay:relay.paseo.sh",
|
||||
type: "relay",
|
||||
relayEndpoint: "relay.paseo.sh",
|
||||
useTls: true,
|
||||
daemonPublicKeyB64: "AAAA",
|
||||
minimumSecurityMode: "protected",
|
||||
};
|
||||
const routedConn: HostConnection = {
|
||||
id: "routed:origin-1",
|
||||
type: "routed",
|
||||
originServerId: "origin-1",
|
||||
};
|
||||
|
||||
it("classifies local socket, pipe, and loopback directTcp connections as local", () => {
|
||||
expect(
|
||||
classifyHostBrowserRouting({
|
||||
serverId: "local-1",
|
||||
connections: [localSocket],
|
||||
activeConnection: { type: "directSocket", endpoint: "/tmp/paseo.sock", display: "socket" },
|
||||
activeConnectionId: localSocket.id,
|
||||
connectionStatus: "online",
|
||||
supportsNetworkTunnel: true,
|
||||
}),
|
||||
).toEqual({ kind: "local" });
|
||||
|
||||
expect(
|
||||
classifyHostBrowserRouting({
|
||||
serverId: "local-2",
|
||||
connections: [localTcp],
|
||||
activeConnection: {
|
||||
type: "directTcp",
|
||||
endpoint: "127.0.0.1:6767",
|
||||
display: "127.0.0.1:6767",
|
||||
},
|
||||
activeConnectionId: localTcp.id,
|
||||
connectionStatus: "online",
|
||||
supportsNetworkTunnel: true,
|
||||
}),
|
||||
).toEqual({ kind: "local" });
|
||||
});
|
||||
|
||||
it("classifies remote directTcp, SSH, and relay hosts with networkTunnel as supported", () => {
|
||||
expect(
|
||||
classifyHostBrowserRouting({
|
||||
serverId: "remote-tcp",
|
||||
connections: [remoteTcp],
|
||||
activeConnection: {
|
||||
type: "directTcp",
|
||||
endpoint: "10.0.0.5:6767",
|
||||
display: "10.0.0.5:6767",
|
||||
},
|
||||
activeConnectionId: remoteTcp.id,
|
||||
connectionStatus: "online",
|
||||
supportsNetworkTunnel: true,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "remote",
|
||||
support: "supported",
|
||||
target: { type: "directTcp", endpoint: "10.0.0.5:6767" },
|
||||
});
|
||||
|
||||
expect(extractBrowserProxyTarget("remote-ssh", remoteSsh)).toEqual({
|
||||
type: "remoteSsh",
|
||||
host: "devbox",
|
||||
sshPort: 2222,
|
||||
daemonPort: 6767,
|
||||
});
|
||||
|
||||
expect(extractBrowserProxyTarget("remote-relay", relayConn)).toEqual({
|
||||
type: "relay",
|
||||
serverId: "remote-relay",
|
||||
relayEndpoint: "relay.paseo.sh",
|
||||
useTls: true,
|
||||
daemonPublicKeyB64: "AAAA",
|
||||
minimumSecurityMode: "protected",
|
||||
});
|
||||
});
|
||||
|
||||
it("fails closed for old daemons, routed hosts, connecting hosts, and offline remote hosts", () => {
|
||||
expect(
|
||||
classifyHostBrowserRouting({
|
||||
serverId: "old-daemon",
|
||||
connections: [remoteTcp],
|
||||
activeConnection: {
|
||||
type: "directTcp",
|
||||
endpoint: "10.0.0.5:6767",
|
||||
display: "10.0.0.5:6767",
|
||||
},
|
||||
activeConnectionId: remoteTcp.id,
|
||||
connectionStatus: "online",
|
||||
supportsNetworkTunnel: false,
|
||||
}),
|
||||
).toEqual({ kind: "remote", support: "daemon_update_required" });
|
||||
|
||||
expect(
|
||||
classifyHostBrowserRouting({
|
||||
serverId: "routed-host",
|
||||
connections: [routedConn],
|
||||
activeConnection: { type: "routed", endpoint: "origin-1", display: "via origin-1" },
|
||||
activeConnectionId: routedConn.id,
|
||||
connectionStatus: "online",
|
||||
supportsNetworkTunnel: true,
|
||||
}),
|
||||
).toEqual({ kind: "remote", support: "routed_unsupported" });
|
||||
|
||||
expect(
|
||||
classifyHostBrowserRouting({
|
||||
serverId: "offline-remote",
|
||||
connections: [remoteSsh],
|
||||
activeConnection: null,
|
||||
activeConnectionId: null,
|
||||
connectionStatus: "offline",
|
||||
supportsNetworkTunnel: null,
|
||||
}),
|
||||
).toEqual({ kind: "remote", support: "host_offline" });
|
||||
|
||||
expect(
|
||||
classifyHostBrowserRouting({
|
||||
serverId: "connecting-remote",
|
||||
connections: [relayConn],
|
||||
activeConnection: null,
|
||||
activeConnectionId: null,
|
||||
connectionStatus: "connecting",
|
||||
supportsNetworkTunnel: null,
|
||||
}),
|
||||
).toEqual({ kind: "remote", support: "host_connecting" });
|
||||
});
|
||||
|
||||
it("routes only loopback URLs on supported remote hosts in Electron to a proxied browser tab", () => {
|
||||
const supportedRemote = {
|
||||
kind: "remote" as const,
|
||||
support: "supported" as const,
|
||||
target: { type: "directTcp" as const, endpoint: "10.0.0.5:6767" },
|
||||
};
|
||||
const oldRemote = { kind: "remote" as const, support: "daemon_update_required" as const };
|
||||
const local = { kind: "local" as const };
|
||||
|
||||
expect(
|
||||
shouldOpenUrlInProxiedWorkspaceBrowser({
|
||||
isElectron: true,
|
||||
url: "http://localhost:5173",
|
||||
routing: supportedRemote,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldOpenUrlInProxiedWorkspaceBrowser({
|
||||
isElectron: true,
|
||||
url: "https://github.com/getpaseo/paseo",
|
||||
routing: supportedRemote,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldOpenUrlInProxiedWorkspaceBrowser({
|
||||
isElectron: true,
|
||||
url: "http://localhost:5173",
|
||||
routing: oldRemote,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldOpenUrlInProxiedWorkspaceBrowser({
|
||||
isElectron: true,
|
||||
url: "http://localhost:5173",
|
||||
routing: local,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldOpenUrlInProxiedWorkspaceBrowser({
|
||||
isElectron: false,
|
||||
url: "http://localhost:5173",
|
||||
routing: supportedRemote,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,196 +0,0 @@
|
||||
import { parseHostPort } from "@getpaseo/protocol/daemon-endpoints";
|
||||
import type { DesktopBrowserProxyTarget } from "@/desktop/host";
|
||||
import type { ActiveConnection, HostRuntimeConnectionStatus } from "@/runtime/host-runtime";
|
||||
import type { HostConnection } from "@/types/host-connection";
|
||||
|
||||
const IPV4_LOOPBACK_PATTERN = /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;
|
||||
|
||||
export function isLoopbackHost(host: string): boolean {
|
||||
const normalized = host
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/^\[|\]$/g, "");
|
||||
if (!normalized) return false;
|
||||
return (
|
||||
normalized === "localhost" ||
|
||||
normalized.endsWith(".localhost") ||
|
||||
normalized === "::1" ||
|
||||
IPV4_LOOPBACK_PATTERN.test(normalized)
|
||||
);
|
||||
}
|
||||
|
||||
export function isLoopbackBrowserUrl(url: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
||||
return false;
|
||||
}
|
||||
return isLoopbackHost(parsed.hostname);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isLoopbackDirectTcpEndpoint(endpoint: string): boolean {
|
||||
try {
|
||||
const { host } = parseHostPort(endpoint);
|
||||
return isLoopbackHost(host);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function isLocalHostConnection(connection: HostConnection | ActiveConnection): boolean {
|
||||
if (connection.type === "directSocket" || connection.type === "directPipe") {
|
||||
return true;
|
||||
}
|
||||
if (connection.type === "directTcp") {
|
||||
return isLoopbackDirectTcpEndpoint(connection.endpoint);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function extractBrowserProxyTarget(
|
||||
serverId: string,
|
||||
connection: HostConnection,
|
||||
): DesktopBrowserProxyTarget | null {
|
||||
if (connection.type === "directTcp") {
|
||||
if (isLoopbackDirectTcpEndpoint(connection.endpoint)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
type: "directTcp",
|
||||
endpoint: connection.endpoint,
|
||||
...(connection.useTls !== undefined ? { useTls: connection.useTls } : {}),
|
||||
};
|
||||
}
|
||||
if (connection.type === "remoteSsh") {
|
||||
return {
|
||||
type: "remoteSsh",
|
||||
host: connection.host,
|
||||
...(connection.sshPort !== undefined ? { sshPort: connection.sshPort } : {}),
|
||||
...(connection.daemonPort !== undefined ? { daemonPort: connection.daemonPort } : {}),
|
||||
};
|
||||
}
|
||||
if (connection.type === "relay") {
|
||||
return {
|
||||
type: "relay",
|
||||
serverId,
|
||||
relayEndpoint: connection.relayEndpoint,
|
||||
...(connection.useTls !== undefined ? { useTls: connection.useTls } : {}),
|
||||
daemonPublicKeyB64: connection.daemonPublicKeyB64,
|
||||
...(connection.minimumSecurityMode === "protected"
|
||||
? { minimumSecurityMode: "protected" }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export type HostBrowserRouting =
|
||||
| { kind: "local" }
|
||||
| { kind: "remote"; support: "supported"; target: DesktopBrowserProxyTarget }
|
||||
| { kind: "remote"; support: "daemon_update_required" }
|
||||
| { kind: "remote"; support: "routed_unsupported" }
|
||||
| { kind: "remote"; support: "host_connecting" }
|
||||
| { kind: "remote"; support: "host_offline" };
|
||||
|
||||
export interface ClassifyHostBrowserRoutingInput {
|
||||
serverId: string;
|
||||
connections: readonly HostConnection[];
|
||||
activeConnection: ActiveConnection | null;
|
||||
activeConnectionId: string | null;
|
||||
connectionStatus: HostRuntimeConnectionStatus;
|
||||
supportsNetworkTunnel: boolean | null;
|
||||
}
|
||||
|
||||
function findMatchingHostConnection(
|
||||
connections: readonly HostConnection[],
|
||||
activeConnectionId: string | null,
|
||||
activeConnection: ActiveConnection | null,
|
||||
): HostConnection | null {
|
||||
if (activeConnectionId) {
|
||||
const byId = connections.find((conn) => conn.id === activeConnectionId);
|
||||
if (byId) return byId;
|
||||
}
|
||||
if (activeConnection) {
|
||||
const byType = connections.find((conn) => {
|
||||
if (conn.type !== activeConnection.type) return false;
|
||||
if (conn.type === "directTcp") return conn.endpoint === activeConnection.endpoint;
|
||||
if (conn.type === "remoteSsh") return conn.host === activeConnection.endpoint;
|
||||
if (conn.type === "relay") return conn.relayEndpoint === activeConnection.endpoint;
|
||||
if (conn.type === "routed") return conn.originServerId === activeConnection.endpoint;
|
||||
return true;
|
||||
});
|
||||
if (byType) return byType;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function classifyHostBrowserRouting(
|
||||
input: ClassifyHostBrowserRoutingInput,
|
||||
): HostBrowserRouting {
|
||||
const {
|
||||
serverId,
|
||||
connections,
|
||||
activeConnection,
|
||||
activeConnectionId,
|
||||
connectionStatus,
|
||||
supportsNetworkTunnel,
|
||||
} = input;
|
||||
|
||||
if (activeConnection) {
|
||||
if (isLocalHostConnection(activeConnection)) {
|
||||
return { kind: "local" };
|
||||
}
|
||||
if (activeConnection.type === "routed") {
|
||||
return { kind: "remote", support: "routed_unsupported" };
|
||||
}
|
||||
} else {
|
||||
// No active connection yet (connecting/offline). Distinguish local hosts from remote
|
||||
// hosts using saved connection definitions so remote tabs fail closed during startup.
|
||||
if (connections.length === 0 || connections.some(isLocalHostConnection)) {
|
||||
return { kind: "local" };
|
||||
}
|
||||
if (connections.every((conn) => conn.type === "routed")) {
|
||||
return { kind: "remote", support: "routed_unsupported" };
|
||||
}
|
||||
}
|
||||
|
||||
if (connectionStatus === "connecting" || connectionStatus === "idle") {
|
||||
return { kind: "remote", support: "host_connecting" };
|
||||
}
|
||||
if (connectionStatus !== "online") {
|
||||
return { kind: "remote", support: "host_offline" };
|
||||
}
|
||||
|
||||
// COMPAT(networkTunnel): added in v0.18.0, remove after 2027-05-26 once daemon floor >= v0.18.0.
|
||||
if (supportsNetworkTunnel !== true) {
|
||||
return { kind: "remote", support: "daemon_update_required" };
|
||||
}
|
||||
|
||||
const matchedConnection = findMatchingHostConnection(
|
||||
connections,
|
||||
activeConnectionId,
|
||||
activeConnection,
|
||||
);
|
||||
const target = matchedConnection ? extractBrowserProxyTarget(serverId, matchedConnection) : null;
|
||||
if (!target) {
|
||||
return { kind: "remote", support: "host_offline" };
|
||||
}
|
||||
|
||||
return { kind: "remote", support: "supported", target };
|
||||
}
|
||||
|
||||
export function shouldOpenUrlInProxiedWorkspaceBrowser(input: {
|
||||
isElectron: boolean;
|
||||
url: string;
|
||||
routing: HostBrowserRouting;
|
||||
}): boolean {
|
||||
return (
|
||||
input.isElectron &&
|
||||
isLoopbackBrowserUrl(input.url) &&
|
||||
input.routing.kind === "remote" &&
|
||||
input.routing.support === "supported"
|
||||
);
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveBrowserProxyPaneState } from "./use-host-browser-proxy";
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
describe("resolveBrowserProxyPaneState", () => {
|
||||
it("fails closed while connecting or offline before a host partition has been prepared", () => {
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: { kind: "remote", support: "host_connecting" },
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: null,
|
||||
ensureError: null,
|
||||
onRetry: noop,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "connecting",
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel: "devbox",
|
||||
isReconnecting: false,
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: { kind: "remote", support: "host_offline" },
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: {
|
||||
serverId: "srv-remote",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
status: "connecting",
|
||||
error: null,
|
||||
socksPort: null,
|
||||
},
|
||||
ensureError: null,
|
||||
onRetry: noop,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "host_offline",
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel: "devbox",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the prepared host partition mounted across transient host disconnects and reconnects", () => {
|
||||
const preparedSnapshot = {
|
||||
serverId: "srv-remote",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
status: "ready" as const,
|
||||
error: null,
|
||||
socksPort: 41234,
|
||||
};
|
||||
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: { kind: "remote", support: "host_offline" },
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: preparedSnapshot,
|
||||
ensureError: null,
|
||||
onRetry: noop,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "ready",
|
||||
partition: preparedSnapshot.partition,
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel: "devbox",
|
||||
proxyStatus: "reconnecting",
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: { kind: "remote", support: "host_connecting" },
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: preparedSnapshot,
|
||||
ensureError: null,
|
||||
onRetry: noop,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "ready",
|
||||
partition: preparedSnapshot.partition,
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel: "devbox",
|
||||
proxyStatus: "reconnecting",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the prepared host partition mounted when a background poll left cached status in error as host returns online", () => {
|
||||
const supportedRouting = {
|
||||
kind: "remote" as const,
|
||||
support: "supported" as const,
|
||||
target: { type: "directTcp" as const, endpoint: "10.0.0.5:6767" },
|
||||
};
|
||||
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: supportedRouting,
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: {
|
||||
serverId: "srv-remote",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
status: "error",
|
||||
error: "Host disconnected",
|
||||
socksPort: 41234,
|
||||
},
|
||||
ensureError: null,
|
||||
onRetry: noop,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "ready",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel: "devbox",
|
||||
proxyStatus: "error",
|
||||
});
|
||||
|
||||
// Once the live snapshot recovers to ready, a stale hook-local ensureError
|
||||
// must not pin the prepared pill dot to error.
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: supportedRouting,
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: {
|
||||
serverId: "srv-remote",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
status: "ready",
|
||||
error: null,
|
||||
socksPort: 41234,
|
||||
},
|
||||
ensureError: "Unable to create ticket",
|
||||
onRetry: noop,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "ready",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel: "devbox",
|
||||
proxyStatus: "ready",
|
||||
});
|
||||
|
||||
// Unprepared partition (socksPort === null) still fails closed with proxy_error.
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: supportedRouting,
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: {
|
||||
serverId: "srv-remote",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
status: "error",
|
||||
error: "Unable to create ticket",
|
||||
socksPort: null,
|
||||
},
|
||||
ensureError: null,
|
||||
onRetry: noop,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "proxy_error",
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel: "devbox",
|
||||
message: "Unable to create ticket",
|
||||
retry: noop,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,292 +0,0 @@
|
||||
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
|
||||
import { getIsElectron } from "@/constants/platform";
|
||||
import { getDesktopHost, type DesktopBrowserProxyStatus } from "@/desktop/host";
|
||||
import { resolveBrowserRoutingMode, type BrowserRoutingMode } from "@/desktop/browser/store";
|
||||
import { useHostRuntimeSnapshot, useHosts } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { normalizeHostLabel } from "@/types/host-connection";
|
||||
import {
|
||||
ensureHostBrowserProxy,
|
||||
getCachedBrowserProxyStatus,
|
||||
installBrowserProxyRendererBridge,
|
||||
subscribeBrowserProxyStatus,
|
||||
} from "./bridge";
|
||||
import { classifyHostBrowserRouting } from "./classify";
|
||||
|
||||
export type BrowserProxyPaneState =
|
||||
| {
|
||||
kind: "ready";
|
||||
partition: string;
|
||||
isRemoteHost: boolean;
|
||||
effectiveRoutingMode: BrowserRoutingMode;
|
||||
hostLabel: string;
|
||||
proxyStatus: DesktopBrowserProxyStatus | null;
|
||||
}
|
||||
| {
|
||||
kind: "connecting";
|
||||
isRemoteHost: true;
|
||||
effectiveRoutingMode: "host";
|
||||
hostLabel: string;
|
||||
isReconnecting: boolean;
|
||||
}
|
||||
| {
|
||||
kind: "daemon_update_required";
|
||||
isRemoteHost: true;
|
||||
effectiveRoutingMode: "host";
|
||||
hostLabel: string;
|
||||
}
|
||||
| {
|
||||
kind: "routed_unsupported";
|
||||
isRemoteHost: true;
|
||||
effectiveRoutingMode: "host";
|
||||
hostLabel: string;
|
||||
}
|
||||
| {
|
||||
kind: "host_offline";
|
||||
isRemoteHost: true;
|
||||
effectiveRoutingMode: "host";
|
||||
hostLabel: string;
|
||||
}
|
||||
| {
|
||||
kind: "proxy_error";
|
||||
isRemoteHost: true;
|
||||
effectiveRoutingMode: "host";
|
||||
hostLabel: string;
|
||||
message: string;
|
||||
retry: () => void;
|
||||
};
|
||||
|
||||
function hasPreparedHostPartition(
|
||||
snapshot: ReturnType<typeof getCachedBrowserProxyStatus>,
|
||||
): snapshot is NonNullable<ReturnType<typeof getCachedBrowserProxyStatus>> & {
|
||||
partition: string;
|
||||
socksPort: number;
|
||||
} {
|
||||
return Boolean(snapshot?.partition && snapshot.socksPort !== null);
|
||||
}
|
||||
|
||||
function resolveRemoteUnavailablePaneState(
|
||||
support: Exclude<
|
||||
Extract<ReturnType<typeof classifyHostBrowserRouting>, { kind: "remote" }>["support"],
|
||||
"supported"
|
||||
>,
|
||||
hostLabel: string,
|
||||
proxyStatusSnapshot: ReturnType<typeof getCachedBrowserProxyStatus>,
|
||||
): BrowserProxyPaneState {
|
||||
// Once Electron main has verified and bound this host's fixed SOCKS5 partition,
|
||||
// keep the webview mounted across transient host disconnects/reconnects so SPA
|
||||
// state, forms, scroll, and DevTools survive. Requests still fail closed at the
|
||||
// local SOCKS5 listener while the tunnel is down.
|
||||
const isTransientDisconnect = support === "host_connecting" || support === "host_offline";
|
||||
if (isTransientDisconnect && hasPreparedHostPartition(proxyStatusSnapshot)) {
|
||||
return {
|
||||
kind: "ready",
|
||||
partition: proxyStatusSnapshot.partition,
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel,
|
||||
proxyStatus: "reconnecting",
|
||||
};
|
||||
}
|
||||
if (support === "host_connecting") {
|
||||
return {
|
||||
kind: "connecting",
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel,
|
||||
isReconnecting: false,
|
||||
};
|
||||
}
|
||||
return {
|
||||
kind: support,
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel,
|
||||
};
|
||||
}
|
||||
|
||||
function resolvePreparedHostPaneStatus(
|
||||
status: DesktopBrowserProxyStatus,
|
||||
): DesktopBrowserProxyStatus {
|
||||
if (status === "ready" || status === "error") {
|
||||
return status;
|
||||
}
|
||||
return "reconnecting";
|
||||
}
|
||||
|
||||
export function resolveBrowserProxyPaneState(input: {
|
||||
routing: ReturnType<typeof classifyHostBrowserRouting>;
|
||||
effectiveRoutingMode: BrowserRoutingMode;
|
||||
localPartition: string;
|
||||
hostLabel: string;
|
||||
proxyStatusSnapshot: ReturnType<typeof getCachedBrowserProxyStatus>;
|
||||
ensureError: string | null;
|
||||
onRetry: () => void;
|
||||
}): BrowserProxyPaneState {
|
||||
const {
|
||||
routing,
|
||||
effectiveRoutingMode,
|
||||
localPartition,
|
||||
hostLabel,
|
||||
proxyStatusSnapshot,
|
||||
ensureError,
|
||||
onRetry,
|
||||
} = input;
|
||||
|
||||
if (routing.kind === "local" || effectiveRoutingMode === "local") {
|
||||
return {
|
||||
kind: "ready",
|
||||
partition: localPartition,
|
||||
isRemoteHost: routing.kind === "remote",
|
||||
effectiveRoutingMode: "local",
|
||||
hostLabel,
|
||||
proxyStatus: null,
|
||||
};
|
||||
}
|
||||
|
||||
if (routing.support !== "supported") {
|
||||
return resolveRemoteUnavailablePaneState(routing.support, hostLabel, proxyStatusSnapshot);
|
||||
}
|
||||
|
||||
// Once the fixed-port SOCKS5 session partition is verified (socksPort !== null),
|
||||
// keep the webview mounted even if a background poll (e.g. HMR) left the cached
|
||||
// tunnel status in "error" or "reconnecting" while the host reconnects.
|
||||
if (hasPreparedHostPartition(proxyStatusSnapshot)) {
|
||||
return {
|
||||
kind: "ready",
|
||||
partition: proxyStatusSnapshot.partition,
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel,
|
||||
proxyStatus: resolvePreparedHostPaneStatus(proxyStatusSnapshot.status),
|
||||
};
|
||||
}
|
||||
|
||||
const errorMessage =
|
||||
ensureError ?? (proxyStatusSnapshot?.status === "error" ? proxyStatusSnapshot.error : null);
|
||||
if (errorMessage) {
|
||||
return {
|
||||
kind: "proxy_error",
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel,
|
||||
message: errorMessage,
|
||||
retry: onRetry,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "connecting",
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel,
|
||||
isReconnecting: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function useHostBrowserProxy(input: {
|
||||
serverId: string;
|
||||
routingMode?: BrowserRoutingMode;
|
||||
}): BrowserProxyPaneState {
|
||||
const { serverId, routingMode } = input;
|
||||
const hosts = useHosts();
|
||||
const host = useMemo(
|
||||
() => hosts.find((entry) => entry.serverId === serverId) ?? null,
|
||||
[hosts, serverId],
|
||||
);
|
||||
const hostLabel = normalizeHostLabel(host?.label, serverId);
|
||||
const runtimeSnapshot = useHostRuntimeSnapshot(serverId);
|
||||
const supportsNetworkTunnel = useSessionStore((state) => {
|
||||
const serverInfo = state.sessions[serverId]?.serverInfo ?? null;
|
||||
return serverInfo !== null ? serverInfo.features?.networkTunnel === true : null;
|
||||
});
|
||||
|
||||
const proxyStatusSnapshot = useSyncExternalStore(
|
||||
useCallback((onChange) => subscribeBrowserProxyStatus(serverId, onChange), [serverId]),
|
||||
() => getCachedBrowserProxyStatus(serverId),
|
||||
() => getCachedBrowserProxyStatus(serverId),
|
||||
);
|
||||
|
||||
const [retryCounter, setRetryCounter] = useState(0);
|
||||
const [ensureError, setEnsureError] = useState<string | null>(null);
|
||||
|
||||
const routing = useMemo(
|
||||
() =>
|
||||
classifyHostBrowserRouting({
|
||||
serverId,
|
||||
connections: host?.connections ?? [],
|
||||
activeConnection: runtimeSnapshot?.activeConnection ?? null,
|
||||
activeConnectionId: runtimeSnapshot?.activeConnectionId ?? null,
|
||||
connectionStatus: runtimeSnapshot?.connectionStatus ?? "offline",
|
||||
supportsNetworkTunnel,
|
||||
}),
|
||||
[
|
||||
host?.connections,
|
||||
runtimeSnapshot?.activeConnection,
|
||||
runtimeSnapshot?.activeConnectionId,
|
||||
runtimeSnapshot?.connectionStatus,
|
||||
serverId,
|
||||
supportsNetworkTunnel,
|
||||
],
|
||||
);
|
||||
|
||||
const effectiveRoutingMode = resolveBrowserRoutingMode(
|
||||
{ routingMode },
|
||||
routing.kind === "remote",
|
||||
);
|
||||
const supportedTarget =
|
||||
routing.kind === "remote" && routing.support === "supported" ? routing.target : null;
|
||||
const targetKey = supportedTarget ? JSON.stringify(supportedTarget) : null;
|
||||
|
||||
const handleRetry = useCallback(() => {
|
||||
setEnsureError(null);
|
||||
setRetryCounter((count) => count + 1);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!getIsElectron() || effectiveRoutingMode !== "host" || !supportedTarget) {
|
||||
setEnsureError(null);
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
installBrowserProxyRendererBridge();
|
||||
setEnsureError(null);
|
||||
|
||||
void ensureHostBrowserProxy({
|
||||
serverId,
|
||||
target: supportedTarget,
|
||||
forceReconnect: retryCounter > 0,
|
||||
})
|
||||
.then((snapshot) => {
|
||||
if (cancelled) return undefined;
|
||||
if (!snapshot) {
|
||||
setEnsureError("Browser proxy bridge is unavailable.");
|
||||
} else if (snapshot.status === "error") {
|
||||
setEnsureError(snapshot.error ?? "Unable to connect browser proxy.");
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.catch((error) => {
|
||||
if (cancelled) return;
|
||||
setEnsureError(error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
// targetKey serializes supportedTarget deterministically.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [effectiveRoutingMode, retryCounter, serverId, targetKey]);
|
||||
|
||||
const localPartition = getDesktopHost()?.browser?.profilePartition ?? "persist:paseo-browser";
|
||||
return resolveBrowserProxyPaneState({
|
||||
routing,
|
||||
effectiveRoutingMode,
|
||||
localPartition,
|
||||
hostLabel,
|
||||
proxyStatusSnapshot,
|
||||
ensureError,
|
||||
onRetry: handleRetry,
|
||||
});
|
||||
}
|
||||
@@ -299,14 +299,12 @@ export function prepareBrowserWebview(
|
||||
browserId: string;
|
||||
workspaceId: string;
|
||||
initialUrl?: string | null;
|
||||
partition?: string;
|
||||
profileHost?: BrowserWebviewProfileHost;
|
||||
},
|
||||
): void {
|
||||
const browser = getBrowserBridge(input.profileHost);
|
||||
const targetPartition = input.partition ?? browser.profilePartition;
|
||||
webview.setAttribute(BROWSER_ID_ATTRIBUTE, input.browserId);
|
||||
webview.setAttribute("partition", targetPartition);
|
||||
webview.setAttribute("partition", browser.profilePartition);
|
||||
webview.setAttribute("allowpopups", "true");
|
||||
webview.setAttribute("spellcheck", "false");
|
||||
webview.setAttribute("autosize", "on");
|
||||
@@ -316,15 +314,10 @@ export function prepareBrowserWebview(
|
||||
registerBrowserWhenAttached(webview as BrowserWebviewElement, input, browser);
|
||||
}
|
||||
|
||||
export function getResidentBrowserWebviewPartition(webview: HTMLElement): string | null {
|
||||
return trimNonEmpty(webview.getAttribute("partition"));
|
||||
}
|
||||
|
||||
export function ensureResidentBrowserWebview(input: {
|
||||
browserId: string;
|
||||
workspaceId: string;
|
||||
url: string;
|
||||
partition?: string;
|
||||
profileHost?: BrowserWebviewProfileHost;
|
||||
}): HTMLElement | null {
|
||||
const browserId = trimNonEmpty(input.browserId);
|
||||
@@ -336,27 +329,18 @@ export function ensureResidentBrowserWebview(input: {
|
||||
return null;
|
||||
}
|
||||
|
||||
const browser = getBrowserBridge(input.profileHost);
|
||||
const desiredPartition = input.partition ?? browser.profilePartition;
|
||||
|
||||
const resident = residentWebviewsByBrowserId.get(browserId) ?? null;
|
||||
if (resident?.isConnected) {
|
||||
if (getResidentBrowserWebviewPartition(resident) === desiredPartition) {
|
||||
releaseResidentBrowserWebview(browserId, resident);
|
||||
return resident;
|
||||
}
|
||||
removeResidentBrowserWebview(browserId);
|
||||
releaseResidentBrowserWebview(browserId, resident);
|
||||
return resident;
|
||||
}
|
||||
|
||||
const existing = findBrowserWebview(browserId, ownerDocument);
|
||||
if (existing) {
|
||||
if (getResidentBrowserWebviewPartition(existing) === desiredPartition) {
|
||||
if (existing.parentElement?.id === RESIDENT_BROWSER_HOST_ID) {
|
||||
releaseResidentBrowserWebview(browserId, existing);
|
||||
}
|
||||
return existing;
|
||||
if (existing.parentElement?.id === RESIDENT_BROWSER_HOST_ID) {
|
||||
releaseResidentBrowserWebview(browserId, existing);
|
||||
}
|
||||
existing.remove();
|
||||
return existing;
|
||||
}
|
||||
|
||||
const webview = ownerDocument.createElement("webview") as BrowserWebviewElement;
|
||||
@@ -364,8 +348,7 @@ export function ensureResidentBrowserWebview(input: {
|
||||
browserId,
|
||||
workspaceId: input.workspaceId,
|
||||
initialUrl: input.url,
|
||||
partition: desiredPartition,
|
||||
profileHost: browser,
|
||||
profileHost: input.profileHost,
|
||||
});
|
||||
releaseResidentBrowserWebview(browserId, webview);
|
||||
return webview;
|
||||
|
||||
@@ -6,7 +6,6 @@ import { useToast } from "@/contexts/toast-context";
|
||||
import { getDesktopHost } from "@/desktop/host";
|
||||
import { SettingsSection } from "@/components/settings/headings/settings-section";
|
||||
import { useBrowserStore } from "@/desktop/browser/store";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import { confirmDialog } from "@/utils/confirm-dialog";
|
||||
|
||||
@@ -40,10 +39,7 @@ export function BrowserDataSection() {
|
||||
throw new Error("Electron browser profile bridge is unavailable");
|
||||
}
|
||||
|
||||
const hostServerIds = getHostRuntimeStore()
|
||||
.getHosts()
|
||||
.map((host) => host.serverId);
|
||||
await clearProfile(Object.keys(useBrowserStore.getState().browsersById), hostServerIds);
|
||||
await clearProfile(Object.keys(useBrowserStore.getState().browsersById));
|
||||
toast.show(t("settings.general.browserData.success"), { variant: "success" });
|
||||
} catch {
|
||||
toast.error(t("settings.general.browserData.error"));
|
||||
|
||||
@@ -9,31 +9,26 @@ import {
|
||||
type BrowserIndexState,
|
||||
type BrowserRecord,
|
||||
type BrowserRecordPatch,
|
||||
type BrowserRoutingMode,
|
||||
type BrowserViewport,
|
||||
createBrowserRecord,
|
||||
normalizeBrowserIndexState,
|
||||
normalizeBrowserUrl,
|
||||
removeBrowserFromIndex,
|
||||
resolveBrowserRoutingMode,
|
||||
sanitizeBrowsersForPersist,
|
||||
trimNonEmpty,
|
||||
} from "./state";
|
||||
|
||||
export {
|
||||
createFixedBrowserViewport,
|
||||
resolveBrowserRoutingMode,
|
||||
RESPONSIVE_BROWSER_VIEWPORT,
|
||||
type BrowserRecord,
|
||||
type BrowserRoutingMode,
|
||||
type BrowserViewport,
|
||||
} from "./state";
|
||||
|
||||
interface BrowserStoreState extends BrowserIndexState {
|
||||
createBrowser: (input?: { initialUrl?: string; routingMode?: BrowserRoutingMode }) => string;
|
||||
createBrowser: (input?: { initialUrl?: string }) => string;
|
||||
updateBrowser: (browserId: string, patch: BrowserRecordPatch) => void;
|
||||
setBrowserViewport: (browserId: string, viewport: BrowserViewport) => void;
|
||||
setBrowserRoutingMode: (browserId: string, routingMode: BrowserRoutingMode) => void;
|
||||
removeBrowser: (browserId: string) => void;
|
||||
}
|
||||
|
||||
@@ -57,7 +52,6 @@ export const useBrowserStore = create<BrowserStoreState>()(
|
||||
const record = createBrowserRecord({
|
||||
browserId,
|
||||
initialUrl: input?.initialUrl,
|
||||
routingMode: input?.routingMode,
|
||||
now: Date.now(),
|
||||
});
|
||||
|
||||
@@ -76,9 +70,6 @@ export const useBrowserStore = create<BrowserStoreState>()(
|
||||
setBrowserViewport: (browserId, viewport) => {
|
||||
set((state) => applyBrowserPatch(state, browserId, { viewport }));
|
||||
},
|
||||
setBrowserRoutingMode: (browserId, routingMode) => {
|
||||
set((state) => applyBrowserPatch(state, browserId, { routingMode }));
|
||||
},
|
||||
removeBrowser: (browserId) => {
|
||||
set((state) => removeBrowserFromIndex(state, browserId));
|
||||
},
|
||||
@@ -103,10 +94,7 @@ export function getBrowserRecord(browserId: string): BrowserRecord | null {
|
||||
return useBrowserStore.getState().browsersById[normalizedBrowserId] ?? null;
|
||||
}
|
||||
|
||||
export function createWorkspaceBrowser(input?: {
|
||||
initialUrl?: string;
|
||||
routingMode?: BrowserRoutingMode;
|
||||
}): {
|
||||
export function createWorkspaceBrowser(input?: { initialUrl?: string }): {
|
||||
browserId: string;
|
||||
url: string;
|
||||
} {
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
normalizeBrowserIndexState,
|
||||
normalizeBrowserUrl,
|
||||
removeBrowserFromIndex,
|
||||
resolveBrowserRoutingMode,
|
||||
sanitizeBrowsersForPersist,
|
||||
} from "./state";
|
||||
|
||||
@@ -189,23 +188,4 @@ describe("normalizeBrowserIndexState", () => {
|
||||
normalizeBrowserIndexState({ browsersById: { b1: legacy } }).browsersById.b1?.viewport,
|
||||
).toEqual({ mode: "responsive" });
|
||||
});
|
||||
|
||||
it("supports optional routingMode and defaults to host for remote workspaces and local for local workspaces", () => {
|
||||
const legacy = createBrowserRecord({
|
||||
browserId: "b1",
|
||||
initialUrl: "http://localhost:3000",
|
||||
now: 0,
|
||||
});
|
||||
expect(legacy.routingMode).toBeUndefined();
|
||||
expect(resolveBrowserRoutingMode(legacy, true)).toBe("host");
|
||||
expect(resolveBrowserRoutingMode(legacy, false)).toBe("local");
|
||||
|
||||
const updated = applyBrowserPatch(withRecords([legacy]), "b1", { routingMode: "local" });
|
||||
expect(updated.browsersById.b1?.routingMode).toBe("local");
|
||||
expect(resolveBrowserRoutingMode(updated.browsersById.b1, true)).toBe("local");
|
||||
|
||||
const persisted = sanitizeBrowsersForPersist(updated);
|
||||
const rehydrated = normalizeBrowserIndexState(persisted);
|
||||
expect(rehydrated.browsersById.b1?.routingMode).toBe("local");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,8 +4,6 @@ export type BrowserViewport =
|
||||
| { mode: "responsive" }
|
||||
| { mode: "fixed"; width: number; height: number };
|
||||
|
||||
export type BrowserRoutingMode = "host" | "local";
|
||||
|
||||
export const RESPONSIVE_BROWSER_VIEWPORT: BrowserViewport = { mode: "responsive" };
|
||||
|
||||
export interface BrowserRecord {
|
||||
@@ -18,7 +16,6 @@ export interface BrowserRecord {
|
||||
faviconUrl: string | null;
|
||||
lastError: string | null;
|
||||
viewport: BrowserViewport;
|
||||
routingMode?: BrowserRoutingMode;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
@@ -37,8 +34,6 @@ const BrowserViewportSchema = z.discriminatedUnion("mode", [
|
||||
}),
|
||||
]);
|
||||
|
||||
const BrowserRoutingModeSchema = z.enum(["host", "local"]);
|
||||
|
||||
const BrowserRecordSchema = z.strictObject({
|
||||
browserId: z.string(),
|
||||
url: z.string(),
|
||||
@@ -49,7 +44,6 @@ const BrowserRecordSchema = z.strictObject({
|
||||
faviconUrl: z.string().nullable(),
|
||||
lastError: z.string().nullable(),
|
||||
viewport: BrowserViewportSchema.optional().default(RESPONSIVE_BROWSER_VIEWPORT),
|
||||
routingMode: BrowserRoutingModeSchema.optional(),
|
||||
createdAt: z.number(),
|
||||
});
|
||||
|
||||
@@ -110,20 +104,9 @@ export function normalizeBrowserUrl(value: string | null | undefined): string {
|
||||
return `https://${trimmed}`;
|
||||
}
|
||||
|
||||
export function resolveBrowserRoutingMode(
|
||||
record: Pick<BrowserRecord, "routingMode"> | null | undefined,
|
||||
isRemoteHost: boolean,
|
||||
): BrowserRoutingMode {
|
||||
if (!isRemoteHost) {
|
||||
return "local";
|
||||
}
|
||||
return record?.routingMode === "local" ? "local" : "host";
|
||||
}
|
||||
|
||||
export function createBrowserRecord(input: {
|
||||
browserId: string;
|
||||
initialUrl: string | null | undefined;
|
||||
routingMode?: BrowserRoutingMode;
|
||||
now: number;
|
||||
}): BrowserRecord {
|
||||
return {
|
||||
@@ -136,7 +119,6 @@ export function createBrowserRecord(input: {
|
||||
faviconUrl: null,
|
||||
lastError: null,
|
||||
viewport: RESPONSIVE_BROWSER_VIEWPORT,
|
||||
...(input.routingMode ? { routingMode: input.routingMode } : {}),
|
||||
createdAt: input.now,
|
||||
};
|
||||
}
|
||||
@@ -173,7 +155,6 @@ export function applyBrowserPatch<S extends BrowserIndexState>(
|
||||
nextRecord.canGoForward === existing.canGoForward &&
|
||||
nextRecord.faviconUrl === existing.faviconUrl &&
|
||||
nextRecord.lastError === existing.lastError &&
|
||||
nextRecord.routingMode === existing.routingMode &&
|
||||
browserViewportsEqual(nextRecord.viewport, existing.viewport)
|
||||
) {
|
||||
return state;
|
||||
|
||||
@@ -144,42 +144,6 @@ export interface DesktopAttachedBrowserRegistration {
|
||||
webContentsId: number;
|
||||
}
|
||||
|
||||
export type DesktopBrowserProxyTarget =
|
||||
| {
|
||||
type: "directTcp";
|
||||
endpoint: string;
|
||||
useTls?: boolean;
|
||||
}
|
||||
| {
|
||||
type: "remoteSsh";
|
||||
host: string;
|
||||
sshPort?: number;
|
||||
daemonPort?: number;
|
||||
}
|
||||
| {
|
||||
type: "relay";
|
||||
serverId: string;
|
||||
relayEndpoint: string;
|
||||
useTls?: boolean;
|
||||
daemonPublicKeyB64: string;
|
||||
minimumSecurityMode?: "protected";
|
||||
};
|
||||
|
||||
export type DesktopBrowserProxyStatus = "idle" | "connecting" | "ready" | "reconnecting" | "error";
|
||||
|
||||
export interface DesktopBrowserProxyStatusSnapshot {
|
||||
serverId: string;
|
||||
partition: string;
|
||||
status: DesktopBrowserProxyStatus;
|
||||
error: string | null;
|
||||
socksPort: number | null;
|
||||
}
|
||||
|
||||
export interface DesktopBrowserProxyTicketRequestEvent {
|
||||
requestId: string;
|
||||
serverId: string;
|
||||
}
|
||||
|
||||
export interface DesktopBrowserBridge {
|
||||
setShortcutPolicy?: (input: BrowserKeyboardPolicy) => Promise<void>;
|
||||
readonly profilePartition?: string;
|
||||
@@ -191,23 +155,7 @@ export interface DesktopBrowserBridge {
|
||||
}) => Promise<void>;
|
||||
focus?: (browserId: string) => Promise<boolean>;
|
||||
openDevTools?: (browserId: string) => Promise<unknown>;
|
||||
clearProfile?: (legacyBrowserIds: string[], hostServerIds?: string[]) => Promise<void>;
|
||||
ensureHostProxy?: (input: {
|
||||
serverId: string;
|
||||
target: DesktopBrowserProxyTarget;
|
||||
forceReconnect?: boolean;
|
||||
}) => Promise<DesktopBrowserProxyStatusSnapshot>;
|
||||
updateHostProxyTarget?: (input: {
|
||||
serverId: string;
|
||||
target: DesktopBrowserProxyTarget;
|
||||
}) => Promise<void>;
|
||||
getHostProxyStatus?: (serverId: string) => Promise<DesktopBrowserProxyStatusSnapshot | null>;
|
||||
releaseHostProxy?: (serverId: string) => Promise<void>;
|
||||
deliverProxyTicket?: (input: {
|
||||
requestId: string;
|
||||
ticket?: string;
|
||||
error?: string;
|
||||
}) => Promise<void>;
|
||||
clearProfile?: (legacyBrowserIds: string[]) => Promise<void>;
|
||||
executeAutomationCommand?: (
|
||||
request: BrowserAutomationExecuteRequest,
|
||||
) => Promise<BrowserAutomationExecuteResponse["payload"]>;
|
||||
|
||||
@@ -656,24 +656,6 @@ export const ar: TranslationResources = {
|
||||
invalidUrl: "متصفح غير صالح URL",
|
||||
unsupportedProtocol: "متصفح محظور غير مدعوم URL:{{protocol}}",
|
||||
},
|
||||
routing: {
|
||||
tooltipHost: "التصفح عبر {{hostName}}. انقر للتصفح محلياً.",
|
||||
tooltipLocal: "التصفح محلياً. انقر للتصفح عبر {{hostName}}.",
|
||||
switchToLocal: "تبديل توجيه المتصفح من {{hostName}} إلى محلي",
|
||||
switchToHost: "تبديل توجيه المتصفح من محلي إلى {{hostName}}",
|
||||
},
|
||||
proxy: {
|
||||
connecting: "جارٍ الاتصال بـ {{hostName}}...",
|
||||
reconnecting: "جارٍ إعادة الاتصال بـ {{hostName}}...",
|
||||
updateTitle: "حدّث {{hostName}} للتصفح عبر هذا المضيف",
|
||||
updateDescription: "لا يدعم هذا المضيف وكيل المتصفح بعد.",
|
||||
routedTitle: "وكيل المتصفح غير متاح للمضيفين الموجَّهين",
|
||||
routedDescription: "اتصل مباشرة بهذا المضيف أو تصفح محلياً.",
|
||||
offlineTitle: "{{hostName}} غير متصل",
|
||||
offlineDescription: "انتظر إعادة اتصال المضيف أو تصفح محلياً.",
|
||||
errorTitle: "تعذر الاتصال بوكيل المتصفح",
|
||||
browseLocally: "التصفح محلياً",
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
hostDisconnected: "Host غير متصل",
|
||||
|
||||
@@ -655,24 +655,6 @@ export const en = {
|
||||
invalidUrl: "Invalid browser URL",
|
||||
unsupportedProtocol: "Blocked unsupported browser URL: {{protocol}}",
|
||||
},
|
||||
routing: {
|
||||
tooltipHost: "Browsing through {{hostName}}. Click to browse locally.",
|
||||
tooltipLocal: "Browsing locally. Click to browse through {{hostName}}.",
|
||||
switchToLocal: "Switch browser routing from {{hostName}} to Local",
|
||||
switchToHost: "Switch browser routing from Local to {{hostName}}",
|
||||
},
|
||||
proxy: {
|
||||
connecting: "Connecting to {{hostName}}...",
|
||||
reconnecting: "Reconnecting to {{hostName}}...",
|
||||
updateTitle: "Update {{hostName}} to browse through this host",
|
||||
updateDescription: "This host does not support browser proxying yet.",
|
||||
routedTitle: "Browser proxy is not available for routed hosts",
|
||||
routedDescription: "Connect directly to this host or browse locally.",
|
||||
offlineTitle: "{{hostName}} is offline",
|
||||
offlineDescription: "Wait for the host to reconnect or browse locally.",
|
||||
errorTitle: "Could not connect browser proxy",
|
||||
browseLocally: "Browse locally",
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
hostDisconnected: "Host is not connected",
|
||||
|
||||
@@ -662,24 +662,6 @@ export const es: TranslationResources = {
|
||||
invalidUrl: "Navegador no válidoURL",
|
||||
unsupportedProtocol: "Navegador bloqueado no compatibleURL:{{protocol}}",
|
||||
},
|
||||
routing: {
|
||||
tooltipHost: "Navegando a través de {{hostName}}. Haz clic para navegar localmente.",
|
||||
tooltipLocal: "Navegando localmente. Haz clic para navegar a través de {{hostName}}.",
|
||||
switchToLocal: "Cambiar el enrutamiento del navegador de {{hostName}} a Local",
|
||||
switchToHost: "Cambiar el enrutamiento del navegador de Local a {{hostName}}",
|
||||
},
|
||||
proxy: {
|
||||
connecting: "Conectando con {{hostName}}...",
|
||||
reconnecting: "Reconectando con {{hostName}}...",
|
||||
updateTitle: "Actualiza {{hostName}} para navegar a través de este host",
|
||||
updateDescription: "Este host todavía no admite el proxy del navegador.",
|
||||
routedTitle: "El proxy del navegador no está disponible para hosts enrutados",
|
||||
routedDescription: "Conéctate directamente a este host o navega localmente.",
|
||||
offlineTitle: "{{hostName}} está desconectado",
|
||||
offlineDescription: "Espera a que el host se reconecte o navega localmente.",
|
||||
errorTitle: "No se pudo conectar el proxy del navegador",
|
||||
browseLocally: "Navegar localmente",
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
hostDisconnected: "Hostno está conectado",
|
||||
|
||||
@@ -662,24 +662,6 @@ export const fr: TranslationResources = {
|
||||
invalidUrl: "URL du navigateur invalide",
|
||||
unsupportedProtocol: "URL bloquée, protocole non pris en charge : {{protocol}}",
|
||||
},
|
||||
routing: {
|
||||
tooltipHost: "Navigation via {{hostName}}. Cliquez pour naviguer en local.",
|
||||
tooltipLocal: "Navigation locale. Cliquez pour naviguer via {{hostName}}.",
|
||||
switchToLocal: "Basculer le routage du navigateur de {{hostName}} vers Local",
|
||||
switchToHost: "Basculer le routage du navigateur de Local vers {{hostName}}",
|
||||
},
|
||||
proxy: {
|
||||
connecting: "Connexion à {{hostName}}...",
|
||||
reconnecting: "Reconnexion à {{hostName}}...",
|
||||
updateTitle: "Mettez à jour {{hostName}} pour naviguer via cet hôte",
|
||||
updateDescription: "Cet hôte ne prend pas encore en charge le proxy du navigateur.",
|
||||
routedTitle: "Le proxy du navigateur n’est pas disponible pour les hôtes routés",
|
||||
routedDescription: "Connectez-vous directement à cet hôte ou naviguez en local.",
|
||||
offlineTitle: "{{hostName}} est hors ligne",
|
||||
offlineDescription: "Attendez la reconnexion de l’hôte ou naviguez en local.",
|
||||
errorTitle: "Impossible de connecter le proxy du navigateur",
|
||||
browseLocally: "Naviguer en local",
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
hostDisconnected: "L’hôte n’est pas connecté",
|
||||
|
||||
@@ -662,24 +662,6 @@ export const ja: TranslationResources = {
|
||||
invalidUrl: "無効なブラウザURL",
|
||||
unsupportedProtocol: "サポートされていないブラウザURLをブロック: {{protocol}}",
|
||||
},
|
||||
routing: {
|
||||
tooltipHost: "{{hostName}} 経由で閲覧中。クリックしてローカルで閲覧。",
|
||||
tooltipLocal: "ローカルで閲覧中。クリックして {{hostName}} 経由で閲覧。",
|
||||
switchToLocal: "ブラウザルーティングを {{hostName}} からローカルに切り替え",
|
||||
switchToHost: "ブラウザルーティングをローカルから {{hostName}} に切り替え",
|
||||
},
|
||||
proxy: {
|
||||
connecting: "{{hostName}} に接続中...",
|
||||
reconnecting: "{{hostName}} に再接続中...",
|
||||
updateTitle: "このホスト経由で閲覧するには {{hostName}} を更新してください",
|
||||
updateDescription: "このホストはまだブラウザプロキシに対応していません。",
|
||||
routedTitle: "ルーティングされたホストではブラウザプロキシを利用できません",
|
||||
routedDescription: "このホストに直接接続するか、ローカルで閲覧してください。",
|
||||
offlineTitle: "{{hostName}} はオフラインです",
|
||||
offlineDescription: "ホストの再接続を待つか、ローカルで閲覧してください。",
|
||||
errorTitle: "ブラウザプロキシに接続できませんでした",
|
||||
browseLocally: "ローカルで閲覧",
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
hostDisconnected: "ホストが接続されていません",
|
||||
|
||||
@@ -657,24 +657,6 @@ export const ko: TranslationResources = {
|
||||
invalidUrl: "잘못된 브라우저 URL",
|
||||
unsupportedProtocol: "지원되지 않는 브라우저 URL을 차단했습니다: {{protocol}}",
|
||||
},
|
||||
routing: {
|
||||
tooltipHost: "{{hostName}}을(를) 통해 탐색 중입니다. 클릭하여 로컬로 탐색하세요.",
|
||||
tooltipLocal: "로컬로 탐색 중입니다. 클릭하여 {{hostName}}을(를) 통해 탐색하세요.",
|
||||
switchToLocal: "브라우저 라우팅을 {{hostName}}에서 로컬로 전환",
|
||||
switchToHost: "브라우저 라우팅을 로컬에서 {{hostName}}(으)로 전환",
|
||||
},
|
||||
proxy: {
|
||||
connecting: "{{hostName}}에 연결 중...",
|
||||
reconnecting: "{{hostName}}에 다시 연결 중...",
|
||||
updateTitle: "이 호스트를 통해 탐색하려면 {{hostName}}을(를) 업데이트하세요",
|
||||
updateDescription: "이 호스트는 아직 브라우저 프록시를 지원하지 않습니다.",
|
||||
routedTitle: "라우팅된 호스트에서는 브라우저 프록시를 사용할 수 없습니다",
|
||||
routedDescription: "이 호스트에 직접 연결하거나 로컬로 탐색하세요.",
|
||||
offlineTitle: "{{hostName}}이(가) 오프라인입니다",
|
||||
offlineDescription: "호스트가 다시 연결될 때까지 기다리거나 로컬로 탐색하세요.",
|
||||
errorTitle: "브라우저 프록시에 연결할 수 없습니다",
|
||||
browseLocally: "로컬로 탐색",
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
hostDisconnected: "호스트가 연결되어 있지 않습니다",
|
||||
|
||||
@@ -661,24 +661,6 @@ export const ptBR: TranslationResources = {
|
||||
invalidUrl: "URL de navegador inválida",
|
||||
unsupportedProtocol: "URL de navegador sem suporte bloqueada: {{protocol}}",
|
||||
},
|
||||
routing: {
|
||||
tooltipHost: "Navegando por {{hostName}}. Clique para navegar localmente.",
|
||||
tooltipLocal: "Navegando localmente. Clique para navegar por {{hostName}}.",
|
||||
switchToLocal: "Alternar roteamento do navegador de {{hostName}} para Local",
|
||||
switchToHost: "Alternar roteamento do navegador de Local para {{hostName}}",
|
||||
},
|
||||
proxy: {
|
||||
connecting: "Conectando a {{hostName}}...",
|
||||
reconnecting: "Reconectando a {{hostName}}...",
|
||||
updateTitle: "Atualize {{hostName}} para navegar por este host",
|
||||
updateDescription: "Este host ainda não oferece suporte ao proxy do navegador.",
|
||||
routedTitle: "O proxy do navegador não está disponível para hosts roteados",
|
||||
routedDescription: "Conecte-se diretamente a este host ou navegue localmente.",
|
||||
offlineTitle: "{{hostName}} está offline",
|
||||
offlineDescription: "Aguarde o host reconectar ou navegue localmente.",
|
||||
errorTitle: "Não foi possível conectar o proxy do navegador",
|
||||
browseLocally: "Navegar localmente",
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
hostDisconnected: "Host não está conectado",
|
||||
|
||||
@@ -664,24 +664,6 @@ export const ru: TranslationResources = {
|
||||
unsupportedProtocol:
|
||||
"URL браузера с неподдерживаемым протоколом заблокирован: {{protocol}}",
|
||||
},
|
||||
routing: {
|
||||
tooltipHost: "Просмотр через {{hostName}}. Нажмите, чтобы перейти в локальный режим.",
|
||||
tooltipLocal: "Локальный просмотр. Нажмите, чтобы просматривать через {{hostName}}.",
|
||||
switchToLocal: "Переключить маршрутизацию браузера с {{hostName}} на локальную",
|
||||
switchToHost: "Переключить маршрутизацию браузера с локальной на {{hostName}}",
|
||||
},
|
||||
proxy: {
|
||||
connecting: "Подключение к {{hostName}}...",
|
||||
reconnecting: "Повторное подключение к {{hostName}}...",
|
||||
updateTitle: "Обновите {{hostName}}, чтобы просматривать через этот хост",
|
||||
updateDescription: "Этот хост пока не поддерживает проксирование браузера.",
|
||||
routedTitle: "Прокси браузера недоступен для маршрутизируемых хостов",
|
||||
routedDescription: "Подключитесь к хосту напрямую или просматривайте локально.",
|
||||
offlineTitle: "{{hostName}} не в сети",
|
||||
offlineDescription: "Дождитесь повторного подключения хоста или просматривайте локально.",
|
||||
errorTitle: "Не удалось подключить прокси браузера",
|
||||
browseLocally: "Просматривать локально",
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
hostDisconnected: "Хост не подключён",
|
||||
|
||||
@@ -656,24 +656,6 @@ export const zhCN: TranslationResources = {
|
||||
invalidUrl: "浏览器 URL 无效",
|
||||
unsupportedProtocol: "已阻止不支持的浏览器 URL:{{protocol}}",
|
||||
},
|
||||
routing: {
|
||||
tooltipHost: "正在通过 {{hostName}} 浏览。点击切换为本地浏览。",
|
||||
tooltipLocal: "正在本地浏览。点击切换为通过 {{hostName}} 浏览。",
|
||||
switchToLocal: "将浏览器路由从 {{hostName}} 切换为本地",
|
||||
switchToHost: "将浏览器路由从本地切换为 {{hostName}}",
|
||||
},
|
||||
proxy: {
|
||||
connecting: "正在连接到 {{hostName}}...",
|
||||
reconnecting: "正在重新连接到 {{hostName}}...",
|
||||
updateTitle: "请更新 {{hostName}} 以通过此主机浏览",
|
||||
updateDescription: "此主机尚不支持浏览器代理。",
|
||||
routedTitle: "路由主机不支持浏览器代理",
|
||||
routedDescription: "请直接连接到此主机,或改为本地浏览。",
|
||||
offlineTitle: "{{hostName}} 已离线",
|
||||
offlineDescription: "请等待主机重新连接,或改为本地浏览。",
|
||||
errorTitle: "无法连接浏览器代理",
|
||||
browseLocally: "本地浏览",
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
hostDisconnected: "Host 未连接",
|
||||
|
||||
@@ -14,10 +14,7 @@ import { buildTerminalsQueryKey } from "@/screens/workspace/terminals/state";
|
||||
import { showExplorerSidebar } from "@/workspace-tabs/explorer-sidebar";
|
||||
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { getIsElectron } from "@/constants/platform";
|
||||
import { createWorkspaceBrowser } from "@/desktop/browser/store";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
|
||||
import { useWorkspaceDirectory, useWorkspaceFields } from "@/stores/session-store-hooks";
|
||||
|
||||
type ListTerminalsPayload = ListTerminalsResponse["payload"];
|
||||
@@ -97,24 +94,6 @@ function TerminalPanel() {
|
||||
workspaceKey: buildWorkspaceTabPersistenceKey({ serverId, workspaceId }),
|
||||
});
|
||||
}, [isCompact, serverId, workspaceId, workspaceDirectory]);
|
||||
const handleOpenBrowserUrl = useCallback(
|
||||
(url: string) => {
|
||||
if (!getIsElectron()) {
|
||||
return;
|
||||
}
|
||||
const workspaceKey = buildWorkspaceTabPersistenceKey({ serverId, workspaceId });
|
||||
if (!workspaceKey) {
|
||||
return;
|
||||
}
|
||||
const { browserId } = createWorkspaceBrowser({ initialUrl: url });
|
||||
useWorkspaceLayoutStore.getState().openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "browser", browserId },
|
||||
intent: "reveal",
|
||||
});
|
||||
},
|
||||
[serverId, workspaceId],
|
||||
);
|
||||
invariant(target.kind === "terminal", "TerminalPanel requires terminal target");
|
||||
|
||||
if (!workspaceDirectory) {
|
||||
@@ -134,7 +113,6 @@ function TerminalPanel() {
|
||||
isPaneFocused={isPaneFocused}
|
||||
onOpenFileExplorer={handleOpenFileExplorer}
|
||||
onOpenWorkspaceFile={openFileInWorkspace}
|
||||
onOpenBrowserUrl={handleOpenBrowserUrl}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ export interface WorkspaceScriptLinks {
|
||||
}
|
||||
|
||||
export interface WorkspaceScriptActions {
|
||||
serverId?: string;
|
||||
start: (scriptName: string) => void;
|
||||
stop: (scriptName: string) => void;
|
||||
/** Stops the script, then starts it again once the daemon reports it stopped. */
|
||||
@@ -170,7 +169,6 @@ export function useWorkspaceScriptActions({
|
||||
|
||||
return useMemo(
|
||||
() => ({
|
||||
serverId,
|
||||
start: startScript,
|
||||
stop: stopScript,
|
||||
restart,
|
||||
@@ -181,7 +179,6 @@ export function useWorkspaceScriptActions({
|
||||
isStopPending: stopScriptMutation.isPending,
|
||||
}),
|
||||
[
|
||||
serverId,
|
||||
startScript,
|
||||
stopScript,
|
||||
restart,
|
||||
|
||||
@@ -324,11 +324,8 @@ function ScriptRow({
|
||||
const handleOpenService = useCallback(() => {
|
||||
if (!selectedLink) return;
|
||||
closeMenu();
|
||||
void openServiceUrl(selectedLink.url, {
|
||||
openInApp: onOpenUrlInBrowserTab,
|
||||
serverId: actions.serverId,
|
||||
});
|
||||
}, [actions.serverId, selectedLink, closeMenu, onOpenUrlInBrowserTab]);
|
||||
void openServiceUrl(selectedLink.url, { openInApp: onOpenUrlInBrowserTab });
|
||||
}, [selectedLink, closeMenu, onOpenUrlInBrowserTab]);
|
||||
|
||||
const handleView = useCallback(() => {
|
||||
if (liveTerminalId) onViewTerminal?.(liveTerminalId);
|
||||
|
||||
@@ -261,11 +261,8 @@ function RunningScriptPage({
|
||||
|
||||
const handleOpenService = useCallback(() => {
|
||||
if (!selected) return;
|
||||
void openServiceUrl(selected.url, {
|
||||
openInApp: onOpenUrlInBrowserTab,
|
||||
serverId: actions.serverId,
|
||||
});
|
||||
}, [actions.serverId, selected, onOpenUrlInBrowserTab]);
|
||||
void openServiceUrl(selected.url, { openInApp: onOpenUrlInBrowserTab });
|
||||
}, [selected, onOpenUrlInBrowserTab]);
|
||||
const handleViewTerminal = useCallback(() => {
|
||||
if (liveTerminalId) onViewTerminal(liveTerminalId);
|
||||
}, [liveTerminalId, onViewTerminal]);
|
||||
|
||||
@@ -3865,7 +3865,6 @@ function WorkspaceScreenContent({
|
||||
serverId={normalizedServerId}
|
||||
workspaceRoot={workspaceDirectory ?? undefined}
|
||||
onOpenWorkspaceFile={openMarkdownPath}
|
||||
onOpenBrowserUrl={handleOpenUrlInBrowserTab}
|
||||
toast={toast}
|
||||
>
|
||||
{renderedWorkspaceScreen}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { getDesktopHost, isElectronRuntime } from "@/desktop/host";
|
||||
import { shouldRouteWorkspaceUrlToProxiedBrowser } from "@/desktop/browser/proxy";
|
||||
import {
|
||||
loadAppSettingsFromStorage,
|
||||
persistAppSettings,
|
||||
@@ -10,7 +9,6 @@ import { openExternalUrl } from "@/utils/open-external-url";
|
||||
|
||||
export interface OpenServiceUrlOptions {
|
||||
openInApp?: (url: string) => void;
|
||||
serverId?: string;
|
||||
}
|
||||
|
||||
export async function openServiceUrl(url: string, options?: OpenServiceUrlOptions): Promise<void> {
|
||||
@@ -20,14 +18,6 @@ export async function openServiceUrl(url: string, options?: OpenServiceUrlOption
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
options?.serverId &&
|
||||
shouldRouteWorkspaceUrlToProxiedBrowser({ serverId: options.serverId, url })
|
||||
) {
|
||||
openInApp(url);
|
||||
return;
|
||||
}
|
||||
|
||||
const behavior = await resolveBehavior(url);
|
||||
if (behavior === "in-app") {
|
||||
openInApp(url);
|
||||
|
||||
@@ -1,139 +0,0 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { DaemonClient, type DaemonTransport } from "./daemon-client.js";
|
||||
|
||||
function createFakeTransport(features: Record<string, boolean | undefined>): {
|
||||
transport: DaemonTransport;
|
||||
sent: unknown[];
|
||||
} {
|
||||
const sent: unknown[] = [];
|
||||
const openHandlers = new Set<() => void>();
|
||||
const messageHandlers = new Set<(data: unknown, isBinary: boolean) => void | Promise<void>>();
|
||||
const closeHandlers = new Set<(event?: unknown) => void>();
|
||||
const errorHandlers = new Set<(event?: unknown) => void>();
|
||||
|
||||
const emitMessage = (text: string) => {
|
||||
queueMicrotask(() => {
|
||||
for (const handler of messageHandlers) {
|
||||
void handler(text, false);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const transport: DaemonTransport = {
|
||||
onOpen(handler) {
|
||||
openHandlers.add(handler);
|
||||
queueMicrotask(() => handler());
|
||||
return () => openHandlers.delete(handler);
|
||||
},
|
||||
onMessage(handler) {
|
||||
messageHandlers.add(handler);
|
||||
return () => messageHandlers.delete(handler);
|
||||
},
|
||||
onClose(handler) {
|
||||
closeHandlers.add(handler);
|
||||
return () => closeHandlers.delete(handler);
|
||||
},
|
||||
onError(handler) {
|
||||
errorHandlers.add(handler);
|
||||
return () => errorHandlers.delete(handler);
|
||||
},
|
||||
send(data) {
|
||||
if (typeof data !== "string") return;
|
||||
const parsed = JSON.parse(data) as {
|
||||
type: string;
|
||||
message?: { type: string; requestId?: string };
|
||||
};
|
||||
sent.push(parsed);
|
||||
|
||||
if (parsed.type === "hello") {
|
||||
emitMessage(
|
||||
JSON.stringify({
|
||||
type: "session",
|
||||
message: {
|
||||
type: "status",
|
||||
payload: {
|
||||
status: "server_info",
|
||||
serverId: "srv_test",
|
||||
version: "0.17.6",
|
||||
features,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
parsed.type === "session" &&
|
||||
parsed.message?.type === "network.tunnel.create_ticket.request" &&
|
||||
parsed.message.requestId
|
||||
) {
|
||||
const requestId = parsed.message.requestId;
|
||||
emitMessage(
|
||||
JSON.stringify({
|
||||
type: "session",
|
||||
message: {
|
||||
type: "network.tunnel.create_ticket.response",
|
||||
payload: {
|
||||
requestId,
|
||||
ticket: "tkt_fake_secret",
|
||||
expiresAtMs: 1_900_000_000_000,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
close() {
|
||||
for (const handler of closeHandlers) {
|
||||
handler({ code: 1000, reason: "closed" });
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
return { transport, sent };
|
||||
}
|
||||
|
||||
describe("DaemonClient.createNetworkTunnelTicket", () => {
|
||||
test("fails closed with unsupported_capability when daemon does not advertise features.networkTunnel", async () => {
|
||||
const { transport, sent } = createFakeTransport({});
|
||||
const client = new DaemonClient({
|
||||
url: "ws://127.0.0.1:6767/ws",
|
||||
clientId: "test-client",
|
||||
transportFactory: () => transport,
|
||||
});
|
||||
await client.connect();
|
||||
|
||||
await expect(client.createNetworkTunnelTicket()).rejects.toMatchObject({
|
||||
code: "unsupported_capability",
|
||||
});
|
||||
expect(
|
||||
sent.some(
|
||||
(m) =>
|
||||
(m as { message?: { type?: string } }).message?.type ===
|
||||
"network.tunnel.create_ticket.request",
|
||||
),
|
||||
).toBe(false);
|
||||
|
||||
await client.close();
|
||||
});
|
||||
|
||||
test("requests and returns a network tunnel ticket when features.networkTunnel is advertised", async () => {
|
||||
const { transport } = createFakeTransport({ networkTunnel: true });
|
||||
const client = new DaemonClient({
|
||||
url: "ws://127.0.0.1:6767/ws",
|
||||
clientId: "test-client",
|
||||
transportFactory: () => transport,
|
||||
});
|
||||
await client.connect();
|
||||
|
||||
const result = await client.createNetworkTunnelTicket("req-ticket-1");
|
||||
expect(result).toEqual({
|
||||
requestId: "req-ticket-1",
|
||||
ticket: "tkt_fake_secret",
|
||||
expiresAtMs: 1_900_000_000_000,
|
||||
});
|
||||
|
||||
await client.close();
|
||||
});
|
||||
});
|
||||
@@ -61,7 +61,6 @@ import type {
|
||||
CreatePaseoWorktreeRequest,
|
||||
FileDownloadTokenResponse,
|
||||
FileUploadResponse,
|
||||
NetworkTunnelCreateTicketPayload,
|
||||
FileExplorerResponse,
|
||||
FileVersion,
|
||||
FileWriteResult,
|
||||
@@ -5973,27 +5972,6 @@ export class DaemonClient {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests a short-lived single-use ticket for opening a dedicated binary
|
||||
* network tunnel WebSocket against this daemon.
|
||||
* Gated on `server_info.features.networkTunnel`.
|
||||
*/
|
||||
async createNetworkTunnelTicket(requestId?: string): Promise<NetworkTunnelCreateTicketPayload> {
|
||||
if (!this.isConnected) {
|
||||
throw this.unavailableError();
|
||||
}
|
||||
// COMPAT(networkTunnel): added in v0.17.6, remove gate after 2027-05-26.
|
||||
if (this.getLastServerInfoMessage()?.features?.networkTunnel !== true) {
|
||||
throw Object.assign(new Error("Update the daemon to use the network tunnel"), {
|
||||
code: "unsupported_capability",
|
||||
});
|
||||
}
|
||||
return this.sendNamespacedCorrelatedSessionRequest<"network.tunnel.create_ticket.response">({
|
||||
requestId,
|
||||
message: { type: "network.tunnel.create_ticket.request" },
|
||||
});
|
||||
}
|
||||
|
||||
async requestProjectIcon(
|
||||
cwd: string,
|
||||
requestId?: string,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,12 +1,14 @@
|
||||
import { validatePort, validateSshHost } from "@getpaseo/protocol/ssh-transport";
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { createServer, type Server, type Socket } from "node:net";
|
||||
import {
|
||||
buildSshTunnelArgs,
|
||||
DEFAULT_SSH_DAEMON_PORT,
|
||||
validatePort,
|
||||
validateSshHost,
|
||||
} from "@getpaseo/protocol/ssh-transport";
|
||||
import { stripAppImageRuntimeEnv } from "@getpaseo/server/process";
|
||||
import { BrowserWindow } from "electron";
|
||||
import { WebSocket, type RawData } from "ws";
|
||||
import {
|
||||
buildSshProxyArgs,
|
||||
buildSshSpawnEnv,
|
||||
createSshProxy,
|
||||
resolveSshFailureDetail,
|
||||
} from "./ssh-proxy.js";
|
||||
|
||||
export interface LocalTransportTarget {
|
||||
transportType: "socket" | "pipe";
|
||||
@@ -78,6 +80,7 @@ export interface LocalTransportManager {
|
||||
}
|
||||
|
||||
const WS_ENDPOINT_PATH = "/ws";
|
||||
const SSH_STDERR_LIMIT = 8192;
|
||||
export const LOCAL_TRANSPORT_SETUP_TIMEOUT_MS = 30_000;
|
||||
|
||||
function emitTransportEvent(payload: TransportEventPayload): void {
|
||||
@@ -169,10 +172,108 @@ function parseOpenTransportSessionInput(value: unknown): OpenTransportSessionInp
|
||||
}
|
||||
|
||||
export function buildSshArgs(target: SshTransportTarget): string[] {
|
||||
return buildSshProxyArgs(target);
|
||||
return buildSshTunnelArgs({
|
||||
host: target.host,
|
||||
...(target.sshPort !== undefined ? { sshPort: target.sshPort } : {}),
|
||||
daemonPort: target.daemonPort ?? DEFAULT_SSH_DAEMON_PORT,
|
||||
});
|
||||
}
|
||||
|
||||
export { buildSshSpawnEnv, resolveSshFailureDetail };
|
||||
function formatSshFailure(
|
||||
stderr: string,
|
||||
code: number | null,
|
||||
signal: NodeJS.Signals | null,
|
||||
): string {
|
||||
const detail = stderr.trim();
|
||||
if (detail) return detail;
|
||||
if (signal) return `ssh exited with signal ${signal}`;
|
||||
return `ssh exited with code ${code ?? "unknown"}`;
|
||||
}
|
||||
|
||||
export function resolveSshFailureDetail(failure: string | null, stderr: string): string | null {
|
||||
return failure ?? (stderr.trim() || null);
|
||||
}
|
||||
|
||||
export function buildSshSpawnEnv(
|
||||
baseEnv: NodeJS.ProcessEnv = process.env,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): NodeJS.ProcessEnv {
|
||||
const env = { ...baseEnv };
|
||||
stripAppImageRuntimeEnv(env, { platform });
|
||||
return env;
|
||||
}
|
||||
|
||||
function createSshProxy(target: SshTransportTarget): Promise<TransportEndpoint> {
|
||||
let server: Server | null = null;
|
||||
let socket: Socket | null = null;
|
||||
let child: ChildProcessWithoutNullStreams | null = null;
|
||||
let stderr = "";
|
||||
let failure: string | null = null;
|
||||
|
||||
function close(): void {
|
||||
server?.close();
|
||||
server = null;
|
||||
socket?.destroy();
|
||||
socket = null;
|
||||
if (child && !child.killed) {
|
||||
child.kill();
|
||||
}
|
||||
child = null;
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
server = createServer((acceptedSocket) => {
|
||||
socket = acceptedSocket;
|
||||
server?.close();
|
||||
server = null;
|
||||
|
||||
child = spawn("ssh", buildSshArgs(target), {
|
||||
env: buildSshSpawnEnv(),
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
windowsHide: true,
|
||||
});
|
||||
child.stderr.on("data", (chunk: Buffer | string) => {
|
||||
stderr = `${stderr}${chunk.toString()}`.slice(-SSH_STDERR_LIMIT);
|
||||
});
|
||||
child.on("error", (error) => {
|
||||
failure = error.message;
|
||||
acceptedSocket.destroy(error);
|
||||
});
|
||||
child.on("exit", (code, signal) => {
|
||||
if (code !== 0 || signal) {
|
||||
failure = formatSshFailure(stderr, code, signal);
|
||||
}
|
||||
acceptedSocket.destroy(failure ? new Error(failure) : undefined);
|
||||
});
|
||||
|
||||
acceptedSocket.on("error", () => undefined);
|
||||
acceptedSocket.on("close", () => {
|
||||
if (child && !child.killed) {
|
||||
child.kill();
|
||||
}
|
||||
});
|
||||
acceptedSocket.pipe(child.stdin);
|
||||
child.stdout.pipe(acceptedSocket);
|
||||
});
|
||||
server.once("error", (error) => {
|
||||
close();
|
||||
reject(error);
|
||||
});
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server?.address();
|
||||
if (!address || typeof address === "string") {
|
||||
close();
|
||||
reject(new Error("Failed to allocate the Remote SSH proxy port."));
|
||||
return;
|
||||
}
|
||||
resolve({
|
||||
url: `ws://127.0.0.1:${address.port}${WS_ENDPOINT_PATH}`,
|
||||
close,
|
||||
failureDetail: () => resolveSshFailureDetail(failure, stderr),
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function resolveTransportEndpoint(target: TransportTarget): Promise<TransportEndpoint> {
|
||||
if (target.transportType === "ssh") {
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { createServer, type Server, type Socket } from "node:net";
|
||||
import {
|
||||
buildSshTunnelArgs,
|
||||
DEFAULT_SSH_DAEMON_PORT,
|
||||
validatePort,
|
||||
validateSshHost,
|
||||
} from "@getpaseo/protocol/ssh-transport";
|
||||
import { stripAppImageRuntimeEnv } from "@getpaseo/server/process";
|
||||
|
||||
export interface SshProxyTarget {
|
||||
host: string;
|
||||
sshPort?: number;
|
||||
daemonPort?: number;
|
||||
}
|
||||
|
||||
export interface SshProxyEndpoint {
|
||||
url: string;
|
||||
close: () => void;
|
||||
failureDetail: () => string | null;
|
||||
}
|
||||
|
||||
const WS_ENDPOINT_PATH = "/ws";
|
||||
const SSH_STDERR_LIMIT = 8192;
|
||||
|
||||
export function buildSshProxyArgs(target: SshProxyTarget): string[] {
|
||||
const host = validateSshHost(target.host);
|
||||
const sshPort =
|
||||
target.sshPort !== undefined ? validatePort(target.sshPort, "SSH port") : undefined;
|
||||
const daemonPort =
|
||||
target.daemonPort !== undefined
|
||||
? validatePort(target.daemonPort, "Daemon port")
|
||||
: DEFAULT_SSH_DAEMON_PORT;
|
||||
|
||||
return buildSshTunnelArgs({
|
||||
host,
|
||||
...(sshPort !== undefined ? { sshPort } : {}),
|
||||
daemonPort,
|
||||
});
|
||||
}
|
||||
|
||||
function formatSshFailure(
|
||||
stderr: string,
|
||||
code: number | null,
|
||||
signal: NodeJS.Signals | null,
|
||||
): string {
|
||||
const detail = stderr.trim();
|
||||
if (detail) return detail;
|
||||
if (signal) return `ssh exited with signal ${signal}`;
|
||||
return `ssh exited with code ${code ?? "unknown"}`;
|
||||
}
|
||||
|
||||
export function resolveSshFailureDetail(failure: string | null, stderr: string): string | null {
|
||||
return failure ?? (stderr.trim() || null);
|
||||
}
|
||||
|
||||
export function buildSshSpawnEnv(
|
||||
baseEnv: NodeJS.ProcessEnv = process.env,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): NodeJS.ProcessEnv {
|
||||
const env = { ...baseEnv };
|
||||
stripAppImageRuntimeEnv(env, { platform });
|
||||
return env;
|
||||
}
|
||||
|
||||
export function createSshProxy(target: SshProxyTarget): Promise<SshProxyEndpoint> {
|
||||
const sshArgs = buildSshProxyArgs(target);
|
||||
let server: Server | null = null;
|
||||
let socket: Socket | null = null;
|
||||
let child: ChildProcessWithoutNullStreams | null = null;
|
||||
let stderr = "";
|
||||
let failure: string | null = null;
|
||||
|
||||
function close(): void {
|
||||
server?.close();
|
||||
server = null;
|
||||
socket?.destroy();
|
||||
socket = null;
|
||||
if (child && !child.killed) {
|
||||
child.kill();
|
||||
}
|
||||
child = null;
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
server = createServer((acceptedSocket) => {
|
||||
socket = acceptedSocket;
|
||||
server?.close();
|
||||
server = null;
|
||||
|
||||
child = spawn("ssh", sshArgs, {
|
||||
env: buildSshSpawnEnv(),
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
windowsHide: true,
|
||||
});
|
||||
child.stdin.on("error", () => undefined);
|
||||
child.stderr.on("data", (chunk: Buffer | string) => {
|
||||
stderr = `${stderr}${chunk.toString()}`.slice(-SSH_STDERR_LIMIT);
|
||||
});
|
||||
child.on("error", (error) => {
|
||||
failure = error.message;
|
||||
acceptedSocket.destroy(error);
|
||||
});
|
||||
child.on("exit", (code, signal) => {
|
||||
if (code !== 0 || signal) {
|
||||
failure = formatSshFailure(stderr, code, signal);
|
||||
}
|
||||
acceptedSocket.destroy(failure ? new Error(failure) : undefined);
|
||||
});
|
||||
|
||||
acceptedSocket.on("error", () => undefined);
|
||||
acceptedSocket.on("close", () => {
|
||||
if (child && !child.killed) {
|
||||
child.kill();
|
||||
}
|
||||
});
|
||||
acceptedSocket.pipe(child.stdin);
|
||||
child.stdout.pipe(acceptedSocket);
|
||||
});
|
||||
server.once("error", (error) => {
|
||||
close();
|
||||
reject(error);
|
||||
});
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server?.address();
|
||||
if (!address || typeof address === "string") {
|
||||
close();
|
||||
reject(new Error("Failed to allocate the Remote SSH proxy port."));
|
||||
return;
|
||||
}
|
||||
resolve({
|
||||
url: `ws://127.0.0.1:${address.port}${WS_ENDPOINT_PATH}`,
|
||||
close,
|
||||
failureDetail: () => resolveSshFailureDetail(failure, stderr),
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,17 +1,11 @@
|
||||
import { mkdtempSync, mkdirSync, rmSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
clearPaseoBrowserProfile,
|
||||
getLegacyPaseoBrowserProfileSession,
|
||||
getPaseoBrowserProfileSessions,
|
||||
listDiskHostBrowserProxyPartitions,
|
||||
listPaseoBrowserProfileGuests,
|
||||
readHostBrowserProxyPartitions,
|
||||
readLegacyPaseoBrowserIds,
|
||||
} from "./browser-profile.js";
|
||||
import { getHostBrowserProxyPartition } from "./browser-proxy/partition.js";
|
||||
|
||||
class FakeProfileSession {
|
||||
public readonly storageClears: unknown[] = [];
|
||||
@@ -93,57 +87,6 @@ describe("listPaseoBrowserProfileGuests", () => {
|
||||
|
||||
expect(guests).toEqual([firstWindowGuest, secondWindowGuest, popupWindow]);
|
||||
});
|
||||
|
||||
test("returns live guests across both local and host proxy sessions", () => {
|
||||
const localSession = {};
|
||||
const hostSession = {};
|
||||
const localGuest = new FakeWebContents(1, localSession, "webview");
|
||||
const hostGuest = new FakeWebContents(2, hostSession, "webview");
|
||||
const hostPopup = new FakeWebContents(3, hostSession, "window");
|
||||
const foreignGuest = new FakeWebContents(4, {}, "webview");
|
||||
|
||||
const guests = listPaseoBrowserProfileGuests({
|
||||
profileSessions: [localSession, hostSession],
|
||||
webContents: [localGuest, hostGuest, hostPopup, foreignGuest],
|
||||
});
|
||||
|
||||
expect(guests).toEqual([localGuest, hostGuest, hostPopup]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("host browser proxy partitions cleanup", () => {
|
||||
test("discovers persisted host proxy partitions from userData and includes them in profile sessions", () => {
|
||||
const tmpDir = mkdtempSync(path.join(os.tmpdir(), "paseo-profile-test-"));
|
||||
try {
|
||||
const diskPartition = getHostBrowserProxyPartition("disk-host");
|
||||
const dirName = diskPartition.replace(/^persist:/, "");
|
||||
mkdirSync(path.join(tmpDir, "Partitions", dirName), { recursive: true });
|
||||
mkdirSync(path.join(tmpDir, "Partitions", "paseo-browser"), { recursive: true });
|
||||
mkdirSync(path.join(tmpDir, "Partitions", "unrelated-partition"), { recursive: true });
|
||||
|
||||
expect(listDiskHostBrowserProxyPartitions(tmpDir)).toEqual([diskPartition]);
|
||||
|
||||
const derived = readHostBrowserProxyPartitions(["runtime-host", diskPartition, "", 42]);
|
||||
const expectedRuntimePartition = getHostBrowserProxyPartition("runtime-host");
|
||||
expect(derived).toEqual([expectedRuntimePartition, diskPartition]);
|
||||
|
||||
const requested: string[] = [];
|
||||
getPaseoBrowserProfileSessions(
|
||||
{
|
||||
fromPartition: (partition) => {
|
||||
requested.push(partition);
|
||||
return new FakeProfileSession();
|
||||
},
|
||||
},
|
||||
[],
|
||||
[...derived, diskPartition, "persist:foreign"],
|
||||
);
|
||||
|
||||
expect(requested).toEqual(["persist:paseo-browser", expectedRuntimePartition, diskPartition]);
|
||||
} finally {
|
||||
rmSync(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("legacy browser profiles", () => {
|
||||
|
||||
@@ -1,16 +1,7 @@
|
||||
import { readdirSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import {
|
||||
getHostBrowserProxyPartition,
|
||||
isHostBrowserProxyPartition,
|
||||
} from "./browser-proxy/partition.js";
|
||||
|
||||
export const PASEO_BROWSER_PROFILE_PARTITION = "persist:paseo-browser";
|
||||
const LEGACY_BROWSER_ID_PATTERN =
|
||||
/^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|\d{13,}-[0-9a-f]+)$/i;
|
||||
const MAX_LEGACY_BROWSER_PROFILES = 1000;
|
||||
const MAX_HOST_BROWSER_PROFILES = 500;
|
||||
const DISK_HOST_PARTITION_DIR_PATTERN = /^paseo-browser-host-[0-9a-f]{16}$/;
|
||||
|
||||
const PASEO_BROWSER_STORAGE_TYPES = [
|
||||
"cookies",
|
||||
@@ -42,8 +33,7 @@ interface BrowserProfileWebContents extends BrowserProfileGuest {
|
||||
}
|
||||
|
||||
interface ListBrowserProfileGuestsInput {
|
||||
profileSession?: object;
|
||||
profileSessions?: Iterable<object>;
|
||||
profileSession: object;
|
||||
webContents: BrowserProfileWebContents[];
|
||||
}
|
||||
|
||||
@@ -77,67 +67,17 @@ export function readLegacyPaseoBrowserIds(input: unknown): string[] {
|
||||
return [...browserIds];
|
||||
}
|
||||
|
||||
export function readHostBrowserProxyPartitions(input: unknown): string[] {
|
||||
if (!Array.isArray(input)) {
|
||||
return [];
|
||||
}
|
||||
const partitions = new Set<string>();
|
||||
for (const value of input) {
|
||||
if (typeof value !== "string") continue;
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) continue;
|
||||
partitions.add(
|
||||
isHostBrowserProxyPartition(trimmed) ? trimmed : getHostBrowserProxyPartition(trimmed),
|
||||
);
|
||||
if (partitions.size >= MAX_HOST_BROWSER_PROFILES) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return [...partitions];
|
||||
}
|
||||
|
||||
export function listDiskHostBrowserProxyPartitions(userDataDir: string): string[] {
|
||||
try {
|
||||
const partitionsDir = path.join(userDataDir, "Partitions");
|
||||
const entries = readdirSync(partitionsDir, { withFileTypes: true });
|
||||
const result: string[] = [];
|
||||
for (const entry of entries) {
|
||||
if (entry.isDirectory() && DISK_HOST_PARTITION_DIR_PATTERN.test(entry.name)) {
|
||||
result.push(`persist:${entry.name}`);
|
||||
}
|
||||
}
|
||||
return result.sort();
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function getPaseoBrowserProfileSessions(
|
||||
sessions: ElectronSessions,
|
||||
legacyBrowserIds: string[],
|
||||
hostPartitions: readonly string[] = [],
|
||||
): [BrowserProfileSession, ...BrowserProfileSession[]] {
|
||||
const localSession = getPaseoBrowserProfileSession(sessions);
|
||||
const seenPartitions = new Set<string>([PASEO_BROWSER_PROFILE_PARTITION]);
|
||||
const extraSessions: BrowserProfileSession[] = [];
|
||||
|
||||
for (const partition of hostPartitions) {
|
||||
if (isHostBrowserProxyPartition(partition) && !seenPartitions.has(partition)) {
|
||||
seenPartitions.add(partition);
|
||||
extraSessions.push(sessions.fromPartition(partition));
|
||||
}
|
||||
}
|
||||
|
||||
// COMPAT(browserProfile): added in v0.1.108; remove after 2027-01-15.
|
||||
for (const browserId of legacyBrowserIds) {
|
||||
const partition = `${PASEO_BROWSER_PROFILE_PARTITION}-${browserId}`;
|
||||
if (!seenPartitions.has(partition)) {
|
||||
seenPartitions.add(partition);
|
||||
extraSessions.push(sessions.fromPartition(partition));
|
||||
}
|
||||
}
|
||||
|
||||
return [localSession, ...extraSessions];
|
||||
return [
|
||||
getPaseoBrowserProfileSession(sessions),
|
||||
// COMPAT(browserProfile): added in v0.1.108; remove after 2027-01-15.
|
||||
...legacyBrowserIds.map((browserId) =>
|
||||
sessions.fromPartition(`${PASEO_BROWSER_PROFILE_PARTITION}-${browserId}`),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
export function getLegacyPaseoBrowserProfileSession(
|
||||
@@ -153,15 +93,11 @@ export function getLegacyPaseoBrowserProfileSession(
|
||||
export function listPaseoBrowserProfileGuests(
|
||||
input: ListBrowserProfileGuestsInput,
|
||||
): BrowserProfileGuest[] {
|
||||
const allowedSessions = new Set<object>(input.profileSessions ?? []);
|
||||
if (input.profileSession) {
|
||||
allowedSessions.add(input.profileSession);
|
||||
}
|
||||
return input.webContents.filter(
|
||||
(contents) =>
|
||||
!contents.isDestroyed() &&
|
||||
(contents.getType() === "webview" || contents.getType() === "window") &&
|
||||
allowedSessions.has(contents.session),
|
||||
contents.session === input.profileSession,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,248 +0,0 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { BrowserWindow, ipcMain, session as electronSession, type WebContents } from "electron";
|
||||
import log from "electron-log/main";
|
||||
import {
|
||||
getHostBrowserProxyPartition,
|
||||
isHostBrowserProxyPartition,
|
||||
PASEO_BROWSER_HOST_PARTITION_PREFIX,
|
||||
} from "./partition.js";
|
||||
import {
|
||||
createBrowserProxyManager,
|
||||
type BrowserProxyManager,
|
||||
type BrowserProxyStatus,
|
||||
type BrowserProxyStatusSnapshot,
|
||||
} from "./internal/proxy-manager.js";
|
||||
import type { BrowserProxyTarget } from "./internal/tunnel-transport.js";
|
||||
|
||||
export {
|
||||
createBrowserProxyManager,
|
||||
getHostBrowserProxyPartition,
|
||||
isHostBrowserProxyPartition,
|
||||
PASEO_BROWSER_HOST_PARTITION_PREFIX,
|
||||
type BrowserProxyManager,
|
||||
type BrowserProxyStatus,
|
||||
type BrowserProxyStatusSnapshot,
|
||||
type BrowserProxyTarget,
|
||||
};
|
||||
|
||||
const TICKET_REQUEST_TIMEOUT_MS = 10_000;
|
||||
export const BROWSER_PROXY_STATUS_EVENT = "paseo:event:browser-proxy-status";
|
||||
export const BROWSER_PROXY_TICKET_REQUEST_EVENT = "paseo:event:browser-proxy-ticket-request";
|
||||
|
||||
interface PendingTicketRequest {
|
||||
readonly serverId: string;
|
||||
readonly expectedResponders: number;
|
||||
failures: number;
|
||||
lastError: string | null;
|
||||
resolve: (ticket: string) => void;
|
||||
reject: (error: Error) => void;
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readNonEmptyString(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function parseDirectTcpTarget(raw: Record<string, unknown>): BrowserProxyTarget | null {
|
||||
const endpoint = readNonEmptyString(raw.endpoint);
|
||||
if (!endpoint) return null;
|
||||
return {
|
||||
type: "directTcp",
|
||||
endpoint,
|
||||
...(typeof raw.useTls === "boolean" ? { useTls: raw.useTls } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function parseRemoteSshTarget(raw: Record<string, unknown>): BrowserProxyTarget | null {
|
||||
const host = readNonEmptyString(raw.host);
|
||||
if (!host) return null;
|
||||
return {
|
||||
type: "remoteSsh",
|
||||
host,
|
||||
...(typeof raw.sshPort === "number" ? { sshPort: raw.sshPort } : {}),
|
||||
...(typeof raw.daemonPort === "number" ? { daemonPort: raw.daemonPort } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function parseRelayTarget(raw: Record<string, unknown>): BrowserProxyTarget | null {
|
||||
const serverId = readNonEmptyString(raw.serverId);
|
||||
const relayEndpoint = readNonEmptyString(raw.relayEndpoint);
|
||||
const daemonPublicKeyB64 = readNonEmptyString(raw.daemonPublicKeyB64);
|
||||
if (!serverId || !relayEndpoint || !daemonPublicKeyB64) return null;
|
||||
return {
|
||||
type: "relay",
|
||||
serverId,
|
||||
relayEndpoint,
|
||||
...(typeof raw.useTls === "boolean" ? { useTls: raw.useTls } : {}),
|
||||
daemonPublicKeyB64,
|
||||
...(raw.minimumSecurityMode === "protected" ? { minimumSecurityMode: "protected" } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseBrowserProxyTarget(raw: unknown): BrowserProxyTarget | null {
|
||||
if (!isRecord(raw) || typeof raw.type !== "string") {
|
||||
return null;
|
||||
}
|
||||
if (raw.type === "directTcp") return parseDirectTcpTarget(raw);
|
||||
if (raw.type === "remoteSsh") return parseRemoteSshTarget(raw);
|
||||
if (raw.type === "relay") return parseRelayTarget(raw);
|
||||
return null;
|
||||
}
|
||||
|
||||
export function createElectronBrowserProxyController(): {
|
||||
manager: BrowserProxyManager;
|
||||
registerIpc: () => void;
|
||||
dispose: () => Promise<void>;
|
||||
} {
|
||||
const pendingTicketRequests = new Map<string, PendingTicketRequest>();
|
||||
|
||||
const requestTicketFromRenderer = (serverId: string): Promise<string> => {
|
||||
const windows = BrowserWindow.getAllWindows().filter((win) => !win.isDestroyed());
|
||||
if (windows.length === 0) {
|
||||
return Promise.reject(new Error("No desktop window is available to mint a tunnel ticket"));
|
||||
}
|
||||
|
||||
const requestId = randomUUID();
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
const pending = pendingTicketRequests.get(requestId);
|
||||
if (!pending) return;
|
||||
pendingTicketRequests.delete(requestId);
|
||||
reject(new Error(pending.lastError ?? "Timed out requesting network tunnel ticket"));
|
||||
}, TICKET_REQUEST_TIMEOUT_MS);
|
||||
timer.unref?.();
|
||||
|
||||
pendingTicketRequests.set(requestId, {
|
||||
serverId,
|
||||
expectedResponders: windows.length,
|
||||
failures: 0,
|
||||
lastError: null,
|
||||
resolve,
|
||||
reject,
|
||||
timer,
|
||||
});
|
||||
|
||||
for (const win of windows) {
|
||||
try {
|
||||
win.webContents.send(BROWSER_PROXY_TICKET_REQUEST_EVENT, { requestId, serverId });
|
||||
} catch {
|
||||
// Ignore destroyed windows
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const broadcastStatus = (status: BrowserProxyStatusSnapshot): void => {
|
||||
for (const win of BrowserWindow.getAllWindows()) {
|
||||
if (win.isDestroyed()) continue;
|
||||
try {
|
||||
win.webContents.send(BROWSER_PROXY_STATUS_EVENT, status);
|
||||
} catch {
|
||||
// Ignore destroyed renderer
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const manager = createBrowserProxyManager({
|
||||
requestTicket: requestTicketFromRenderer,
|
||||
getSessionForPartition: (partition) => electronSession.fromPartition(partition),
|
||||
onStatusChange: broadcastStatus,
|
||||
log: {
|
||||
info: (message, details) => log.info(message, details),
|
||||
warn: (message, details) => log.warn(message, details),
|
||||
},
|
||||
});
|
||||
|
||||
const registerIpc = (): void => {
|
||||
ipcMain.handle("paseo:browser-proxy:ensure-host", async (_event, rawInput: unknown) => {
|
||||
if (!isRecord(rawInput) || typeof rawInput.serverId !== "string") {
|
||||
throw new Error("Invalid browser proxy ensure input");
|
||||
}
|
||||
const target = parseBrowserProxyTarget(rawInput.target);
|
||||
if (!target) {
|
||||
throw new Error("Invalid browser proxy target");
|
||||
}
|
||||
return await manager.ensureHostProxy({
|
||||
serverId: rawInput.serverId,
|
||||
target,
|
||||
forceReconnect: rawInput.forceReconnect === true,
|
||||
});
|
||||
});
|
||||
|
||||
ipcMain.handle("paseo:browser-proxy:update-target", (_event, rawInput: unknown) => {
|
||||
if (!isRecord(rawInput) || typeof rawInput.serverId !== "string") {
|
||||
return;
|
||||
}
|
||||
const target = parseBrowserProxyTarget(rawInput.target);
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
manager.updateHostProxyTarget({ serverId: rawInput.serverId, target });
|
||||
});
|
||||
|
||||
ipcMain.handle("paseo:browser-proxy:get-status", (_event, serverId: unknown) => {
|
||||
if (typeof serverId !== "string" || serverId.trim().length === 0) {
|
||||
return null;
|
||||
}
|
||||
return manager.getHostProxyStatus(serverId);
|
||||
});
|
||||
|
||||
ipcMain.handle("paseo:browser-proxy:release-host", async (_event, serverId: unknown) => {
|
||||
if (typeof serverId !== "string" || serverId.trim().length === 0) {
|
||||
return;
|
||||
}
|
||||
await manager.releaseHostProxy(serverId);
|
||||
});
|
||||
|
||||
ipcMain.handle("paseo:browser-proxy:deliver-ticket", (_event, rawInput: unknown) => {
|
||||
if (!isRecord(rawInput) || typeof rawInput.requestId !== "string") {
|
||||
return;
|
||||
}
|
||||
const pending = pendingTicketRequests.get(rawInput.requestId);
|
||||
if (!pending) {
|
||||
return;
|
||||
}
|
||||
if (typeof rawInput.ticket === "string" && rawInput.ticket.trim().length > 0) {
|
||||
clearTimeout(pending.timer);
|
||||
pendingTicketRequests.delete(rawInput.requestId);
|
||||
pending.resolve(rawInput.ticket.trim());
|
||||
return;
|
||||
}
|
||||
pending.failures += 1;
|
||||
if (typeof rawInput.error === "string" && rawInput.error.trim().length > 0) {
|
||||
pending.lastError = rawInput.error.trim();
|
||||
}
|
||||
if (pending.failures >= pending.expectedResponders) {
|
||||
clearTimeout(pending.timer);
|
||||
pendingTicketRequests.delete(rawInput.requestId);
|
||||
pending.reject(new Error(pending.lastError ?? "Unable to mint network tunnel ticket"));
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const dispose = async (): Promise<void> => {
|
||||
for (const [requestId, pending] of pendingTicketRequests) {
|
||||
clearTimeout(pending.timer);
|
||||
pendingTicketRequests.delete(requestId);
|
||||
pending.reject(new Error("Browser proxy shutting down"));
|
||||
}
|
||||
await manager.disposeAll();
|
||||
};
|
||||
|
||||
return { manager, registerIpc, dispose };
|
||||
}
|
||||
|
||||
export function applyProxiedWebContentsPolicy(
|
||||
contents: Pick<WebContents, "session" | "setWebRTCIPHandlingPolicy">,
|
||||
manager: Pick<BrowserProxyManager, "isProxiedSession">,
|
||||
): void {
|
||||
if (manager.isProxiedSession(contents.session)) {
|
||||
contents.setWebRTCIPHandlingPolicy("disable_non_proxied_udp");
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
getHostBrowserProxyPartition,
|
||||
isHostBrowserProxyPartition,
|
||||
PASEO_BROWSER_HOST_PARTITION_PREFIX,
|
||||
} from "./partition.js";
|
||||
|
||||
describe("host browser proxy partition naming", () => {
|
||||
test("produces deterministic 16-hex-char persistent partitions per serverId", () => {
|
||||
const first = getHostBrowserProxyPartition("srv_alpha_123");
|
||||
const second = getHostBrowserProxyPartition("srv_alpha_123");
|
||||
const other = getHostBrowserProxyPartition("srv_beta_456");
|
||||
|
||||
expect(first).toBe(second);
|
||||
expect(first).not.toBe(other);
|
||||
expect(first.startsWith(PASEO_BROWSER_HOST_PARTITION_PREFIX)).toBe(true);
|
||||
expect(first).toMatch(/^persist:paseo-browser-host-[0-9a-f]{16}$/);
|
||||
expect(isHostBrowserProxyPartition(first)).toBe(true);
|
||||
expect(isHostBrowserProxyPartition(other)).toBe(true);
|
||||
});
|
||||
|
||||
test("validates only exact host proxy partition format", () => {
|
||||
expect(isHostBrowserProxyPartition("persist:paseo-browser-host-0123456789abcdef")).toBe(true);
|
||||
expect(isHostBrowserProxyPartition("persist:paseo-browser")).toBe(false);
|
||||
expect(isHostBrowserProxyPartition("persist:paseo-browser-host-0123456789abcde")).toBe(false);
|
||||
expect(isHostBrowserProxyPartition("persist:paseo-browser-host-0123456789abcdef0")).toBe(false);
|
||||
expect(isHostBrowserProxyPartition("persist:paseo-browser-host-0123456789ABCDEF")).toBe(false);
|
||||
expect(isHostBrowserProxyPartition("persist:paseo-browser-host-zzzzzzzzzzzzzzzz")).toBe(false);
|
||||
expect(isHostBrowserProxyPartition("persist:foreign")).toBe(false);
|
||||
expect(isHostBrowserProxyPartition(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,18 +0,0 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
export const PASEO_BROWSER_HOST_PARTITION_PREFIX = "persist:paseo-browser-host-";
|
||||
|
||||
const HOST_PARTITION_PATTERN = /^persist:paseo-browser-host-[0-9a-f]{16}$/;
|
||||
|
||||
export function getHostBrowserProxyPartition(serverId: string): string {
|
||||
const normalized = serverId.trim();
|
||||
if (!normalized) {
|
||||
throw new Error("Host serverId is required to derive a browser proxy partition");
|
||||
}
|
||||
const digest = createHash("sha256").update(normalized, "utf8").digest("hex").slice(0, 16);
|
||||
return `${PASEO_BROWSER_HOST_PARTITION_PREFIX}${digest}`;
|
||||
}
|
||||
|
||||
export function isHostBrowserProxyPartition(partition: string | undefined): partition is string {
|
||||
return typeof partition === "string" && HOST_PARTITION_PATTERN.test(partition);
|
||||
}
|
||||
@@ -1,365 +0,0 @@
|
||||
import net from "node:net";
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
import {
|
||||
decodeNetworkTunnelFrame,
|
||||
encodeNetworkTunnelFrame,
|
||||
type DecodedNetworkTunnelFrame,
|
||||
type NetworkTunnelFrame,
|
||||
} from "@getpaseo/protocol/network-tunnel";
|
||||
import { getHostBrowserProxyPartition } from "./partition.js";
|
||||
import {
|
||||
createBrowserProxyManager,
|
||||
type BrowserProxyManager,
|
||||
type BrowserProxySessionLike,
|
||||
type BrowserProxyStatusSnapshot,
|
||||
} from "./proxy-manager.js";
|
||||
import type { BrowserProxyTarget, TunnelWireConnection } from "./tunnel-transport.js";
|
||||
|
||||
function createFakeSession(resolveProxyResult?: (url: string, proxyRules: string) => string) {
|
||||
const sessionObj: BrowserProxySessionLike & {
|
||||
lastProxyConfig: Parameters<BrowserProxySessionLike["setProxy"]>[0] | null;
|
||||
closeAllConnectionsCalls: number;
|
||||
resolvedUrls: string[];
|
||||
} = {
|
||||
lastProxyConfig: null,
|
||||
closeAllConnectionsCalls: 0,
|
||||
resolvedUrls: [],
|
||||
setProxy: async (config) => {
|
||||
sessionObj.lastProxyConfig = config;
|
||||
},
|
||||
closeAllConnections: async () => {
|
||||
sessionObj.closeAllConnectionsCalls += 1;
|
||||
},
|
||||
resolveProxy: async (url) => {
|
||||
sessionObj.resolvedUrls.push(url);
|
||||
const rules = sessionObj.lastProxyConfig?.proxyRules ?? "";
|
||||
if (resolveProxyResult) {
|
||||
return resolveProxyResult(url, rules);
|
||||
}
|
||||
const match = rules.match(/^socks5:\/\/(127\.0\.0\.1:\d+)$/);
|
||||
return match ? `SOCKS5 ${match[1]}` : "DIRECT";
|
||||
},
|
||||
};
|
||||
return sessionObj;
|
||||
}
|
||||
|
||||
function createEchoTunnelWire() {
|
||||
const binaryListeners = new Set<(bytes: Uint8Array) => void>();
|
||||
const closeListeners = new Set<(error?: Error) => void>();
|
||||
const openedTargets: Array<{ host: string; port: number }> = [];
|
||||
let closed = false;
|
||||
|
||||
const emit = (frame: NetworkTunnelFrame) => {
|
||||
const encoded = encodeNetworkTunnelFrame(frame);
|
||||
for (const listener of binaryListeners) listener(encoded);
|
||||
};
|
||||
|
||||
const wire: TunnelWireConnection = {
|
||||
ready: {
|
||||
maxFramePayloadBytes: 64 * 1024,
|
||||
initialStreamWindowBytes: 512 * 1024,
|
||||
initialConnectionWindowBytes: 4 * 1024 * 1024,
|
||||
},
|
||||
sendBinary: async (bytes) => {
|
||||
if (closed) throw new Error("Wire closed");
|
||||
const frame: DecodedNetworkTunnelFrame = decodeNetworkTunnelFrame(bytes);
|
||||
if (frame.type === "open") {
|
||||
openedTargets.push({ host: frame.host, port: frame.port });
|
||||
queueMicrotask(() => {
|
||||
emit({ type: "opened", streamId: frame.streamId, initialWindowBytes: 512 * 1024 });
|
||||
});
|
||||
} else if (frame.type === "data") {
|
||||
queueMicrotask(() => {
|
||||
emit({
|
||||
type: "data",
|
||||
streamId: frame.streamId,
|
||||
data: Buffer.concat([Buffer.from("ECHO:"), Buffer.from(frame.data)]),
|
||||
});
|
||||
});
|
||||
} else if (frame.type === "half_close") {
|
||||
queueMicrotask(() => {
|
||||
emit({ type: "half_close", streamId: frame.streamId });
|
||||
});
|
||||
}
|
||||
},
|
||||
onBinary: (handler) => {
|
||||
binaryListeners.add(handler);
|
||||
return () => binaryListeners.delete(handler);
|
||||
},
|
||||
onClose: (handler) => {
|
||||
closeListeners.add(handler);
|
||||
return () => closeListeners.delete(handler);
|
||||
},
|
||||
close: () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
for (const listener of closeListeners) listener();
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
wire,
|
||||
openedTargets,
|
||||
drop: () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
for (const listener of closeListeners) listener(new Error("dropped"));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function socks5ConnectAndExchange(
|
||||
socksPort: number,
|
||||
targetHost: string,
|
||||
targetPort: number,
|
||||
payload: string,
|
||||
): Promise<string> {
|
||||
return await new Promise<string>((resolve, reject) => {
|
||||
const socket = net.createConnection({ host: "127.0.0.1", port: socksPort });
|
||||
let stage: "method" | "connect" | "data" = "method";
|
||||
let buffer = Buffer.alloc(0);
|
||||
const received: Buffer[] = [];
|
||||
|
||||
socket.once("error", reject);
|
||||
socket.once("connect", () => {
|
||||
socket.write(Buffer.from([0x05, 0x01, 0x00]));
|
||||
});
|
||||
socket.on("data", (chunk: Buffer) => {
|
||||
if (stage === "data") {
|
||||
received.push(chunk);
|
||||
return;
|
||||
}
|
||||
buffer = Buffer.concat([buffer, chunk]);
|
||||
if (stage === "method" && buffer.length >= 2) {
|
||||
if (buffer[0] !== 0x05 || buffer[1] !== 0x00) {
|
||||
socket.destroy();
|
||||
reject(new Error(`Unexpected method reply: ${buffer.subarray(0, 2).toString("hex")}`));
|
||||
return;
|
||||
}
|
||||
buffer = buffer.subarray(2);
|
||||
stage = "connect";
|
||||
const hostBuf = Buffer.from(targetHost, "utf8");
|
||||
const portBuf = Buffer.alloc(2);
|
||||
portBuf.writeUInt16BE(targetPort, 0);
|
||||
socket.write(
|
||||
Buffer.concat([Buffer.from([0x05, 0x01, 0x00, 0x03, hostBuf.length]), hostBuf, portBuf]),
|
||||
);
|
||||
}
|
||||
if (stage === "connect" && buffer.length >= 10) {
|
||||
if (buffer[1] !== 0x00) {
|
||||
socket.destroy();
|
||||
reject(new Error(`SOCKS5 CONNECT failed with code ${buffer[1]}`));
|
||||
return;
|
||||
}
|
||||
const extra = buffer.subarray(10);
|
||||
if (extra.length > 0) received.push(extra);
|
||||
buffer = Buffer.alloc(0);
|
||||
stage = "data";
|
||||
socket.end(Buffer.from(payload, "utf8"));
|
||||
}
|
||||
});
|
||||
socket.once("end", () => {
|
||||
resolve(Buffer.concat(received).toString("utf8"));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
describe("BrowserProxyManager", () => {
|
||||
const managers: BrowserProxyManager[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
while (managers.length > 0) {
|
||||
await managers.pop()!.disposeAll();
|
||||
}
|
||||
});
|
||||
|
||||
test("configures fixed-port SOCKS5 + session proxy, verifies resolveProxy, and keeps the same port across tunnel reconnect", async () => {
|
||||
const sessionsByPartition = new Map<string, ReturnType<typeof createFakeSession>>();
|
||||
const wires: Array<ReturnType<typeof createEchoTunnelWire>> = [];
|
||||
const requestedTickets: string[] = [];
|
||||
const statuses: BrowserProxyStatusSnapshot[] = [];
|
||||
|
||||
const manager = createBrowserProxyManager({
|
||||
verifySocketOwner: async () => true,
|
||||
requestTicket: async (serverId) => {
|
||||
requestedTickets.push(serverId);
|
||||
return `ticket-${requestedTickets.length}`;
|
||||
},
|
||||
openTunnelWire: async () => {
|
||||
const created = createEchoTunnelWire();
|
||||
wires.push(created);
|
||||
return created.wire;
|
||||
},
|
||||
getSessionForPartition: (partition) => {
|
||||
let session = sessionsByPartition.get(partition);
|
||||
if (!session) {
|
||||
session = createFakeSession();
|
||||
sessionsByPartition.set(partition, session);
|
||||
}
|
||||
return session;
|
||||
},
|
||||
onStatusChange: (status) => statuses.push(status),
|
||||
});
|
||||
managers.push(manager);
|
||||
|
||||
const target: BrowserProxyTarget = { type: "directTcp", endpoint: "10.0.0.5:6767" };
|
||||
const ready = await manager.ensureHostProxy({ serverId: "remote-1", target });
|
||||
const expectedPartition = getHostBrowserProxyPartition("remote-1");
|
||||
|
||||
expect(ready.status).toBe("ready");
|
||||
expect(ready.partition).toBe(expectedPartition);
|
||||
expect(ready.socksPort).toBeGreaterThan(0);
|
||||
expect(manager.isAllowedHostPartition(expectedPartition)).toBe(true);
|
||||
expect(manager.isProxiedSession(sessionsByPartition.get(expectedPartition)!)).toBe(true);
|
||||
|
||||
const session = sessionsByPartition.get(expectedPartition)!;
|
||||
expect(session.lastProxyConfig).toEqual({
|
||||
mode: "fixed_servers",
|
||||
proxyRules: `socks5://127.0.0.1:${ready.socksPort}`,
|
||||
proxyBypassRules: "<-loopback>",
|
||||
});
|
||||
expect(session.closeAllConnectionsCalls).toBe(1);
|
||||
expect(session.resolvedUrls).toContain("http://localhost:80/");
|
||||
expect(session.resolvedUrls).toContain("http://127.0.0.1:80/");
|
||||
|
||||
// First SOCKS5 connection goes through wire 1
|
||||
const firstReply = await socks5ConnectAndExchange(ready.socksPort!, "localhost", 5173, "hello");
|
||||
expect(firstReply).toBe("ECHO:hello");
|
||||
expect(wires).toHaveLength(1);
|
||||
expect(wires[0]!.openedTargets).toEqual([{ host: "localhost", port: 5173 }]);
|
||||
|
||||
// Drop wire 1 -> status becomes reconnecting, SOCKS5 port stays fixed!
|
||||
wires[0]!.drop();
|
||||
expect(manager.getHostProxyStatus("remote-1")?.status).toBe("reconnecting");
|
||||
expect(manager.getHostProxyStatus("remote-1")?.socksPort).toBe(ready.socksPort);
|
||||
|
||||
// Next SOCKS5 connection on the SAME fixed port transparently reconnects with a fresh ticket!
|
||||
const secondReply = await socks5ConnectAndExchange(
|
||||
ready.socksPort!,
|
||||
"app.localhost",
|
||||
6767,
|
||||
"again",
|
||||
);
|
||||
expect(secondReply).toBe("ECHO:again");
|
||||
expect(wires).toHaveLength(2);
|
||||
expect(requestedTickets).toEqual(["remote-1", "remote-1"]);
|
||||
expect(manager.getHostProxyStatus("remote-1")?.status).toBe("ready");
|
||||
expect(manager.getHostProxyStatus("remote-1")?.socksPort).toBe(ready.socksPort);
|
||||
expect(statuses.some((s) => s.status === "reconnecting")).toBe(true);
|
||||
});
|
||||
|
||||
test("rejects SOCKS5 connections from unauthorized OS socket owners before handshake", async () => {
|
||||
const wire = createEchoTunnelWire();
|
||||
const session = createFakeSession();
|
||||
const manager = createBrowserProxyManager({
|
||||
verifySocketOwner: async () => false,
|
||||
requestTicket: async () => "ticket-1",
|
||||
openTunnelWire: async () => wire.wire,
|
||||
getSessionForPartition: () => session,
|
||||
});
|
||||
managers.push(manager);
|
||||
|
||||
const ready = await manager.ensureHostProxy({
|
||||
serverId: "remote-owner-check",
|
||||
target: { type: "directTcp", endpoint: "10.0.0.9:6767" },
|
||||
});
|
||||
|
||||
const outcome = await new Promise<"closed_without_data" | "received_data">((resolve) => {
|
||||
const socket = net.createConnection({ host: "127.0.0.1", port: ready.socksPort! });
|
||||
let sawData = false;
|
||||
socket.on("data", () => {
|
||||
sawData = true;
|
||||
});
|
||||
socket.once("connect", () => {
|
||||
socket.write(Buffer.from([0x05, 0x01, 0x00]));
|
||||
});
|
||||
socket.once("close", () => {
|
||||
resolve(sawData ? "received_data" : "closed_without_data");
|
||||
});
|
||||
socket.once("error", () => {
|
||||
// ECONNRESET after server destroys socket is expected
|
||||
});
|
||||
});
|
||||
|
||||
expect(outcome).toBe("closed_without_data");
|
||||
expect(wire.openedTargets).toEqual([]);
|
||||
});
|
||||
|
||||
test("fails closed when session.resolveProxy does not confirm the SOCKS5 proxy for loopback", async () => {
|
||||
const wire = createEchoTunnelWire();
|
||||
const brokenSession = createFakeSession(() => "DIRECT");
|
||||
const manager = createBrowserProxyManager({
|
||||
verifySocketOwner: async () => true,
|
||||
requestTicket: async () => "ticket-1",
|
||||
openTunnelWire: async () => wire.wire,
|
||||
getSessionForPartition: () => brokenSession,
|
||||
});
|
||||
managers.push(manager);
|
||||
|
||||
const result = await manager.ensureHostProxy({
|
||||
serverId: "remote-broken-proxy",
|
||||
target: { type: "directTcp", endpoint: "10.0.0.10:6767" },
|
||||
});
|
||||
|
||||
expect(result.status).toBe("error");
|
||||
expect(result.socksPort).toBeNull();
|
||||
expect(result.error).toMatch(/resolveProxy|proxy/i);
|
||||
expect(manager.isAllowedHostPartition(result.partition)).toBe(false);
|
||||
});
|
||||
|
||||
test("keeps socksPort null on initial tunnel failure, and preserves socksPort across later reconnect errors", async () => {
|
||||
const session = createFakeSession();
|
||||
let wireCalls = 0;
|
||||
let failTicket = true;
|
||||
const wires: Array<ReturnType<typeof createEchoTunnelWire>> = [];
|
||||
|
||||
const manager = createBrowserProxyManager({
|
||||
verifySocketOwner: async () => true,
|
||||
requestTicket: async () => {
|
||||
if (failTicket) {
|
||||
throw new Error("host disconnected");
|
||||
}
|
||||
return `ticket-${wireCalls + 1}`;
|
||||
},
|
||||
openTunnelWire: async () => {
|
||||
wireCalls += 1;
|
||||
const created = createEchoTunnelWire();
|
||||
wires.push(created);
|
||||
return created.wire;
|
||||
},
|
||||
getSessionForPartition: () => session,
|
||||
});
|
||||
managers.push(manager);
|
||||
|
||||
const target: BrowserProxyTarget = { type: "directTcp", endpoint: "10.0.0.11:6767" };
|
||||
const initialFail = await manager.ensureHostProxy({ serverId: "remote-flaky", target });
|
||||
expect(initialFail.status).toBe("error");
|
||||
expect(initialFail.socksPort).toBeNull();
|
||||
expect(manager.isAllowedHostPartition(initialFail.partition)).toBe(false);
|
||||
|
||||
failTicket = false;
|
||||
const ready = await manager.ensureHostProxy({ serverId: "remote-flaky", target });
|
||||
expect(ready.status).toBe("ready");
|
||||
expect(ready.socksPort).toBeGreaterThan(0);
|
||||
|
||||
// Simulate outage + background page poll (e.g. HMR) failing tunnel reconnect.
|
||||
failTicket = true;
|
||||
wires[0]!.drop();
|
||||
await expect(
|
||||
socks5ConnectAndExchange(ready.socksPort!, "localhost", 5173, "hmr-poll"),
|
||||
).rejects.toThrow(/SOCKS5 CONNECT failed/);
|
||||
const afterPollError = manager.getHostProxyStatus("remote-flaky");
|
||||
expect(afterPollError?.status).toBe("error");
|
||||
expect(afterPollError?.socksPort).toBe(ready.socksPort);
|
||||
|
||||
// Host recovers -> next ensureHostProxy brings the same fixed port back to ready.
|
||||
failTicket = false;
|
||||
const recovered = await manager.ensureHostProxy({
|
||||
serverId: "remote-flaky",
|
||||
target,
|
||||
forceReconnect: true,
|
||||
});
|
||||
expect(recovered.status).toBe("ready");
|
||||
expect(recovered.socksPort).toBe(ready.socksPort);
|
||||
});
|
||||
});
|
||||
@@ -1,529 +0,0 @@
|
||||
import net, { type AddressInfo, type Server, type Socket } from "node:net";
|
||||
import { getHostBrowserProxyPartition, isHostBrowserProxyPartition } from "./partition.js";
|
||||
import { createOsSocketOwnerVerifier, type SocketOwnerVerifier } from "./socket-owner.js";
|
||||
import {
|
||||
performSocks5Handshake,
|
||||
Socks5Error,
|
||||
Socks5ReplyCode,
|
||||
socks5ReplyForTunnelCloseReason,
|
||||
writeSocks5Reply,
|
||||
} from "./socks5.js";
|
||||
import { TunnelMuxClient } from "./tunnel-mux.js";
|
||||
import {
|
||||
openTunnelWireConnection,
|
||||
type BrowserProxyTarget,
|
||||
type TunnelWireConnection,
|
||||
} from "./tunnel-transport.js";
|
||||
|
||||
export type BrowserProxyStatus = "idle" | "connecting" | "ready" | "reconnecting" | "error";
|
||||
|
||||
export interface BrowserProxyStatusSnapshot {
|
||||
serverId: string;
|
||||
partition: string;
|
||||
status: BrowserProxyStatus;
|
||||
error: string | null;
|
||||
socksPort: number | null;
|
||||
}
|
||||
|
||||
export interface BrowserProxySessionLike {
|
||||
setProxy(config: {
|
||||
mode: "fixed_servers";
|
||||
proxyRules: string;
|
||||
proxyBypassRules: string;
|
||||
}): Promise<void>;
|
||||
closeAllConnections(): Promise<void>;
|
||||
resolveProxy(url: string): Promise<string>;
|
||||
}
|
||||
|
||||
export interface BrowserProxyManagerDeps {
|
||||
requestTicket: (serverId: string) => Promise<string>;
|
||||
getSessionForPartition: (partition: string) => BrowserProxySessionLike;
|
||||
verifySocketOwner?: SocketOwnerVerifier;
|
||||
openTunnelWire?: (input: {
|
||||
target: BrowserProxyTarget;
|
||||
ticket: string;
|
||||
}) => Promise<TunnelWireConnection>;
|
||||
onStatusChange?: (status: BrowserProxyStatusSnapshot) => void;
|
||||
log?: {
|
||||
info: (message: string, details?: Record<string, unknown>) => void;
|
||||
warn: (message: string, details?: Record<string, unknown>) => void;
|
||||
};
|
||||
}
|
||||
|
||||
export interface EnsureHostProxyInput {
|
||||
serverId: string;
|
||||
target: BrowserProxyTarget;
|
||||
forceReconnect?: boolean;
|
||||
}
|
||||
|
||||
export interface BrowserProxyManager {
|
||||
ensureHostProxy(input: EnsureHostProxyInput): Promise<BrowserProxyStatusSnapshot>;
|
||||
updateHostProxyTarget(input: { serverId: string; target: BrowserProxyTarget }): void;
|
||||
getHostProxyStatus(serverId: string): BrowserProxyStatusSnapshot | null;
|
||||
isAllowedHostPartition(partition: string): boolean;
|
||||
isProxiedSession(session: object): boolean;
|
||||
listKnownPartitions(): string[];
|
||||
releaseHostProxy(serverId: string): Promise<void>;
|
||||
disposeAll(): Promise<void>;
|
||||
}
|
||||
|
||||
interface HostProxyEntry {
|
||||
readonly serverId: string;
|
||||
readonly partition: string;
|
||||
target: BrowserProxyTarget;
|
||||
status: BrowserProxyStatus;
|
||||
error: string | null;
|
||||
socksServer: Server | null;
|
||||
socksPort: number | null;
|
||||
session: BrowserProxySessionLike | null;
|
||||
sessionConfigured: boolean;
|
||||
mux: TunnelMuxClient | null;
|
||||
connectPromise: Promise<TunnelMuxClient> | null;
|
||||
ensurePromise: Promise<BrowserProxyStatusSnapshot> | null;
|
||||
activeSockets: Set<Socket>;
|
||||
disposed: boolean;
|
||||
}
|
||||
|
||||
function isLoopbackRemoteAddress(address: string | undefined): boolean {
|
||||
return address === "127.0.0.1" || address === "::ffff:127.0.0.1";
|
||||
}
|
||||
|
||||
function targetsEqual(left: BrowserProxyTarget, right: BrowserProxyTarget): boolean {
|
||||
if (left.type !== right.type) return false;
|
||||
if (left.type === "directTcp" && right.type === "directTcp") {
|
||||
return left.endpoint === right.endpoint && (left.useTls ?? false) === (right.useTls ?? false);
|
||||
}
|
||||
if (left.type === "remoteSsh" && right.type === "remoteSsh") {
|
||||
return (
|
||||
left.host === right.host &&
|
||||
left.sshPort === right.sshPort &&
|
||||
left.daemonPort === right.daemonPort
|
||||
);
|
||||
}
|
||||
if (left.type === "relay" && right.type === "relay") {
|
||||
return (
|
||||
left.serverId === right.serverId &&
|
||||
left.relayEndpoint === right.relayEndpoint &&
|
||||
(left.useTls ?? false) === (right.useTls ?? false) &&
|
||||
left.daemonPublicKeyB64 === right.daemonPublicKeyB64 &&
|
||||
left.minimumSecurityMode === right.minimumSecurityMode
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function formatError(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function isExpectedResolvedProxy(resolved: string, socksPort: number): boolean {
|
||||
const normalized = resolved.trim().toUpperCase();
|
||||
const expected = `SOCKS5 127.0.0.1:${socksPort}`;
|
||||
return normalized.includes(expected);
|
||||
}
|
||||
|
||||
export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): BrowserProxyManager {
|
||||
const verifySocketOwner = deps.verifySocketOwner ?? createOsSocketOwnerVerifier();
|
||||
const openTunnelWire =
|
||||
deps.openTunnelWire ??
|
||||
((input) => openTunnelWireConnection({ target: input.target, ticket: input.ticket }));
|
||||
|
||||
const entriesByServerId = new Map<string, HostProxyEntry>();
|
||||
const allowedPartitions = new Set<string>();
|
||||
const knownPartitions = new Set<string>();
|
||||
const proxiedSessions = new WeakSet<object>();
|
||||
|
||||
function snapshotOf(entry: HostProxyEntry): BrowserProxyStatusSnapshot {
|
||||
return {
|
||||
serverId: entry.serverId,
|
||||
partition: entry.partition,
|
||||
status: entry.status,
|
||||
error: entry.error,
|
||||
// Only expose socksPort once Chromium's session proxy has been configured and
|
||||
// verified via resolveProxy so renderers never mount an unverified partition.
|
||||
socksPort: entry.sessionConfigured ? entry.socksPort : null,
|
||||
};
|
||||
}
|
||||
|
||||
function setEntryStatus(
|
||||
entry: HostProxyEntry,
|
||||
status: BrowserProxyStatus,
|
||||
error: string | null = null,
|
||||
): void {
|
||||
if (entry.status === status && entry.error === error) {
|
||||
return;
|
||||
}
|
||||
entry.status = status;
|
||||
entry.error = error;
|
||||
deps.onStatusChange?.(snapshotOf(entry));
|
||||
}
|
||||
|
||||
async function ensureSocksServer(entry: HostProxyEntry): Promise<number> {
|
||||
if (entry.socksServer && entry.socksPort !== null) {
|
||||
return entry.socksPort;
|
||||
}
|
||||
|
||||
const server = net.createServer((socket) => {
|
||||
void handleAcceptedSocksSocket(entry, socket);
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
server.off("error", reject);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
const address = server.address() as AddressInfo | null;
|
||||
if (!address || typeof address === "string" || address.port <= 0) {
|
||||
server.close();
|
||||
throw new Error("Failed to bind local loopback SOCKS5 port");
|
||||
}
|
||||
|
||||
entry.socksServer = server;
|
||||
entry.socksPort = address.port;
|
||||
server.on("error", (error) => {
|
||||
deps.log?.warn("[browser-proxy] socks5 server error", {
|
||||
serverId: entry.serverId,
|
||||
error: formatError(error),
|
||||
});
|
||||
});
|
||||
|
||||
return address.port;
|
||||
}
|
||||
|
||||
async function ensureSessionConfigured(entry: HostProxyEntry, socksPort: number): Promise<void> {
|
||||
if (entry.sessionConfigured && entry.session) {
|
||||
return;
|
||||
}
|
||||
|
||||
const hostSession = deps.getSessionForPartition(entry.partition);
|
||||
await hostSession.setProxy({
|
||||
mode: "fixed_servers",
|
||||
proxyRules: `socks5://127.0.0.1:${socksPort}`,
|
||||
proxyBypassRules: "<-loopback>",
|
||||
});
|
||||
await hostSession.closeAllConnections();
|
||||
|
||||
// Verify that both hostname loopback and IP loopback actually resolve to our SOCKS5 proxy.
|
||||
const [resolvedLocalhost, resolvedLoopbackIp] = await Promise.all([
|
||||
hostSession.resolveProxy("http://localhost:80/"),
|
||||
hostSession.resolveProxy("http://127.0.0.1:80/"),
|
||||
]);
|
||||
|
||||
if (
|
||||
!isExpectedResolvedProxy(resolvedLocalhost, socksPort) ||
|
||||
!isExpectedResolvedProxy(resolvedLoopbackIp, socksPort)
|
||||
) {
|
||||
throw new Error(
|
||||
`Session resolveProxy verification failed (localhost="${resolvedLocalhost}", 127.0.0.1="${resolvedLoopbackIp}")`,
|
||||
);
|
||||
}
|
||||
|
||||
entry.session = hostSession;
|
||||
entry.sessionConfigured = true;
|
||||
allowedPartitions.add(entry.partition);
|
||||
knownPartitions.add(entry.partition);
|
||||
proxiedSessions.add(hostSession);
|
||||
}
|
||||
|
||||
async function ensureTunnelConnected(entry: HostProxyEntry): Promise<TunnelMuxClient> {
|
||||
if (entry.disposed) {
|
||||
throw new Error("Host browser proxy was disposed");
|
||||
}
|
||||
if (entry.mux && !entry.mux.isClosed()) {
|
||||
return entry.mux;
|
||||
}
|
||||
if (entry.connectPromise) {
|
||||
return await entry.connectPromise;
|
||||
}
|
||||
|
||||
const nextStatus: BrowserProxyStatus =
|
||||
entry.sessionConfigured || entry.status === "ready" || entry.status === "reconnecting"
|
||||
? "reconnecting"
|
||||
: "connecting";
|
||||
setEntryStatus(entry, nextStatus, null);
|
||||
|
||||
const connectTask = (async () => {
|
||||
const ticket = await deps.requestTicket(entry.serverId);
|
||||
if (entry.disposed) {
|
||||
throw new Error("Host browser proxy was disposed");
|
||||
}
|
||||
const wire = await openTunnelWire({
|
||||
target: entry.target,
|
||||
ticket,
|
||||
});
|
||||
if (entry.disposed) {
|
||||
wire.close();
|
||||
throw new Error("Host browser proxy was disposed");
|
||||
}
|
||||
|
||||
const mux = new TunnelMuxClient(wire);
|
||||
entry.mux = mux;
|
||||
mux.onClose(() => {
|
||||
if (entry.mux === mux) {
|
||||
entry.mux = null;
|
||||
if (!entry.disposed && entry.sessionConfigured) {
|
||||
setEntryStatus(entry, "reconnecting", null);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (entry.sessionConfigured) {
|
||||
setEntryStatus(entry, "ready", null);
|
||||
}
|
||||
return mux;
|
||||
})();
|
||||
|
||||
entry.connectPromise = connectTask;
|
||||
try {
|
||||
return await connectTask;
|
||||
} catch (error) {
|
||||
if (!entry.disposed) {
|
||||
setEntryStatus(entry, "error", formatError(error));
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
if (entry.connectPromise === connectTask) {
|
||||
entry.connectPromise = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAcceptedSocksSocket(entry: HostProxyEntry, socket: Socket): Promise<void> {
|
||||
socket.pause();
|
||||
entry.activeSockets.add(socket);
|
||||
socket.once("close", () => {
|
||||
entry.activeSockets.delete(socket);
|
||||
});
|
||||
socket.on("error", () => {
|
||||
// Handled by stream/close cleanup.
|
||||
});
|
||||
|
||||
if (entry.disposed || entry.socksPort === null) {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
const clientPort = socket.remotePort;
|
||||
if (!isLoopbackRemoteAddress(socket.remoteAddress) || !clientPort) {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
let ownerAllowed = false;
|
||||
try {
|
||||
ownerAllowed = await verifySocketOwner({
|
||||
clientPort,
|
||||
serverPort: entry.socksPort,
|
||||
});
|
||||
} catch {
|
||||
ownerAllowed = false;
|
||||
}
|
||||
|
||||
if (!ownerAllowed || socket.destroyed || entry.disposed) {
|
||||
deps.log?.warn("[browser-proxy] rejected unauthorized local SOCKS5 connection", {
|
||||
serverId: entry.serverId,
|
||||
remoteAddress: socket.remoteAddress,
|
||||
clientPort,
|
||||
});
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
socket.resume();
|
||||
|
||||
let request: { host: string; port: number; leftover: Buffer };
|
||||
try {
|
||||
request = await performSocks5Handshake(socket);
|
||||
} catch (error) {
|
||||
if (!(error instanceof Socks5Error) || error.replyCode === null) {
|
||||
socket.destroy();
|
||||
} else {
|
||||
socket.end();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let mux: TunnelMuxClient;
|
||||
try {
|
||||
mux = await ensureTunnelConnected(entry);
|
||||
} catch {
|
||||
writeSocks5Reply(socket, Socks5ReplyCode.NetworkUnreachable);
|
||||
socket.end();
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await mux.openStream({
|
||||
host: request.host,
|
||||
port: request.port,
|
||||
socket,
|
||||
initialData: request.leftover,
|
||||
onOpened: () => {
|
||||
writeSocks5Reply(socket, Socks5ReplyCode.Succeeded);
|
||||
},
|
||||
});
|
||||
|
||||
if (!result.ok) {
|
||||
writeSocks5Reply(socket, socks5ReplyForTunnelCloseReason(result.reason));
|
||||
socket.end();
|
||||
}
|
||||
}
|
||||
|
||||
function getOrCreateEntry(serverId: string, target: BrowserProxyTarget): HostProxyEntry {
|
||||
const existing = entriesByServerId.get(serverId);
|
||||
if (existing && !existing.disposed) {
|
||||
if (!targetsEqual(existing.target, target)) {
|
||||
existing.target = target;
|
||||
// Close existing tunnel so the next connect uses the updated target
|
||||
// while keeping the fixed local SOCKS5 port intact!
|
||||
existing.mux?.close();
|
||||
existing.mux = null;
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
|
||||
const partition = getHostBrowserProxyPartition(serverId);
|
||||
knownPartitions.add(partition);
|
||||
const entry: HostProxyEntry = {
|
||||
serverId,
|
||||
partition,
|
||||
target,
|
||||
status: "idle",
|
||||
error: null,
|
||||
socksServer: null,
|
||||
socksPort: null,
|
||||
session: null,
|
||||
sessionConfigured: false,
|
||||
mux: null,
|
||||
connectPromise: null,
|
||||
ensurePromise: null,
|
||||
activeSockets: new Set(),
|
||||
disposed: false,
|
||||
};
|
||||
entriesByServerId.set(serverId, entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
async function ensureHostProxy(input: EnsureHostProxyInput): Promise<BrowserProxyStatusSnapshot> {
|
||||
const serverId = input.serverId.trim();
|
||||
if (!serverId) {
|
||||
throw new Error("Host serverId is required");
|
||||
}
|
||||
|
||||
const entry = getOrCreateEntry(serverId, input.target);
|
||||
if (input.forceReconnect && entry.mux) {
|
||||
entry.mux.close();
|
||||
entry.mux = null;
|
||||
}
|
||||
|
||||
if (entry.ensurePromise) {
|
||||
return await entry.ensurePromise;
|
||||
}
|
||||
|
||||
const ensureTask = (async (): Promise<BrowserProxyStatusSnapshot> => {
|
||||
try {
|
||||
if (entry.status !== "ready") {
|
||||
setEntryStatus(entry, entry.sessionConfigured ? "reconnecting" : "connecting", null);
|
||||
}
|
||||
const socksPort = await ensureSocksServer(entry);
|
||||
await ensureTunnelConnected(entry);
|
||||
await ensureSessionConfigured(entry, socksPort);
|
||||
setEntryStatus(entry, "ready", null);
|
||||
return snapshotOf(entry);
|
||||
} catch (error) {
|
||||
const message = formatError(error);
|
||||
if (!entry.disposed) {
|
||||
setEntryStatus(entry, "error", message);
|
||||
}
|
||||
return snapshotOf(entry);
|
||||
}
|
||||
})();
|
||||
|
||||
entry.ensurePromise = ensureTask;
|
||||
try {
|
||||
return await ensureTask;
|
||||
} finally {
|
||||
if (entry.ensurePromise === ensureTask) {
|
||||
entry.ensurePromise = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function updateHostProxyTarget(input: { serverId: string; target: BrowserProxyTarget }): void {
|
||||
const entry = entriesByServerId.get(input.serverId.trim());
|
||||
if (!entry || entry.disposed) return;
|
||||
if (!targetsEqual(entry.target, input.target)) {
|
||||
entry.target = input.target;
|
||||
entry.mux?.close();
|
||||
entry.mux = null;
|
||||
if (entry.sessionConfigured) {
|
||||
setEntryStatus(entry, "reconnecting", null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getHostProxyStatus(serverId: string): BrowserProxyStatusSnapshot | null {
|
||||
const entry = entriesByServerId.get(serverId.trim());
|
||||
return entry && !entry.disposed ? snapshotOf(entry) : null;
|
||||
}
|
||||
|
||||
function isAllowedHostPartition(partition: string): boolean {
|
||||
return isHostBrowserProxyPartition(partition) && allowedPartitions.has(partition);
|
||||
}
|
||||
|
||||
function isProxiedSession(session: object): boolean {
|
||||
return proxiedSessions.has(session);
|
||||
}
|
||||
|
||||
function listKnownPartitions(): string[] {
|
||||
return [...knownPartitions];
|
||||
}
|
||||
|
||||
async function disposeEntry(entry: HostProxyEntry): Promise<void> {
|
||||
if (entry.disposed) return;
|
||||
entry.disposed = true;
|
||||
entriesByServerId.delete(entry.serverId);
|
||||
allowedPartitions.delete(entry.partition);
|
||||
|
||||
entry.mux?.close();
|
||||
entry.mux = null;
|
||||
|
||||
for (const socket of entry.activeSockets) {
|
||||
socket.destroy();
|
||||
}
|
||||
entry.activeSockets.clear();
|
||||
|
||||
const server = entry.socksServer;
|
||||
entry.socksServer = null;
|
||||
if (server) {
|
||||
await new Promise<void>((resolve) => {
|
||||
server.close(() => resolve());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function releaseHostProxy(serverId: string): Promise<void> {
|
||||
const entry = entriesByServerId.get(serverId.trim());
|
||||
if (!entry) return;
|
||||
await disposeEntry(entry);
|
||||
}
|
||||
|
||||
async function disposeAll(): Promise<void> {
|
||||
const entries = [...entriesByServerId.values()];
|
||||
await Promise.all(entries.map((entry) => disposeEntry(entry)));
|
||||
verifySocketOwner.dispose?.();
|
||||
}
|
||||
|
||||
return {
|
||||
ensureHostProxy,
|
||||
updateHostProxyTarget,
|
||||
getHostProxyStatus,
|
||||
isAllowedHostPartition,
|
||||
isProxiedSession,
|
||||
listKnownPartitions,
|
||||
releaseHostProxy,
|
||||
disposeAll,
|
||||
};
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
createOsSocketOwnerVerifier,
|
||||
findDarwinLoopbackSocketUid,
|
||||
findLinuxLoopbackSocketUid,
|
||||
parseWindowsLoopbackSocketOwner,
|
||||
} from "./socket-owner.js";
|
||||
|
||||
describe("OS loopback socket owner verification", () => {
|
||||
test("parses Linux /proc/net/tcp for matching 127.0.0.1 client->server connection UID", () => {
|
||||
// 127.0.0.1 in little-endian hex is 0100007F.
|
||||
// clientPort = 45678 = 0xB26E, serverPort = 1080 = 0x0438
|
||||
const sample = [
|
||||
" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode",
|
||||
" 0: 0100007F:0438 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 12345 1 0000000000000000 100 0 0 10 0",
|
||||
" 1: 0100007F:B26E 0100007F:0438 01 00000000:00000000 00:00000000 00000000 1001 0 12346 1 0000000000000000 20 4 30 10 -1",
|
||||
" 2: 0100007F:0438 0100007F:B26E 01 00000000:00000000 00:00000000 00000000 1000 0 12347 1 0000000000000000 20 4 30 10 -1",
|
||||
].join("\n");
|
||||
|
||||
expect(findLinuxLoopbackSocketUid(sample, 45678, 1080)).toBe(1001);
|
||||
expect(findLinuxLoopbackSocketUid(sample, 45679, 1080)).toBeNull();
|
||||
});
|
||||
|
||||
test("parses macOS lsof machine-readable output for client UID", () => {
|
||||
const sample = ["p1234", "u501", "f12", "n127.0.0.1:45678->127.0.0.1:1080"].join("\n");
|
||||
expect(findDarwinLoopbackSocketUid(sample, 45678, 1080)).toBe(501);
|
||||
expect(findDarwinLoopbackSocketUid(sample, 45679, 1080)).toBeNull();
|
||||
});
|
||||
|
||||
test("parses Windows PowerShell owner SID output", () => {
|
||||
expect(parseWindowsLoopbackSocketOwner("S-1-5-21-100-200-300-1001\r\n")).toBe(
|
||||
"S-1-5-21-100-200-300-1001",
|
||||
);
|
||||
expect(parseWindowsLoopbackSocketOwner(" \n")).toBeNull();
|
||||
});
|
||||
|
||||
test("admits matching UID and rejects foreign UID or lookup failure on Linux", async () => {
|
||||
const procContent = [
|
||||
" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode",
|
||||
" 1: 0100007F:C350 0100007F:1F90 01 00000000:00000000 00:00000000 00000000 1000 0 12346",
|
||||
" 2: 0100007F:C351 0100007F:1F90 01 00000000:00000000 00:00000000 00000000 2000 0 12347",
|
||||
].join("\n");
|
||||
|
||||
const verify = createOsSocketOwnerVerifier({
|
||||
platform: "linux",
|
||||
getCurrentUid: () => 1000,
|
||||
readFile: async () => procContent,
|
||||
});
|
||||
|
||||
// 0xC350 = 50000, 0xC351 = 50001, 0x1F90 = 8080
|
||||
expect(await verify({ clientPort: 50000, serverPort: 8080 })).toBe(true);
|
||||
expect(await verify({ clientPort: 50001, serverPort: 8080 })).toBe(false);
|
||||
expect(await verify({ clientPort: 50002, serverPort: 8080 })).toBe(false);
|
||||
|
||||
const failingVerify = createOsSocketOwnerVerifier({
|
||||
platform: "linux",
|
||||
getCurrentUid: () => 1000,
|
||||
readFile: async () => {
|
||||
throw new Error("EACCES");
|
||||
},
|
||||
});
|
||||
expect(await failingVerify({ clientPort: 50000, serverPort: 8080 })).toBe(false);
|
||||
});
|
||||
|
||||
test("reuses one persistent worker across lookups on Windows and disposes cleanly", async () => {
|
||||
let workersCreated = 0;
|
||||
let disposedCount = 0;
|
||||
const verify = createOsSocketOwnerVerifier({
|
||||
platform: "win32",
|
||||
createWindowsWorker: () => {
|
||||
workersCreated += 1;
|
||||
return {
|
||||
lookup: async ({ clientPort }) => clientPort === 50000,
|
||||
dispose: () => {
|
||||
disposedCount += 1;
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
expect(await verify({ clientPort: 50000, serverPort: 8080 })).toBe(true);
|
||||
expect(await verify({ clientPort: 50001, serverPort: 8080 })).toBe(false);
|
||||
expect(workersCreated).toBe(1);
|
||||
|
||||
verify.dispose?.();
|
||||
expect(disposedCount).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -1,360 +0,0 @@
|
||||
import {
|
||||
execFile as nodeExecFile,
|
||||
spawn as nodeSpawn,
|
||||
type ChildProcessWithoutNullStreams,
|
||||
} from "node:child_process";
|
||||
import { readFile as nodeReadFile } from "node:fs/promises";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const execFileAsync = promisify(nodeExecFile);
|
||||
|
||||
export interface SocketOwnerCheckInput {
|
||||
clientPort: number;
|
||||
serverPort: number;
|
||||
}
|
||||
|
||||
export interface SocketOwnerVerifier {
|
||||
(input: SocketOwnerCheckInput): Promise<boolean>;
|
||||
dispose?: () => void;
|
||||
}
|
||||
|
||||
export interface WindowsSocketOwnerWorker {
|
||||
lookup: (input: SocketOwnerCheckInput) => Promise<boolean>;
|
||||
dispose: () => void;
|
||||
}
|
||||
|
||||
export interface OsSocketOwnerVerifierDeps {
|
||||
platform?: NodeJS.Platform;
|
||||
getCurrentUid?: () => number | null;
|
||||
readFile?: (filePath: string, encoding: "utf8") => Promise<string>;
|
||||
execFile?: (
|
||||
command: string,
|
||||
args: string[],
|
||||
options?: { timeout?: number; windowsHide?: boolean },
|
||||
) => Promise<{ stdout: string }>;
|
||||
createWindowsWorker?: () => WindowsSocketOwnerWorker;
|
||||
}
|
||||
|
||||
const LINUX_LOOPBACK_IPV4_HEX = "0100007F";
|
||||
const LINUX_LOOPBACK_IPV4_MAPPED_IPV6_HEX = "0000000000000000FFFF00000100007F";
|
||||
const LOOKUP_TIMEOUT_MS = 3_000;
|
||||
const WINDOWS_WORKER_SCRIPT = [
|
||||
"$selfSid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value;",
|
||||
"$cache = @{};",
|
||||
"while (($line = [Console]::In.ReadLine()) -ne $null) {",
|
||||
" $parts = $line.Trim().Split(' ');",
|
||||
" if ($parts.Length -ne 2) { [Console]::Out.WriteLine('0'); continue }",
|
||||
" $cp = [int]$parts[0]; $sp = [int]$parts[1];",
|
||||
" $conn = Get-NetTCPConnection -LocalAddress 127.0.0.1 -LocalPort $cp -RemoteAddress 127.0.0.1 -RemotePort $sp -ErrorAction SilentlyContinue | Select-Object -First 1;",
|
||||
" if (-not $conn) { [Console]::Out.WriteLine('0'); continue }",
|
||||
" $pidKey = [int]$conn.OwningProcess;",
|
||||
" $now = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds();",
|
||||
" $entry = $cache[$pidKey];",
|
||||
" if ($entry -and ($now - $entry.ts) -lt 10000) {",
|
||||
" [Console]::Out.WriteLine($(if ($entry.ok) { '1' } else { '0' }));",
|
||||
" continue",
|
||||
" }",
|
||||
" $ok = $false;",
|
||||
" try {",
|
||||
' $proc = Get-CimInstance Win32_Process -Filter "ProcessId=$pidKey" -ErrorAction SilentlyContinue;',
|
||||
" if ($proc) {",
|
||||
" $sid = (Invoke-CimMethod -InputObject $proc -MethodName GetOwnerSid).Sid;",
|
||||
" $ok = ($sid -eq $selfSid);",
|
||||
" }",
|
||||
" } catch { $ok = $false }",
|
||||
" $cache[$pidKey] = @{ ok = $ok; ts = $now };",
|
||||
" [Console]::Out.WriteLine($(if ($ok) { '1' } else { '0' }));",
|
||||
"}",
|
||||
].join(" ");
|
||||
|
||||
function formatHexPort(port: number): string {
|
||||
return port.toString(16).toUpperCase().padStart(4, "0");
|
||||
}
|
||||
|
||||
function isValidPort(port: number): boolean {
|
||||
return Number.isInteger(port) && port >= 1 && port <= 65535;
|
||||
}
|
||||
|
||||
export function findLinuxLoopbackSocketUid(
|
||||
procNetTcpContent: string,
|
||||
clientPort: number,
|
||||
serverPort: number,
|
||||
): number | null {
|
||||
if (!isValidPort(clientPort) || !isValidPort(serverPort)) {
|
||||
return null;
|
||||
}
|
||||
const clientHexPort = formatHexPort(clientPort);
|
||||
const serverHexPort = formatHexPort(serverPort);
|
||||
const targetLocalV4 = `${LINUX_LOOPBACK_IPV4_HEX}:${clientHexPort}`;
|
||||
const targetRemoteV4 = `${LINUX_LOOPBACK_IPV4_HEX}:${serverHexPort}`;
|
||||
const targetLocalV6 = `${LINUX_LOOPBACK_IPV4_MAPPED_IPV6_HEX}:${clientHexPort}`;
|
||||
const targetRemoteV6 = `${LINUX_LOOPBACK_IPV4_MAPPED_IPV6_HEX}:${serverHexPort}`;
|
||||
|
||||
const lines = procNetTcpContent.split(/\r?\n/u);
|
||||
for (let i = 1; i < lines.length; i += 1) {
|
||||
const trimmed = lines[i]?.trim();
|
||||
if (!trimmed) continue;
|
||||
const fields = trimmed.split(/\s+/u);
|
||||
if (fields.length < 8) continue;
|
||||
const localAddr = fields[1]?.toUpperCase();
|
||||
const remoteAddr = fields[2]?.toUpperCase();
|
||||
if (
|
||||
(localAddr === targetLocalV4 && remoteAddr === targetRemoteV4) ||
|
||||
(localAddr === targetLocalV6 && remoteAddr === targetRemoteV6)
|
||||
) {
|
||||
const uid = Number.parseInt(fields[7] ?? "", 10);
|
||||
return Number.isInteger(uid) && uid >= 0 ? uid : null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function findDarwinLoopbackSocketUid(
|
||||
lsofOutput: string,
|
||||
clientPort: number,
|
||||
serverPort: number,
|
||||
): number | null {
|
||||
if (!isValidPort(clientPort) || !isValidPort(serverPort)) {
|
||||
return null;
|
||||
}
|
||||
const expectedName = `127.0.0.1:${clientPort}->127.0.0.1:${serverPort}`;
|
||||
let currentUid: number | null = null;
|
||||
for (const rawLine of lsofOutput.split(/\r?\n/u)) {
|
||||
const line = rawLine.trim();
|
||||
if (!line) continue;
|
||||
const prefix = line[0];
|
||||
const value = line.slice(1);
|
||||
if (prefix === "p") {
|
||||
currentUid = null;
|
||||
} else if (prefix === "u") {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
currentUid = Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
|
||||
} else if (prefix === "n" && value === expectedName) {
|
||||
return currentUid;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function parseWindowsLoopbackSocketOwner(output: string): string | null {
|
||||
const sid = output.trim();
|
||||
return /^S-1-\d+(?:-\d+)+$/u.test(sid) ? sid : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a single warm PowerShell worker on Windows so parallel browser
|
||||
* connections do not each pay PowerShell startup + NetTCPIP/WMI cold boot.
|
||||
* Serializes line-delimited `<clientPort> <serverPort>` lookups and resets
|
||||
* cleanly on timeout or process exit.
|
||||
*/
|
||||
function createPersistentWindowsPowerShellWorker(): WindowsSocketOwnerWorker {
|
||||
let child: ChildProcessWithoutNullStreams | null = null;
|
||||
let stdoutBuffer = "";
|
||||
let disposed = false;
|
||||
|
||||
interface QueuedLookup {
|
||||
input: SocketOwnerCheckInput;
|
||||
resolve: (allowed: boolean) => void;
|
||||
timer: ReturnType<typeof setTimeout> | null;
|
||||
}
|
||||
|
||||
let active: QueuedLookup | null = null;
|
||||
const queue: QueuedLookup[] = [];
|
||||
|
||||
const failActiveAndReset = () => {
|
||||
const current = active;
|
||||
active = null;
|
||||
if (current) {
|
||||
if (current.timer) clearTimeout(current.timer);
|
||||
current.resolve(false);
|
||||
}
|
||||
const oldChild = child;
|
||||
child = null;
|
||||
stdoutBuffer = "";
|
||||
if (oldChild && !oldChild.killed) {
|
||||
try {
|
||||
oldChild.kill();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
if (!disposed) {
|
||||
pumpQueue();
|
||||
}
|
||||
};
|
||||
|
||||
const ensureChild = (): ChildProcessWithoutNullStreams | null => {
|
||||
if (disposed) return null;
|
||||
if (child && !child.killed && child.exitCode === null) {
|
||||
return child;
|
||||
}
|
||||
const proc = nodeSpawn(
|
||||
"powershell.exe",
|
||||
["-NoProfile", "-NonInteractive", "-Command", WINDOWS_WORKER_SCRIPT],
|
||||
{
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
windowsHide: true,
|
||||
},
|
||||
);
|
||||
child = proc;
|
||||
stdoutBuffer = "";
|
||||
|
||||
proc.stdin.on("error", () => {
|
||||
if (child === proc) failActiveAndReset();
|
||||
});
|
||||
proc.stdout.on("data", (chunk: Buffer | string) => {
|
||||
if (child !== proc) return;
|
||||
stdoutBuffer += chunk.toString();
|
||||
let newlineIndex = stdoutBuffer.indexOf("\n");
|
||||
while (newlineIndex >= 0) {
|
||||
const line = stdoutBuffer.slice(0, newlineIndex).trim();
|
||||
stdoutBuffer = stdoutBuffer.slice(newlineIndex + 1);
|
||||
const current = active;
|
||||
active = null;
|
||||
if (current) {
|
||||
if (current.timer) clearTimeout(current.timer);
|
||||
current.resolve(line === "1");
|
||||
}
|
||||
pumpQueue();
|
||||
newlineIndex = stdoutBuffer.indexOf("\n");
|
||||
}
|
||||
});
|
||||
proc.on("error", () => {
|
||||
if (child === proc) failActiveAndReset();
|
||||
});
|
||||
proc.on("exit", () => {
|
||||
if (child === proc) failActiveAndReset();
|
||||
});
|
||||
return proc;
|
||||
};
|
||||
|
||||
const pumpQueue = () => {
|
||||
if (disposed || active || queue.length === 0) return;
|
||||
const next = queue.shift()!;
|
||||
const proc = ensureChild();
|
||||
if (!proc) {
|
||||
next.resolve(false);
|
||||
return;
|
||||
}
|
||||
active = next;
|
||||
next.timer = setTimeout(() => {
|
||||
if (active === next) {
|
||||
failActiveAndReset();
|
||||
}
|
||||
}, LOOKUP_TIMEOUT_MS);
|
||||
next.timer.unref?.();
|
||||
|
||||
try {
|
||||
proc.stdin.write(`${next.input.clientPort} ${next.input.serverPort}\n`);
|
||||
} catch {
|
||||
failActiveAndReset();
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
lookup: (input) =>
|
||||
new Promise<boolean>((resolve) => {
|
||||
if (disposed) {
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
queue.push({ input, resolve, timer: null });
|
||||
pumpQueue();
|
||||
}),
|
||||
dispose: () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
for (const queued of queue.splice(0)) {
|
||||
if (queued.timer) clearTimeout(queued.timer);
|
||||
queued.resolve(false);
|
||||
}
|
||||
failActiveAndReset();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createOsSocketOwnerVerifier(
|
||||
deps: OsSocketOwnerVerifierDeps = {},
|
||||
): SocketOwnerVerifier {
|
||||
const platform = deps.platform ?? process.platform;
|
||||
const getCurrentUid =
|
||||
deps.getCurrentUid ?? (() => (typeof process.getuid === "function" ? process.getuid() : null));
|
||||
const readFile = deps.readFile ?? ((filePath, encoding) => nodeReadFile(filePath, encoding));
|
||||
const execFile =
|
||||
deps.execFile ??
|
||||
(async (command, args, options) => {
|
||||
const result = await execFileAsync(command, args, {
|
||||
encoding: "utf8",
|
||||
timeout: options?.timeout ?? LOOKUP_TIMEOUT_MS,
|
||||
windowsHide: options?.windowsHide ?? true,
|
||||
});
|
||||
return { stdout: result.stdout };
|
||||
});
|
||||
|
||||
let windowsWorker: WindowsSocketOwnerWorker | null = null;
|
||||
const getWindowsWorker = (): WindowsSocketOwnerWorker => {
|
||||
if (!windowsWorker) {
|
||||
windowsWorker = (deps.createWindowsWorker ?? createPersistentWindowsPowerShellWorker)();
|
||||
}
|
||||
return windowsWorker;
|
||||
};
|
||||
|
||||
const verify: SocketOwnerVerifier = async ({
|
||||
clientPort,
|
||||
serverPort,
|
||||
}: SocketOwnerCheckInput): Promise<boolean> => {
|
||||
if (!isValidPort(clientPort) || !isValidPort(serverPort)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (platform === "linux") {
|
||||
const expectedUid = getCurrentUid();
|
||||
if (expectedUid === null) return false;
|
||||
try {
|
||||
const tcpContent = await readFile("/proc/net/tcp", "utf8");
|
||||
const uid = findLinuxLoopbackSocketUid(tcpContent, clientPort, serverPort);
|
||||
if (uid !== null) {
|
||||
return uid === expectedUid;
|
||||
}
|
||||
const tcp6Content = await readFile("/proc/net/tcp6", "utf8").catch(() => "");
|
||||
const uid6 = findLinuxLoopbackSocketUid(tcp6Content, clientPort, serverPort);
|
||||
return uid6 !== null && uid6 === expectedUid;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (platform === "darwin") {
|
||||
const expectedUid = getCurrentUid();
|
||||
if (expectedUid === null) return false;
|
||||
try {
|
||||
const { stdout } = await execFile(
|
||||
"lsof",
|
||||
["-nP", "-F", "pun", `-iTCP@127.0.0.1:${clientPort}`],
|
||||
{ timeout: LOOKUP_TIMEOUT_MS },
|
||||
);
|
||||
const uid = findDarwinLoopbackSocketUid(stdout, clientPort, serverPort);
|
||||
return uid !== null && uid === expectedUid;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (platform === "win32") {
|
||||
try {
|
||||
return await getWindowsWorker().lookup({ clientPort, serverPort });
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
verify.dispose = () => {
|
||||
windowsWorker?.dispose();
|
||||
windowsWorker = null;
|
||||
};
|
||||
|
||||
return verify;
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
import { Duplex, PassThrough } from "node:stream";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { NetworkTunnelCloseReason } from "@getpaseo/protocol/network-tunnel";
|
||||
import {
|
||||
performSocks5Handshake,
|
||||
Socks5Error,
|
||||
Socks5ReplyCode,
|
||||
socks5ReplyForTunnelCloseReason,
|
||||
writeSocks5Reply,
|
||||
} from "./socks5.js";
|
||||
|
||||
function createSocketPair(): { client: Duplex; server: Duplex } {
|
||||
const aToB = new PassThrough();
|
||||
const bToA = new PassThrough();
|
||||
|
||||
const client = new Duplex({
|
||||
read() {},
|
||||
write(chunk, encoding, cb) {
|
||||
aToB.write(chunk, encoding, cb);
|
||||
},
|
||||
final(cb) {
|
||||
aToB.end(cb);
|
||||
},
|
||||
});
|
||||
bToA.on("data", (chunk) => client.push(chunk));
|
||||
bToA.on("end", () => client.push(null));
|
||||
|
||||
const server = new Duplex({
|
||||
read() {},
|
||||
write(chunk, encoding, cb) {
|
||||
bToA.write(chunk, encoding, cb);
|
||||
},
|
||||
final(cb) {
|
||||
bToA.end(cb);
|
||||
},
|
||||
});
|
||||
aToB.on("data", (chunk) => server.push(chunk));
|
||||
aToB.on("end", () => server.push(null));
|
||||
|
||||
return { client, server };
|
||||
}
|
||||
|
||||
function readBytes(stream: Duplex, count: number): Promise<Buffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks: Buffer[] = [];
|
||||
let total = 0;
|
||||
const onData = (chunk: Buffer) => {
|
||||
chunks.push(chunk);
|
||||
total += chunk.length;
|
||||
if (total >= count) {
|
||||
cleanup();
|
||||
resolve(Buffer.concat(chunks).subarray(0, count));
|
||||
}
|
||||
};
|
||||
const onEnd = () => {
|
||||
cleanup();
|
||||
reject(new Error(`Unexpected EOF after ${total} bytes (expected ${count})`));
|
||||
};
|
||||
const cleanup = () => {
|
||||
stream.off("data", onData);
|
||||
stream.off("end", onEnd);
|
||||
};
|
||||
stream.on("data", onData);
|
||||
stream.on("end", onEnd);
|
||||
});
|
||||
}
|
||||
|
||||
describe("SOCKS5 handshake", () => {
|
||||
test("parses domain name CONNECT (ATYP=0x03) including fragmented chunks and trailing bytes", async () => {
|
||||
const { client, server } = createSocketPair();
|
||||
const handshakePromise = performSocks5Handshake(server);
|
||||
|
||||
// Send greeting fragmented
|
||||
client.write(Buffer.from([0x05, 0x02]));
|
||||
client.write(Buffer.from([0x02, 0x00]));
|
||||
|
||||
const methodReply = await readBytes(client, 2);
|
||||
expect(Array.from(methodReply)).toEqual([0x05, 0x00]);
|
||||
|
||||
// Send domain CONNECT for web.localhost:6767 + pipelined "GET /"
|
||||
const domain = Buffer.from("web.localhost", "utf8");
|
||||
const req = Buffer.concat([
|
||||
Buffer.from([0x05, 0x01, 0x00, 0x03, domain.length]),
|
||||
domain,
|
||||
Buffer.from([0x1a, 0x6f]), // 6767
|
||||
Buffer.from("GET /"),
|
||||
]);
|
||||
client.write(req.subarray(0, 6));
|
||||
client.write(req.subarray(6));
|
||||
|
||||
const result = await handshakePromise;
|
||||
expect(result.host).toBe("web.localhost");
|
||||
expect(result.port).toBe(6767);
|
||||
expect(result.leftover.toString("utf8")).toBe("GET /");
|
||||
|
||||
writeSocks5Reply(server, Socks5ReplyCode.Succeeded);
|
||||
const reply = await readBytes(client, 10);
|
||||
expect(Array.from(reply)).toEqual([0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0]);
|
||||
});
|
||||
|
||||
test("parses IPv4 CONNECT (ATYP=0x01)", async () => {
|
||||
const { client, server } = createSocketPair();
|
||||
const handshakePromise = performSocks5Handshake(server);
|
||||
|
||||
client.write(Buffer.from([0x05, 0x01, 0x00]));
|
||||
await readBytes(client, 2);
|
||||
|
||||
// 127.0.0.1:3000 (0x0BB8)
|
||||
client.write(Buffer.from([0x05, 0x01, 0x00, 0x01, 127, 0, 0, 1, 0x0b, 0xb8]));
|
||||
const result = await handshakePromise;
|
||||
expect(result).toEqual({ host: "127.0.0.1", port: 3000, leftover: Buffer.alloc(0) });
|
||||
});
|
||||
|
||||
test("parses IPv6 CONNECT (ATYP=0x04)", async () => {
|
||||
const { client, server } = createSocketPair();
|
||||
const handshakePromise = performSocks5Handshake(server);
|
||||
|
||||
client.write(Buffer.from([0x05, 0x01, 0x00]));
|
||||
await readBytes(client, 2);
|
||||
|
||||
// ::1 port 5173 (0x1435)
|
||||
const ipv6 = Buffer.alloc(16);
|
||||
ipv6[15] = 1;
|
||||
client.write(
|
||||
Buffer.concat([Buffer.from([0x05, 0x01, 0x00, 0x04]), ipv6, Buffer.from([0x14, 0x35])]),
|
||||
);
|
||||
|
||||
const result = await handshakePromise;
|
||||
expect(result.host).toBe("::1");
|
||||
expect(result.port).toBe(5173);
|
||||
expect(result.leftover.length).toBe(0);
|
||||
});
|
||||
|
||||
test("rejects non-CONNECT commands with CommandNotSupported (0x07)", async () => {
|
||||
const { client, server } = createSocketPair();
|
||||
const handshakePromise = performSocks5Handshake(server);
|
||||
|
||||
client.write(Buffer.from([0x05, 0x01, 0x00]));
|
||||
await readBytes(client, 2);
|
||||
|
||||
// CMD=0x03 (UDP ASSOCIATE)
|
||||
client.write(Buffer.from([0x05, 0x03, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50]));
|
||||
|
||||
await expect(handshakePromise).rejects.toMatchObject({
|
||||
name: Socks5Error.name,
|
||||
replyCode: Socks5ReplyCode.CommandNotSupported,
|
||||
});
|
||||
const reply = await readBytes(client, 10);
|
||||
expect(reply[1]).toBe(Socks5ReplyCode.CommandNotSupported);
|
||||
});
|
||||
|
||||
test("rejects greetings without NO AUTH (0x00) with 0xFF", async () => {
|
||||
const { client, server } = createSocketPair();
|
||||
const handshakePromise = performSocks5Handshake(server);
|
||||
|
||||
client.write(Buffer.from([0x05, 0x01, 0x02])); // username/password only
|
||||
|
||||
await expect(handshakePromise).rejects.toThrow(/auth/i);
|
||||
const reply = await readBytes(client, 2);
|
||||
expect(Array.from(reply)).toEqual([0x05, 0xff]);
|
||||
});
|
||||
|
||||
test("maps daemon tunnel close reasons to SOCKS5 reply codes", () => {
|
||||
expect(socks5ReplyForTunnelCloseReason(NetworkTunnelCloseReason.ConnectRefused)).toBe(
|
||||
Socks5ReplyCode.ConnectionRefused,
|
||||
);
|
||||
expect(socks5ReplyForTunnelCloseReason(NetworkTunnelCloseReason.PolicyDenied)).toBe(
|
||||
Socks5ReplyCode.ConnectionNotAllowed,
|
||||
);
|
||||
expect(socks5ReplyForTunnelCloseReason(NetworkTunnelCloseReason.DnsFailed)).toBe(
|
||||
Socks5ReplyCode.HostUnreachable,
|
||||
);
|
||||
expect(socks5ReplyForTunnelCloseReason(NetworkTunnelCloseReason.HostUnreachable)).toBe(
|
||||
Socks5ReplyCode.NetworkUnreachable,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,279 +0,0 @@
|
||||
import type { Duplex } from "node:stream";
|
||||
import { NetworkTunnelCloseReason } from "@getpaseo/protocol/network-tunnel";
|
||||
|
||||
const SOCKS5_VERSION = 0x05;
|
||||
const SOCKS5_AUTH_NONE = 0x00;
|
||||
const SOCKS5_AUTH_NO_ACCEPTABLE = 0xff;
|
||||
const SOCKS5_CMD_CONNECT = 0x01;
|
||||
const SOCKS5_ATYP_IPV4 = 0x01;
|
||||
const SOCKS5_ATYP_DOMAIN = 0x03;
|
||||
const SOCKS5_ATYP_IPV6 = 0x04;
|
||||
const DEFAULT_HANDSHAKE_TIMEOUT_MS = 10_000;
|
||||
|
||||
export enum Socks5ReplyCode {
|
||||
Succeeded = 0x00,
|
||||
GeneralFailure = 0x01,
|
||||
ConnectionNotAllowed = 0x02,
|
||||
NetworkUnreachable = 0x03,
|
||||
HostUnreachable = 0x04,
|
||||
ConnectionRefused = 0x05,
|
||||
CommandNotSupported = 0x07,
|
||||
AddressTypeNotSupported = 0x08,
|
||||
}
|
||||
|
||||
export class Socks5Error extends Error {
|
||||
public readonly replyCode: Socks5ReplyCode | null;
|
||||
|
||||
public constructor(message: string, replyCode: Socks5ReplyCode | null = null) {
|
||||
super(message);
|
||||
this.name = "Socks5Error";
|
||||
this.replyCode = replyCode;
|
||||
}
|
||||
}
|
||||
|
||||
export interface Socks5ConnectRequest {
|
||||
host: string;
|
||||
port: number;
|
||||
leftover: Buffer;
|
||||
}
|
||||
|
||||
export function socks5ReplyForTunnelCloseReason(reason: NetworkTunnelCloseReason): Socks5ReplyCode {
|
||||
switch (reason) {
|
||||
case NetworkTunnelCloseReason.ConnectRefused:
|
||||
return Socks5ReplyCode.ConnectionRefused;
|
||||
case NetworkTunnelCloseReason.PolicyDenied:
|
||||
return Socks5ReplyCode.ConnectionNotAllowed;
|
||||
case NetworkTunnelCloseReason.HostUnreachable:
|
||||
return Socks5ReplyCode.NetworkUnreachable;
|
||||
case NetworkTunnelCloseReason.DnsFailed:
|
||||
case NetworkTunnelCloseReason.Timeout:
|
||||
return Socks5ReplyCode.HostUnreachable;
|
||||
default:
|
||||
return Socks5ReplyCode.GeneralFailure;
|
||||
}
|
||||
}
|
||||
|
||||
export function writeSocks5Reply(socket: Duplex, replyCode: Socks5ReplyCode): void {
|
||||
if (socket.destroyed || !socket.writable) {
|
||||
return;
|
||||
}
|
||||
socket.write(Buffer.from([SOCKS5_VERSION, replyCode, 0x00, SOCKS5_ATYP_IPV4, 0, 0, 0, 0, 0, 0]));
|
||||
}
|
||||
|
||||
function formatIpv6Bytes(bytes: Buffer): string {
|
||||
const groups: number[] = [];
|
||||
for (let i = 0; i < 16; i += 2) {
|
||||
groups.push(bytes.readUInt16BE(i));
|
||||
}
|
||||
let bestStart = -1;
|
||||
let bestLen = 0;
|
||||
let curStart = -1;
|
||||
let curLen = 0;
|
||||
for (let i = 0; i < 8; i += 1) {
|
||||
if (groups[i] === 0) {
|
||||
if (curStart === -1) {
|
||||
curStart = i;
|
||||
curLen = 1;
|
||||
} else {
|
||||
curLen += 1;
|
||||
}
|
||||
if (curLen > bestLen) {
|
||||
bestStart = curStart;
|
||||
bestLen = curLen;
|
||||
}
|
||||
} else {
|
||||
curStart = -1;
|
||||
curLen = 0;
|
||||
}
|
||||
}
|
||||
if (bestLen < 2) {
|
||||
return groups.map((g) => g.toString(16)).join(":");
|
||||
}
|
||||
const head = groups
|
||||
.slice(0, bestStart)
|
||||
.map((g) => g.toString(16))
|
||||
.join(":");
|
||||
const tail = groups
|
||||
.slice(bestStart + bestLen)
|
||||
.map((g) => g.toString(16))
|
||||
.join(":");
|
||||
return `${head}::${tail}`;
|
||||
}
|
||||
|
||||
class BufferedSocketReader {
|
||||
private buffer: Buffer = Buffer.alloc(0);
|
||||
private ended = false;
|
||||
private failure: Error | null = null;
|
||||
private waiting: {
|
||||
need: number;
|
||||
resolve: (bytes: Buffer) => void;
|
||||
reject: (error: Error) => void;
|
||||
} | null = null;
|
||||
|
||||
private readonly onData = (chunk: Buffer | string) => {
|
||||
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
this.buffer = this.buffer.length === 0 ? buf : Buffer.concat([this.buffer, buf]);
|
||||
this.flushWaiter();
|
||||
};
|
||||
|
||||
private readonly onEnd = () => {
|
||||
this.ended = true;
|
||||
this.flushWaiter();
|
||||
};
|
||||
|
||||
private readonly onError = (error: Error) => {
|
||||
this.failure = error;
|
||||
this.flushWaiter();
|
||||
};
|
||||
|
||||
private readonly onClose = () => {
|
||||
this.ended = true;
|
||||
this.flushWaiter();
|
||||
};
|
||||
|
||||
public constructor(private readonly socket: Duplex) {
|
||||
socket.on("data", this.onData);
|
||||
socket.on("end", this.onEnd);
|
||||
socket.on("error", this.onError);
|
||||
socket.on("close", this.onClose);
|
||||
}
|
||||
|
||||
public readExact(count: number): Promise<Buffer> {
|
||||
if (this.buffer.length >= count) {
|
||||
const out = this.buffer.subarray(0, count);
|
||||
this.buffer = this.buffer.subarray(count);
|
||||
return Promise.resolve(out);
|
||||
}
|
||||
if (this.failure) {
|
||||
return Promise.reject(this.failure);
|
||||
}
|
||||
if (this.ended) {
|
||||
return Promise.reject(new Socks5Error("SOCKS5 client closed during handshake"));
|
||||
}
|
||||
return new Promise<Buffer>((resolve, reject) => {
|
||||
this.waiting = { need: count, resolve, reject };
|
||||
});
|
||||
}
|
||||
|
||||
public detach(): Buffer {
|
||||
this.socket.off("data", this.onData);
|
||||
this.socket.off("end", this.onEnd);
|
||||
this.socket.off("error", this.onError);
|
||||
this.socket.off("close", this.onClose);
|
||||
const leftover = this.buffer;
|
||||
this.buffer = Buffer.alloc(0);
|
||||
return leftover;
|
||||
}
|
||||
|
||||
private flushWaiter(): void {
|
||||
const waiter = this.waiting;
|
||||
if (!waiter) return;
|
||||
if (this.buffer.length >= waiter.need) {
|
||||
this.waiting = null;
|
||||
const out = this.buffer.subarray(0, waiter.need);
|
||||
this.buffer = this.buffer.subarray(waiter.need);
|
||||
waiter.resolve(out);
|
||||
return;
|
||||
}
|
||||
if (this.failure) {
|
||||
this.waiting = null;
|
||||
waiter.reject(this.failure);
|
||||
return;
|
||||
}
|
||||
if (this.ended) {
|
||||
this.waiting = null;
|
||||
waiter.reject(new Socks5Error("SOCKS5 client closed during handshake"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function performSocks5Handshake(
|
||||
socket: Duplex,
|
||||
options?: { timeoutMs?: number },
|
||||
): Promise<Socks5ConnectRequest> {
|
||||
const reader = new BufferedSocketReader(socket);
|
||||
const timeoutMs = options?.timeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS;
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const handshake = async (): Promise<Socks5ConnectRequest> => {
|
||||
const greetingHeader = await reader.readExact(2);
|
||||
if (greetingHeader[0] !== SOCKS5_VERSION) {
|
||||
throw new Socks5Error(`Unsupported SOCKS version: ${greetingHeader[0]}`);
|
||||
}
|
||||
const nMethods = greetingHeader[1] ?? 0;
|
||||
const methods = nMethods > 0 ? await reader.readExact(nMethods) : Buffer.alloc(0);
|
||||
if (!methods.includes(SOCKS5_AUTH_NONE)) {
|
||||
if (!socket.destroyed && socket.writable) {
|
||||
socket.write(Buffer.from([SOCKS5_VERSION, SOCKS5_AUTH_NO_ACCEPTABLE]));
|
||||
}
|
||||
throw new Socks5Error("SOCKS5 client did not offer NO AUTH method");
|
||||
}
|
||||
socket.write(Buffer.from([SOCKS5_VERSION, SOCKS5_AUTH_NONE]));
|
||||
|
||||
const reqHeader = await reader.readExact(4);
|
||||
if (reqHeader[0] !== SOCKS5_VERSION) {
|
||||
throw new Socks5Error(`Unsupported SOCKS request version: ${reqHeader[0]}`);
|
||||
}
|
||||
const cmd = reqHeader[1];
|
||||
const atyp = reqHeader[3];
|
||||
|
||||
if (cmd !== SOCKS5_CMD_CONNECT) {
|
||||
writeSocks5Reply(socket, Socks5ReplyCode.CommandNotSupported);
|
||||
throw new Socks5Error(
|
||||
`Unsupported SOCKS5 command: ${cmd}`,
|
||||
Socks5ReplyCode.CommandNotSupported,
|
||||
);
|
||||
}
|
||||
|
||||
let host: string;
|
||||
if (atyp === SOCKS5_ATYP_IPV4) {
|
||||
const addr = await reader.readExact(4);
|
||||
host = `${addr[0]}.${addr[1]}.${addr[2]}.${addr[3]}`;
|
||||
} else if (atyp === SOCKS5_ATYP_DOMAIN) {
|
||||
const lenBuf = await reader.readExact(1);
|
||||
const len = lenBuf[0] ?? 0;
|
||||
if (len === 0) {
|
||||
writeSocks5Reply(socket, Socks5ReplyCode.GeneralFailure);
|
||||
throw new Socks5Error("Empty SOCKS5 domain name", Socks5ReplyCode.GeneralFailure);
|
||||
}
|
||||
const domainBuf = await reader.readExact(len);
|
||||
host = domainBuf.toString("utf8");
|
||||
} else if (atyp === SOCKS5_ATYP_IPV6) {
|
||||
const addr = await reader.readExact(16);
|
||||
host = formatIpv6Bytes(addr);
|
||||
} else {
|
||||
writeSocks5Reply(socket, Socks5ReplyCode.AddressTypeNotSupported);
|
||||
throw new Socks5Error(
|
||||
`Unsupported SOCKS5 address type: ${atyp}`,
|
||||
Socks5ReplyCode.AddressTypeNotSupported,
|
||||
);
|
||||
}
|
||||
|
||||
const portBuf = await reader.readExact(2);
|
||||
const port = portBuf.readUInt16BE(0);
|
||||
if (port < 1) {
|
||||
writeSocks5Reply(socket, Socks5ReplyCode.GeneralFailure);
|
||||
throw new Socks5Error(`Invalid SOCKS5 target port: ${port}`, Socks5ReplyCode.GeneralFailure);
|
||||
}
|
||||
|
||||
const leftover = reader.detach();
|
||||
return { host, port, leftover };
|
||||
};
|
||||
|
||||
try {
|
||||
return await Promise.race([
|
||||
handshake(),
|
||||
new Promise<never>((_resolve, reject) => {
|
||||
timer = setTimeout(() => {
|
||||
reject(new Socks5Error("SOCKS5 handshake timed out"));
|
||||
}, timeoutMs);
|
||||
timer.unref?.();
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
reader.detach();
|
||||
}
|
||||
}
|
||||
@@ -1,315 +0,0 @@
|
||||
import { Duplex, PassThrough } from "node:stream";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
decodeNetworkTunnelFrame,
|
||||
encodeNetworkTunnelFrame,
|
||||
NetworkTunnelCloseReason,
|
||||
type DecodedNetworkTunnelFrame,
|
||||
type NetworkTunnelFrame,
|
||||
} from "@getpaseo/protocol/network-tunnel";
|
||||
import { TunnelMuxClient } from "./tunnel-mux.js";
|
||||
import type { TunnelWireConnection } from "./tunnel-transport.js";
|
||||
|
||||
function createFakeWire(ready?: Partial<TunnelWireConnection["ready"]>) {
|
||||
const sentFrames: DecodedNetworkTunnelFrame[] = [];
|
||||
const binaryListeners = new Set<(bytes: Uint8Array) => void>();
|
||||
const closeListeners = new Set<(error?: Error) => void>();
|
||||
let closed = false;
|
||||
|
||||
const wire: TunnelWireConnection = {
|
||||
ready: {
|
||||
maxFramePayloadBytes: ready?.maxFramePayloadBytes ?? 64 * 1024,
|
||||
initialStreamWindowBytes: ready?.initialStreamWindowBytes ?? 64 * 1024,
|
||||
initialConnectionWindowBytes: ready?.initialConnectionWindowBytes ?? 256 * 1024,
|
||||
},
|
||||
sendBinary: async (bytes) => {
|
||||
if (closed) throw new Error("Wire closed");
|
||||
sentFrames.push(decodeNetworkTunnelFrame(bytes));
|
||||
},
|
||||
onBinary: (handler) => {
|
||||
binaryListeners.add(handler);
|
||||
return () => binaryListeners.delete(handler);
|
||||
},
|
||||
onClose: (handler) => {
|
||||
closeListeners.add(handler);
|
||||
return () => closeListeners.delete(handler);
|
||||
},
|
||||
close: () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
for (const listener of closeListeners) listener();
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
wire,
|
||||
sentFrames,
|
||||
injectFrame: (frame: NetworkTunnelFrame) => {
|
||||
const encoded = encodeNetworkTunnelFrame(frame);
|
||||
for (const listener of binaryListeners) listener(encoded);
|
||||
},
|
||||
drop: (error?: Error) => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
for (const listener of closeListeners) listener(error);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createSocketPair(): { client: Duplex; server: Duplex } {
|
||||
const aToB = new PassThrough();
|
||||
const bToA = new PassThrough();
|
||||
|
||||
const client = new Duplex({
|
||||
read() {},
|
||||
write(chunk, encoding, cb) {
|
||||
aToB.write(chunk, encoding, cb);
|
||||
},
|
||||
final(cb) {
|
||||
aToB.end(cb);
|
||||
},
|
||||
});
|
||||
bToA.on("data", (chunk) => client.push(chunk));
|
||||
bToA.on("end", () => client.push(null));
|
||||
|
||||
const server = new Duplex({
|
||||
read() {},
|
||||
write(chunk, encoding, cb) {
|
||||
bToA.write(chunk, encoding, cb);
|
||||
},
|
||||
final(cb) {
|
||||
bToA.end(cb);
|
||||
},
|
||||
});
|
||||
aToB.on("data", (chunk) => server.push(chunk));
|
||||
aToB.on("end", () => server.push(null));
|
||||
|
||||
return { client, server };
|
||||
}
|
||||
|
||||
describe("TunnelMuxClient", () => {
|
||||
test("opens a stream, exchanges bidirectional data, respects credit windows, and handles half-close", async () => {
|
||||
const fake = createFakeWire({
|
||||
maxFramePayloadBytes: 4,
|
||||
initialStreamWindowBytes: 8,
|
||||
initialConnectionWindowBytes: 16,
|
||||
});
|
||||
const mux = new TunnelMuxClient(fake.wire);
|
||||
const { client, server } = createSocketPair();
|
||||
|
||||
const openPromise = mux.openStream({
|
||||
host: "localhost",
|
||||
port: 3000,
|
||||
socket: server,
|
||||
initialData: Buffer.from("0123456789"), // 10 bytes > initialStreamWindowBytes (8)
|
||||
});
|
||||
|
||||
expect(fake.sentFrames[0]).toMatchObject({
|
||||
type: "open",
|
||||
streamId: 1,
|
||||
host: "localhost",
|
||||
port: 3000,
|
||||
});
|
||||
|
||||
fake.injectFrame({ type: "opened", streamId: 1, initialWindowBytes: 8 });
|
||||
const openResult = await openPromise;
|
||||
expect(openResult).toEqual({ ok: true });
|
||||
|
||||
// Only 8 bytes (in two 4-byte chunks) should be sent until window update arrives!
|
||||
await Promise.resolve();
|
||||
const dataFramesBefore = fake.sentFrames.filter((f) => f.type === "data");
|
||||
const sentBefore = Buffer.concat(dataFramesBefore.map((f) => Buffer.from(f.data))).toString();
|
||||
expect(sentBefore).toBe("01234567");
|
||||
|
||||
// Grant more stream credit -> remaining "89" flushes!
|
||||
fake.injectFrame({ type: "window_update", streamId: 1, creditBytes: 8 });
|
||||
await Promise.resolve();
|
||||
const dataFramesAfter = fake.sentFrames.filter((f) => f.type === "data");
|
||||
const sentAfter = Buffer.concat(dataFramesAfter.map((f) => Buffer.from(f.data))).toString();
|
||||
expect(sentAfter).toBe("0123456789");
|
||||
|
||||
// Remote sends data + half_close -> client socket receives exact bytes + EOF
|
||||
const received: Buffer[] = [];
|
||||
const clientEnded = new Promise<void>((resolve) => {
|
||||
client.on("data", (chunk: Buffer) => received.push(chunk));
|
||||
client.on("end", () => resolve());
|
||||
});
|
||||
fake.injectFrame({ type: "data", streamId: 1, data: Buffer.from("HTTP/1.1 200 OK") });
|
||||
fake.injectFrame({ type: "half_close", streamId: 1 });
|
||||
await clientEnded;
|
||||
expect(Buffer.concat(received).toString()).toBe("HTTP/1.1 200 OK");
|
||||
|
||||
// Client sends EOF -> mux sends HalfClose + Close (both halves closed)
|
||||
client.end();
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
expect(fake.sentFrames.some((f) => f.type === "half_close" && f.streamId === 1)).toBe(true);
|
||||
});
|
||||
|
||||
test("returns daemon Close reason when Open is rejected", async () => {
|
||||
const fake = createFakeWire();
|
||||
const mux = new TunnelMuxClient(fake.wire);
|
||||
const { server } = createSocketPair();
|
||||
|
||||
const openPromise = mux.openStream({
|
||||
host: "169.254.169.254",
|
||||
port: 80,
|
||||
socket: server,
|
||||
});
|
||||
fake.injectFrame({
|
||||
type: "close",
|
||||
streamId: 1,
|
||||
reason: NetworkTunnelCloseReason.PolicyDenied,
|
||||
message: "Blocked metadata IP",
|
||||
});
|
||||
|
||||
expect(await openPromise).toEqual({
|
||||
ok: false,
|
||||
reason: NetworkTunnelCloseReason.PolicyDenied,
|
||||
message: "Blocked metadata IP",
|
||||
});
|
||||
});
|
||||
|
||||
test("replies Pong to Ping frames and tears down active streams on wire drop", async () => {
|
||||
const fake = createFakeWire();
|
||||
const mux = new TunnelMuxClient(fake.wire);
|
||||
const { server } = createSocketPair();
|
||||
|
||||
fake.injectFrame({ type: "ping", payload: Buffer.from("abc") });
|
||||
await Promise.resolve();
|
||||
expect(fake.sentFrames.at(-1)).toMatchObject({
|
||||
type: "pong",
|
||||
payload: new Uint8Array(Buffer.from("abc")),
|
||||
});
|
||||
|
||||
const openPromise = mux.openStream({ host: "localhost", port: 8080, socket: server });
|
||||
fake.injectFrame({ type: "opened", streamId: 1, initialWindowBytes: 1024 });
|
||||
await openPromise;
|
||||
|
||||
const destroyed = new Promise<void>((resolve) => server.once("close", () => resolve()));
|
||||
fake.drop(new Error("socket dropped"));
|
||||
await destroyed;
|
||||
expect(mux.isClosed()).toBe(true);
|
||||
});
|
||||
|
||||
test("recovers connection receive credit when a backpressured socket is destroyed before drain without accumulating drain listeners", async () => {
|
||||
const fake = createFakeWire({
|
||||
maxFramePayloadBytes: 64,
|
||||
initialStreamWindowBytes: 256,
|
||||
initialConnectionWindowBytes: 128,
|
||||
});
|
||||
const mux = new TunnelMuxClient(fake.wire);
|
||||
|
||||
const stalledSocket = new Duplex({
|
||||
highWaterMark: 1,
|
||||
read() {},
|
||||
write(_chunk, _encoding, _cb) {
|
||||
// Hold write callbacks indefinitely to trigger backpressure without draining.
|
||||
},
|
||||
});
|
||||
|
||||
const openPromise = mux.openStream({
|
||||
host: "localhost",
|
||||
port: 3000,
|
||||
socket: stalledSocket,
|
||||
});
|
||||
fake.injectFrame({ type: "opened", streamId: 1, initialWindowBytes: 256 });
|
||||
expect(await openPromise).toEqual({ ok: true });
|
||||
|
||||
// Send 3 backpressured chunks totaling 96 bytes (>= 64 byte connection window threshold).
|
||||
fake.injectFrame({ type: "data", streamId: 1, data: Buffer.alloc(32, 0x61) });
|
||||
fake.injectFrame({ type: "data", streamId: 1, data: Buffer.alloc(32, 0x62) });
|
||||
fake.injectFrame({ type: "data", streamId: 1, data: Buffer.alloc(32, 0x63) });
|
||||
|
||||
// Only a single persistent drain listener should be attached to the socket.
|
||||
expect(stalledSocket.listenerCount("drain")).toBe(1);
|
||||
expect(fake.sentFrames.filter((f) => f.type === "window_update" && f.streamId === 0)).toEqual(
|
||||
[],
|
||||
);
|
||||
|
||||
// Destroy socket before drain fires -> pendingDrainBytes must be credited back to stream 0.
|
||||
stalledSocket.destroy();
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
|
||||
expect(stalledSocket.listenerCount("drain")).toBe(0);
|
||||
expect(
|
||||
fake.sentFrames.filter((f) => f.type === "window_update" && f.streamId === 0),
|
||||
).toMatchObject([
|
||||
{
|
||||
type: "window_update",
|
||||
streamId: 0,
|
||||
creditBytes: 96,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("emits half_close only once even when WindowUpdate arrives afterward", async () => {
|
||||
const fake = createFakeWire({
|
||||
maxFramePayloadBytes: 16,
|
||||
initialStreamWindowBytes: 32,
|
||||
initialConnectionWindowBytes: 64,
|
||||
});
|
||||
const mux = new TunnelMuxClient(fake.wire);
|
||||
const { client, server } = createSocketPair();
|
||||
|
||||
const openPromise = mux.openStream({
|
||||
host: "localhost",
|
||||
port: 3000,
|
||||
socket: server,
|
||||
});
|
||||
fake.injectFrame({ type: "opened", streamId: 1, initialWindowBytes: 16 });
|
||||
expect(await openPromise).toEqual({ ok: true });
|
||||
|
||||
// Local side finishes writing (EOF) while remote side stays open.
|
||||
client.end();
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
|
||||
expect(fake.sentFrames.filter((f) => f.type === "half_close" && f.streamId === 1)).toHaveLength(
|
||||
1,
|
||||
);
|
||||
|
||||
// Subsequent stream-level and connection-level WindowUpdates must not emit duplicate half_close frames.
|
||||
fake.injectFrame({ type: "window_update", streamId: 1, creditBytes: 16 });
|
||||
fake.injectFrame({ type: "window_update", streamId: 0, creditBytes: 32 });
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
|
||||
expect(fake.sentFrames.filter((f) => f.type === "half_close" && f.streamId === 1)).toHaveLength(
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
test("sends heartbeat pings and closes a silent half-open wire after heartbeatTimeoutMs", async () => {
|
||||
const fake = createFakeWire();
|
||||
const mux = new TunnelMuxClient(fake.wire, {
|
||||
heartbeatIntervalMs: 25,
|
||||
heartbeatTimeoutMs: 65,
|
||||
});
|
||||
|
||||
const closed = new Promise<Error | undefined>((resolve) => {
|
||||
mux.onClose((err) => resolve(err));
|
||||
});
|
||||
|
||||
const closeErr = await closed;
|
||||
expect(mux.isClosed()).toBe(true);
|
||||
expect(fake.sentFrames.some((f) => f.type === "ping")).toBe(true);
|
||||
expect(closeErr?.message).toMatch(/heartbeat/i);
|
||||
});
|
||||
|
||||
test("closes an unresponsive wire when openStream times out with zero inbound frames", async () => {
|
||||
const fake = createFakeWire();
|
||||
const mux = new TunnelMuxClient(fake.wire, {
|
||||
heartbeatIntervalMs: 0,
|
||||
heartbeatTimeoutMs: 0,
|
||||
});
|
||||
const { server } = createSocketPair();
|
||||
|
||||
const result = await mux.openStream({
|
||||
host: "localhost",
|
||||
port: 3000,
|
||||
socket: server,
|
||||
timeoutMs: 30,
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({ ok: false, reason: NetworkTunnelCloseReason.Timeout });
|
||||
expect(mux.isClosed()).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,603 +0,0 @@
|
||||
import type { Duplex } from "node:stream";
|
||||
import {
|
||||
decodeNetworkTunnelFrame,
|
||||
encodeNetworkTunnelFrame,
|
||||
NETWORK_TUNNEL_MAX_DATA_PAYLOAD_BYTES,
|
||||
NetworkTunnelCloseReason,
|
||||
type DecodedNetworkTunnelFrame,
|
||||
type NetworkTunnelFrame,
|
||||
} from "@getpaseo/protocol/network-tunnel";
|
||||
import type { TunnelWireConnection } from "./tunnel-transport.js";
|
||||
|
||||
export type OpenTunnelStreamResult =
|
||||
| { ok: true }
|
||||
| { ok: false; reason: NetworkTunnelCloseReason; message?: string };
|
||||
|
||||
interface ActiveStream {
|
||||
readonly streamId: number;
|
||||
readonly socket: Duplex;
|
||||
state: "opening" | "open" | "closed";
|
||||
sendWindow: number;
|
||||
outboundQueue: Buffer[];
|
||||
socketPaused: boolean;
|
||||
localHalfClosed: boolean;
|
||||
localHalfCloseSent: boolean;
|
||||
remoteHalfClosed: boolean;
|
||||
recvConsumed: number;
|
||||
recvWindowLimit: number;
|
||||
pendingDrainBytes: number;
|
||||
pendingOpenResolve?: (result: OpenTunnelStreamResult) => void;
|
||||
onOpened?: () => void;
|
||||
cleanupSocketListeners?: () => void;
|
||||
}
|
||||
|
||||
const DEFAULT_OPEN_TIMEOUT_MS = 15_000;
|
||||
const DEFAULT_HEARTBEAT_INTERVAL_MS = 15_000;
|
||||
const DEFAULT_HEARTBEAT_TIMEOUT_MS = 30_000;
|
||||
|
||||
export interface TunnelMuxClientOptions {
|
||||
heartbeatIntervalMs?: number;
|
||||
heartbeatTimeoutMs?: number;
|
||||
}
|
||||
|
||||
export class TunnelMuxClient {
|
||||
private readonly streams = new Map<number, ActiveStream>();
|
||||
private readonly maxFramePayloadBytes: number;
|
||||
private readonly initialStreamWindowBytes: number;
|
||||
private readonly initialConnectionWindowBytes: number;
|
||||
private readonly heartbeatTimeoutMs: number;
|
||||
private sendConnWindow: number;
|
||||
private recvConnConsumed = 0;
|
||||
private nextStreamId = 1;
|
||||
private closed = false;
|
||||
private lastInboundAt = Date.now();
|
||||
private inboundFrameSeq = 0;
|
||||
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private readonly unsubBinary: () => void;
|
||||
private readonly unsubClose: () => void;
|
||||
private readonly closeListeners = new Set<(error?: Error) => void>();
|
||||
|
||||
public constructor(
|
||||
private readonly wire: TunnelWireConnection,
|
||||
options?: TunnelMuxClientOptions,
|
||||
) {
|
||||
this.maxFramePayloadBytes = Math.max(
|
||||
1,
|
||||
Math.min(wire.ready.maxFramePayloadBytes, NETWORK_TUNNEL_MAX_DATA_PAYLOAD_BYTES),
|
||||
);
|
||||
this.initialStreamWindowBytes = Math.max(1, wire.ready.initialStreamWindowBytes);
|
||||
this.initialConnectionWindowBytes = Math.max(1, wire.ready.initialConnectionWindowBytes);
|
||||
this.sendConnWindow = this.initialConnectionWindowBytes;
|
||||
|
||||
const heartbeatIntervalMs = options?.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;
|
||||
this.heartbeatTimeoutMs = options?.heartbeatTimeoutMs ?? DEFAULT_HEARTBEAT_TIMEOUT_MS;
|
||||
|
||||
this.unsubBinary = wire.onBinary((bytes) => {
|
||||
this.handleInboundBytes(bytes);
|
||||
});
|
||||
this.unsubClose = wire.onClose((error) => {
|
||||
this.handleWireClosed(error);
|
||||
});
|
||||
|
||||
if (heartbeatIntervalMs > 0 && this.heartbeatTimeoutMs > 0) {
|
||||
this.heartbeatTimer = setInterval(() => {
|
||||
if (this.closed) return;
|
||||
if (Date.now() - this.lastInboundAt >= this.heartbeatTimeoutMs) {
|
||||
const timeoutError = new Error("Tunnel heartbeat timed out");
|
||||
this.handleWireClosed(timeoutError);
|
||||
this.wire.close();
|
||||
return;
|
||||
}
|
||||
this.sendFrameBestEffort({ type: "ping" });
|
||||
}, heartbeatIntervalMs);
|
||||
this.heartbeatTimer.unref?.();
|
||||
}
|
||||
}
|
||||
|
||||
public isClosed(): boolean {
|
||||
return this.closed;
|
||||
}
|
||||
|
||||
public onClose(listener: (error?: Error) => void): () => void {
|
||||
if (this.closed) {
|
||||
listener();
|
||||
return () => {};
|
||||
}
|
||||
this.closeListeners.add(listener);
|
||||
return () => {
|
||||
this.closeListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
public openStream(input: {
|
||||
host: string;
|
||||
port: number;
|
||||
socket: Duplex;
|
||||
initialData?: Buffer;
|
||||
onOpened?: () => void;
|
||||
timeoutMs?: number;
|
||||
}): Promise<OpenTunnelStreamResult> {
|
||||
if (this.closed) {
|
||||
return Promise.resolve({
|
||||
ok: false,
|
||||
reason: NetworkTunnelCloseReason.HostUnreachable,
|
||||
message: "Tunnel connection is closed",
|
||||
});
|
||||
}
|
||||
|
||||
const streamId = this.allocateStreamId();
|
||||
const stream: ActiveStream = {
|
||||
streamId,
|
||||
socket: input.socket,
|
||||
state: "opening",
|
||||
sendWindow: 0,
|
||||
outboundQueue:
|
||||
input.initialData && input.initialData.length > 0 ? [Buffer.from(input.initialData)] : [],
|
||||
socketPaused: false,
|
||||
localHalfClosed: false,
|
||||
localHalfCloseSent: false,
|
||||
remoteHalfClosed: false,
|
||||
recvConsumed: 0,
|
||||
recvWindowLimit: this.initialStreamWindowBytes,
|
||||
pendingDrainBytes: 0,
|
||||
onOpened: input.onOpened,
|
||||
};
|
||||
|
||||
this.streams.set(streamId, stream);
|
||||
|
||||
let resolveOpen!: (result: OpenTunnelStreamResult) => void;
|
||||
const promise = new Promise<OpenTunnelStreamResult>((resolve) => {
|
||||
resolveOpen = resolve;
|
||||
});
|
||||
const timeoutMs = input.timeoutMs ?? DEFAULT_OPEN_TIMEOUT_MS;
|
||||
const finishOpen = (result: OpenTunnelStreamResult) => {
|
||||
if (!stream.pendingOpenResolve) return;
|
||||
clearTimeout(timer);
|
||||
stream.pendingOpenResolve = undefined;
|
||||
resolveOpen(result);
|
||||
};
|
||||
|
||||
const openInboundSeq = this.inboundFrameSeq;
|
||||
const timer = setTimeout(() => {
|
||||
if (stream.state !== "opening") return;
|
||||
this.streams.delete(streamId);
|
||||
stream.state = "closed";
|
||||
this.sendFrameBestEffort({
|
||||
type: "close",
|
||||
streamId,
|
||||
reason: NetworkTunnelCloseReason.Timeout,
|
||||
});
|
||||
finishOpen({
|
||||
ok: false,
|
||||
reason: NetworkTunnelCloseReason.Timeout,
|
||||
message: "Timed out opening remote tunnel stream",
|
||||
});
|
||||
// If zero inbound frames arrived from the daemon during the entire open timeout,
|
||||
// treat the underlying tunnel wire as dead so the next request opens a fresh one.
|
||||
if (this.inboundFrameSeq === openInboundSeq) {
|
||||
const err = new Error("Tunnel became unresponsive during stream open");
|
||||
this.handleWireClosed(err);
|
||||
this.wire.close();
|
||||
}
|
||||
}, timeoutMs);
|
||||
timer.unref?.();
|
||||
|
||||
stream.pendingOpenResolve = finishOpen;
|
||||
|
||||
void this.sendFrame({
|
||||
type: "open",
|
||||
streamId,
|
||||
host: input.host,
|
||||
port: input.port,
|
||||
}).catch((error) => {
|
||||
if (stream.state !== "opening") return;
|
||||
this.streams.delete(streamId);
|
||||
stream.state = "closed";
|
||||
finishOpen({
|
||||
ok: false,
|
||||
reason: NetworkTunnelCloseReason.InternalError,
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
});
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
public close(): void {
|
||||
if (this.closed) return;
|
||||
this.wire.close();
|
||||
this.handleWireClosed();
|
||||
}
|
||||
|
||||
private allocateStreamId(): number {
|
||||
let id = this.nextStreamId;
|
||||
this.nextStreamId += 1;
|
||||
if (this.nextStreamId > 0xffffffff) {
|
||||
this.nextStreamId = 1;
|
||||
}
|
||||
while (id === 0 || this.streams.has(id)) {
|
||||
id = this.nextStreamId;
|
||||
this.nextStreamId += 1;
|
||||
if (this.nextStreamId > 0xffffffff) {
|
||||
this.nextStreamId = 1;
|
||||
}
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
private sendFrame(frame: NetworkTunnelFrame): Promise<void> {
|
||||
if (this.closed) {
|
||||
return Promise.reject(new Error("Tunnel mux is closed"));
|
||||
}
|
||||
return this.wire.sendBinary(encodeNetworkTunnelFrame(frame));
|
||||
}
|
||||
|
||||
private sendFrameBestEffort(frame: NetworkTunnelFrame): void {
|
||||
if (this.closed) return;
|
||||
void this.sendFrame(frame).catch(() => {
|
||||
// Wire failure triggers handleWireClosed separately.
|
||||
});
|
||||
}
|
||||
|
||||
private handleInboundBytes(bytes: Uint8Array): void {
|
||||
this.lastInboundAt = Date.now();
|
||||
this.inboundFrameSeq += 1;
|
||||
let frame: DecodedNetworkTunnelFrame;
|
||||
try {
|
||||
frame = decodeNetworkTunnelFrame(bytes);
|
||||
} catch (error) {
|
||||
this.wire.close();
|
||||
this.handleWireClosed(error instanceof Error ? error : new Error(String(error)));
|
||||
return;
|
||||
}
|
||||
|
||||
switch (frame.type) {
|
||||
case "ping":
|
||||
this.sendFrameBestEffort({ type: "pong", payload: frame.payload });
|
||||
return;
|
||||
|
||||
case "pong":
|
||||
return;
|
||||
|
||||
case "opened":
|
||||
this.handleOpened(frame);
|
||||
return;
|
||||
|
||||
case "data":
|
||||
this.handleData(frame);
|
||||
return;
|
||||
|
||||
case "window_update":
|
||||
this.handleWindowUpdate(frame);
|
||||
return;
|
||||
|
||||
case "half_close":
|
||||
this.handleRemoteHalfClose(frame.streamId);
|
||||
return;
|
||||
|
||||
case "close":
|
||||
this.handleRemoteClose(frame);
|
||||
return;
|
||||
|
||||
case "open":
|
||||
// Client never accepts inbound Open frames.
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private handleOpened(frame: Extract<DecodedNetworkTunnelFrame, { type: "opened" }>): void {
|
||||
const stream = this.streams.get(frame.streamId);
|
||||
if (!stream || stream.state !== "opening") {
|
||||
return;
|
||||
}
|
||||
stream.state = "open";
|
||||
stream.sendWindow = frame.initialWindowBytes;
|
||||
|
||||
// Notify caller (writes SOCKS5 reply) BEFORE attaching inbound/outbound piping.
|
||||
try {
|
||||
stream.onOpened?.();
|
||||
} catch {
|
||||
this.closeStreamLocally(stream, NetworkTunnelCloseReason.InternalError);
|
||||
stream.pendingOpenResolve?.({
|
||||
ok: false,
|
||||
reason: NetworkTunnelCloseReason.InternalError,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
this.attachSocketToStream(stream);
|
||||
stream.pendingOpenResolve?.({ ok: true });
|
||||
this.flushOutbound(stream);
|
||||
}
|
||||
|
||||
private attachSocketToStream(stream: ActiveStream): void {
|
||||
const { socket } = stream;
|
||||
|
||||
const onData = (chunk: Buffer | string) => {
|
||||
if (stream.state !== "open") return;
|
||||
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
if (buf.length === 0) return;
|
||||
stream.outboundQueue.push(buf);
|
||||
this.flushOutbound(stream);
|
||||
};
|
||||
|
||||
const onDrain = () => {
|
||||
if (this.closed || stream.state !== "open") return;
|
||||
if (stream.pendingDrainBytes > 0) {
|
||||
const drained = stream.pendingDrainBytes;
|
||||
stream.pendingDrainBytes = 0;
|
||||
this.recordInboundConsumed(stream, drained);
|
||||
}
|
||||
};
|
||||
|
||||
const onEnd = () => {
|
||||
if (stream.state !== "open" || stream.localHalfClosed) return;
|
||||
stream.localHalfClosed = true;
|
||||
this.flushOutbound(stream);
|
||||
};
|
||||
|
||||
const onError = () => {
|
||||
this.closeStreamLocally(stream, NetworkTunnelCloseReason.Reset);
|
||||
};
|
||||
|
||||
const onClose = () => {
|
||||
if (stream.state === "open") {
|
||||
this.closeStreamLocally(
|
||||
stream,
|
||||
stream.localHalfClosed && stream.remoteHalfClosed
|
||||
? NetworkTunnelCloseReason.Normal
|
||||
: NetworkTunnelCloseReason.Reset,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
socket.on("data", onData);
|
||||
socket.on("drain", onDrain);
|
||||
socket.on("end", onEnd);
|
||||
socket.on("error", onError);
|
||||
socket.on("close", onClose);
|
||||
|
||||
stream.cleanupSocketListeners = () => {
|
||||
socket.off("data", onData);
|
||||
socket.off("drain", onDrain);
|
||||
socket.off("end", onEnd);
|
||||
socket.off("error", onError);
|
||||
socket.off("close", onClose);
|
||||
};
|
||||
}
|
||||
|
||||
private flushOutbound(stream: ActiveStream): void {
|
||||
if (stream.state !== "open" || this.closed) {
|
||||
return;
|
||||
}
|
||||
|
||||
while (stream.outboundQueue.length > 0) {
|
||||
const available = Math.min(stream.sendWindow, this.sendConnWindow, this.maxFramePayloadBytes);
|
||||
if (available <= 0) {
|
||||
if (!stream.socketPaused) {
|
||||
stream.socketPaused = true;
|
||||
stream.socket.pause();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const head = stream.outboundQueue[0]!;
|
||||
let slice: Buffer;
|
||||
if (head.length <= available) {
|
||||
slice = stream.outboundQueue.shift()!;
|
||||
} else {
|
||||
slice = head.subarray(0, available);
|
||||
stream.outboundQueue[0] = head.subarray(available);
|
||||
}
|
||||
|
||||
stream.sendWindow -= slice.length;
|
||||
this.sendConnWindow -= slice.length;
|
||||
|
||||
this.sendFrameBestEffort({
|
||||
type: "data",
|
||||
streamId: stream.streamId,
|
||||
data: slice,
|
||||
});
|
||||
}
|
||||
|
||||
if (stream.socketPaused && stream.sendWindow > 0 && this.sendConnWindow > 0) {
|
||||
stream.socketPaused = false;
|
||||
stream.socket.resume();
|
||||
}
|
||||
|
||||
if (stream.localHalfClosed && !stream.localHalfCloseSent && stream.outboundQueue.length === 0) {
|
||||
stream.localHalfCloseSent = true;
|
||||
this.sendFrameBestEffort({
|
||||
type: "half_close",
|
||||
streamId: stream.streamId,
|
||||
});
|
||||
if (stream.remoteHalfClosed) {
|
||||
this.closeStreamLocally(stream, NetworkTunnelCloseReason.Normal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private flushAllOutbound(): void {
|
||||
for (const stream of this.streams.values()) {
|
||||
if (stream.state === "open") {
|
||||
this.flushOutbound(stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private handleData(frame: Extract<DecodedNetworkTunnelFrame, { type: "data" }>): void {
|
||||
const stream = this.streams.get(frame.streamId);
|
||||
if (!stream || stream.state !== "open") {
|
||||
return;
|
||||
}
|
||||
if (frame.data.byteLength === 0) {
|
||||
return;
|
||||
}
|
||||
if (stream.socket.destroyed || !stream.socket.writable) {
|
||||
this.closeStreamLocally(stream, NetworkTunnelCloseReason.Reset);
|
||||
return;
|
||||
}
|
||||
|
||||
const byteLength = frame.data.byteLength;
|
||||
const canContinue = stream.socket.write(frame.data);
|
||||
if (canContinue && stream.pendingDrainBytes === 0) {
|
||||
this.recordInboundConsumed(stream, byteLength);
|
||||
} else {
|
||||
stream.pendingDrainBytes += byteLength;
|
||||
}
|
||||
}
|
||||
|
||||
private flushConnectionRecvWindow(): void {
|
||||
if (this.closed) return;
|
||||
|
||||
const connThreshold = Math.max(1, Math.floor(this.initialConnectionWindowBytes / 2));
|
||||
if (this.recvConnConsumed >= connThreshold) {
|
||||
const credit = this.recvConnConsumed;
|
||||
this.recvConnConsumed = 0;
|
||||
this.sendFrameBestEffort({
|
||||
type: "window_update",
|
||||
streamId: 0,
|
||||
creditBytes: credit,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private recordInboundConsumed(stream: ActiveStream, bytes: number): void {
|
||||
if (this.closed) return;
|
||||
|
||||
this.recvConnConsumed += bytes;
|
||||
this.flushConnectionRecvWindow();
|
||||
|
||||
if (stream.state === "open") {
|
||||
stream.recvConsumed += bytes;
|
||||
const streamThreshold = Math.max(1, Math.floor(stream.recvWindowLimit / 2));
|
||||
if (stream.recvConsumed >= streamThreshold) {
|
||||
const credit = stream.recvConsumed;
|
||||
stream.recvConsumed = 0;
|
||||
this.sendFrameBestEffort({
|
||||
type: "window_update",
|
||||
streamId: stream.streamId,
|
||||
creditBytes: credit,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private handleWindowUpdate(
|
||||
frame: Extract<DecodedNetworkTunnelFrame, { type: "window_update" }>,
|
||||
): void {
|
||||
if (frame.streamId === 0) {
|
||||
this.sendConnWindow += frame.creditBytes;
|
||||
this.flushAllOutbound();
|
||||
return;
|
||||
}
|
||||
const stream = this.streams.get(frame.streamId);
|
||||
if (!stream || stream.state !== "open") {
|
||||
return;
|
||||
}
|
||||
stream.sendWindow += frame.creditBytes;
|
||||
this.flushOutbound(stream);
|
||||
}
|
||||
|
||||
private handleRemoteHalfClose(streamId: number): void {
|
||||
const stream = this.streams.get(streamId);
|
||||
if (!stream || stream.state !== "open") {
|
||||
return;
|
||||
}
|
||||
stream.remoteHalfClosed = true;
|
||||
if (!stream.socket.destroyed && stream.socket.writable) {
|
||||
stream.socket.end();
|
||||
}
|
||||
if (stream.localHalfCloseSent) {
|
||||
this.cleanupStream(stream);
|
||||
}
|
||||
}
|
||||
|
||||
private handleRemoteClose(frame: Extract<DecodedNetworkTunnelFrame, { type: "close" }>): void {
|
||||
const stream = this.streams.get(frame.streamId);
|
||||
if (!stream) {
|
||||
return;
|
||||
}
|
||||
if (stream.state === "opening") {
|
||||
this.streams.delete(frame.streamId);
|
||||
stream.state = "closed";
|
||||
stream.pendingOpenResolve?.({
|
||||
ok: false,
|
||||
reason: frame.reason,
|
||||
...(frame.message !== undefined ? { message: frame.message } : {}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.cleanupStream(stream);
|
||||
if (!stream.socket.destroyed) {
|
||||
if (frame.reason === NetworkTunnelCloseReason.Normal) {
|
||||
stream.socket.end();
|
||||
} else {
|
||||
stream.socket.destroy();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private closeStreamLocally(stream: ActiveStream, reason: NetworkTunnelCloseReason): void {
|
||||
if (stream.state === "closed") {
|
||||
return;
|
||||
}
|
||||
const streamId = stream.streamId;
|
||||
this.cleanupStream(stream);
|
||||
this.sendFrameBestEffort({
|
||||
type: "close",
|
||||
streamId,
|
||||
reason,
|
||||
});
|
||||
}
|
||||
|
||||
private cleanupStream(stream: ActiveStream): void {
|
||||
if (stream.state === "closed") {
|
||||
return;
|
||||
}
|
||||
stream.state = "closed";
|
||||
stream.outboundQueue.length = 0;
|
||||
stream.cleanupSocketListeners?.();
|
||||
stream.cleanupSocketListeners = undefined;
|
||||
this.streams.delete(stream.streamId);
|
||||
|
||||
// Never leak connection-level receive credit when a stream closes with un-drained bytes.
|
||||
if (stream.pendingDrainBytes > 0) {
|
||||
this.recvConnConsumed += stream.pendingDrainBytes;
|
||||
stream.pendingDrainBytes = 0;
|
||||
this.flushConnectionRecvWindow();
|
||||
}
|
||||
}
|
||||
|
||||
private handleWireClosed(error?: Error): void {
|
||||
if (this.closed) {
|
||||
return;
|
||||
}
|
||||
this.closed = true;
|
||||
if (this.heartbeatTimer) {
|
||||
clearInterval(this.heartbeatTimer);
|
||||
this.heartbeatTimer = null;
|
||||
}
|
||||
this.unsubBinary();
|
||||
this.unsubClose();
|
||||
|
||||
for (const stream of this.streams.values()) {
|
||||
const wasOpening = stream.state === "opening";
|
||||
this.cleanupStream(stream);
|
||||
if (wasOpening) {
|
||||
stream.pendingOpenResolve?.({
|
||||
ok: false,
|
||||
reason: NetworkTunnelCloseReason.HostUnreachable,
|
||||
message: error?.message ?? "Tunnel connection closed",
|
||||
});
|
||||
} else if (!stream.socket.destroyed) {
|
||||
stream.socket.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
for (const listener of this.closeListeners) {
|
||||
listener(error);
|
||||
}
|
||||
this.closeListeners.clear();
|
||||
}
|
||||
}
|
||||
@@ -1,582 +0,0 @@
|
||||
import {
|
||||
buildRelayWebSocketUrl,
|
||||
shouldUseTlsForDefaultHostedRelay,
|
||||
} from "@getpaseo/protocol/daemon-endpoints";
|
||||
import {
|
||||
WSTunnelHandshakeResponseSchema,
|
||||
type WSTunnelHandshakeResponse,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import {
|
||||
openClientSecureChannel,
|
||||
type SecureChannel,
|
||||
type Transport as RelayClientTransport,
|
||||
} from "@getpaseo/relay/e2ee";
|
||||
import { WebSocket, type RawData } from "ws";
|
||||
import { createSshProxy } from "../../../daemon/ssh-proxy.js";
|
||||
|
||||
export type BrowserProxyTarget =
|
||||
| {
|
||||
type: "directTcp";
|
||||
endpoint: string;
|
||||
useTls?: boolean;
|
||||
}
|
||||
| {
|
||||
type: "remoteSsh";
|
||||
host: string;
|
||||
sshPort?: number;
|
||||
daemonPort?: number;
|
||||
}
|
||||
| {
|
||||
type: "relay";
|
||||
serverId: string;
|
||||
relayEndpoint: string;
|
||||
useTls?: boolean;
|
||||
daemonPublicKeyB64: string;
|
||||
minimumSecurityMode?: "protected";
|
||||
};
|
||||
|
||||
export interface TunnelReadyLimits {
|
||||
maxFramePayloadBytes: number;
|
||||
initialStreamWindowBytes: number;
|
||||
initialConnectionWindowBytes: number;
|
||||
}
|
||||
|
||||
export interface TunnelWireConnection {
|
||||
readonly ready: TunnelReadyLimits;
|
||||
sendBinary(bytes: Uint8Array): Promise<void>;
|
||||
onBinary(handler: (bytes: Uint8Array) => void): () => void;
|
||||
onClose(handler: (error?: Error) => void): () => void;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
export class TunnelHandshakeError extends Error {
|
||||
public readonly code: string;
|
||||
|
||||
public constructor(code: string, message: string) {
|
||||
super(message);
|
||||
this.name = "TunnelHandshakeError";
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULT_CONNECT_TIMEOUT_MS = 15_000;
|
||||
const WS_ENDPOINT_PATH = "/ws";
|
||||
|
||||
function rawDataToUint8Array(data: RawData): Uint8Array {
|
||||
if (Buffer.isBuffer(data)) {
|
||||
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
||||
}
|
||||
if (Array.isArray(data)) {
|
||||
const joined = Buffer.concat(data);
|
||||
return new Uint8Array(joined.buffer, joined.byteOffset, joined.byteLength);
|
||||
}
|
||||
return new Uint8Array(data);
|
||||
}
|
||||
|
||||
function buildDirectTcpWebSocketUrl(
|
||||
target: Extract<BrowserProxyTarget, { type: "directTcp" }>,
|
||||
): string {
|
||||
const trimmed = target.endpoint.trim().replace(/\/+$/u, "");
|
||||
if (!trimmed) {
|
||||
throw new Error("Direct TCP endpoint is required");
|
||||
}
|
||||
if (/^wss?:\/\//iu.test(trimmed)) {
|
||||
return trimmed.endsWith(WS_ENDPOINT_PATH) ? trimmed : `${trimmed}${WS_ENDPOINT_PATH}`;
|
||||
}
|
||||
const scheme = target.useTls ? "wss" : "ws";
|
||||
return `${scheme}://${trimmed}${WS_ENDPOINT_PATH}`;
|
||||
}
|
||||
|
||||
function waitForWebSocketOpen(
|
||||
ws: WebSocket,
|
||||
timeoutMs: number,
|
||||
getFailureDetail?: () => string | null,
|
||||
): Promise<void> {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
cleanup();
|
||||
try {
|
||||
ws.terminate();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
reject(new Error("Timed out connecting tunnel WebSocket"));
|
||||
}, timeoutMs);
|
||||
timer.unref?.();
|
||||
|
||||
const onOpen = () => {
|
||||
cleanup();
|
||||
resolve();
|
||||
};
|
||||
const onError = (error: Error) => {
|
||||
cleanup();
|
||||
const detail = getFailureDetail?.();
|
||||
reject(new Error(detail ? `${error.message}: ${detail}` : error.message));
|
||||
};
|
||||
const onClose = (code: number, reason: Buffer) => {
|
||||
cleanup();
|
||||
const detail = getFailureDetail?.();
|
||||
let suffix = "";
|
||||
if (detail) {
|
||||
suffix = `: ${detail}`;
|
||||
} else if (reason.length > 0) {
|
||||
suffix = `: ${reason.toString("utf8")}`;
|
||||
}
|
||||
reject(new Error(`Tunnel WebSocket closed before open (${code})${suffix}`));
|
||||
};
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
ws.off("open", onOpen);
|
||||
ws.off("error", onError);
|
||||
ws.off("close", onClose);
|
||||
};
|
||||
|
||||
ws.once("open", onOpen);
|
||||
ws.once("error", onError);
|
||||
ws.once("close", onClose);
|
||||
});
|
||||
}
|
||||
|
||||
async function openPlainWebSocketTunnel(input: {
|
||||
url: string;
|
||||
ticket: string;
|
||||
timeoutMs: number;
|
||||
cleanupTarget?: () => void;
|
||||
getFailureDetail?: () => string | null;
|
||||
}): Promise<TunnelWireConnection> {
|
||||
const ws = new WebSocket(input.url, { perMessageDeflate: false });
|
||||
try {
|
||||
await waitForWebSocketOpen(ws, input.timeoutMs, input.getFailureDetail);
|
||||
} catch (error) {
|
||||
input.cleanupTarget?.();
|
||||
throw error;
|
||||
}
|
||||
|
||||
const binaryListeners = new Set<(bytes: Uint8Array) => void>();
|
||||
const closeListeners = new Set<(error?: Error) => void>();
|
||||
let closed = false;
|
||||
let handshakeDone = false;
|
||||
|
||||
const notifyClose = (error?: Error) => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
input.cleanupTarget?.();
|
||||
for (const listener of closeListeners) {
|
||||
listener(error);
|
||||
}
|
||||
closeListeners.clear();
|
||||
binaryListeners.clear();
|
||||
};
|
||||
|
||||
let resolveHandshake!: (response: WSTunnelHandshakeResponse) => void;
|
||||
let rejectHandshake!: (error: Error) => void;
|
||||
const handshakePromise = new Promise<WSTunnelHandshakeResponse>((resolve, reject) => {
|
||||
resolveHandshake = resolve;
|
||||
rejectHandshake = reject;
|
||||
});
|
||||
|
||||
const handshakeTimer = setTimeout(() => {
|
||||
if (!handshakeDone) {
|
||||
handshakeDone = true;
|
||||
rejectHandshake(new Error("Timed out waiting for tunnel_ready handshake"));
|
||||
try {
|
||||
ws.terminate();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
notifyClose(new Error("Tunnel handshake timeout"));
|
||||
}
|
||||
}, input.timeoutMs);
|
||||
handshakeTimer.unref?.();
|
||||
|
||||
ws.on("message", (data: RawData, isBinary: boolean) => {
|
||||
if (!handshakeDone) {
|
||||
if (isBinary) {
|
||||
handshakeDone = true;
|
||||
clearTimeout(handshakeTimer);
|
||||
rejectHandshake(new Error("Received binary frame before tunnel_ready handshake"));
|
||||
ws.close();
|
||||
return;
|
||||
}
|
||||
const text = Buffer.isBuffer(data) ? data.toString("utf8") : String(data);
|
||||
try {
|
||||
const parsed = WSTunnelHandshakeResponseSchema.parse(JSON.parse(text));
|
||||
handshakeDone = true;
|
||||
clearTimeout(handshakeTimer);
|
||||
resolveHandshake(parsed);
|
||||
} catch (error) {
|
||||
handshakeDone = true;
|
||||
clearTimeout(handshakeTimer);
|
||||
rejectHandshake(
|
||||
error instanceof Error ? error : new Error("Invalid tunnel handshake response"),
|
||||
);
|
||||
ws.close();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isBinary) {
|
||||
// Ignore unexpected text after entering binary mode.
|
||||
return;
|
||||
}
|
||||
const bytes = rawDataToUint8Array(data);
|
||||
for (const listener of binaryListeners) {
|
||||
listener(bytes);
|
||||
}
|
||||
});
|
||||
|
||||
ws.on("error", (error) => {
|
||||
if (!handshakeDone) {
|
||||
handshakeDone = true;
|
||||
clearTimeout(handshakeTimer);
|
||||
rejectHandshake(error);
|
||||
}
|
||||
notifyClose(error);
|
||||
});
|
||||
|
||||
ws.on("close", (code, reason) => {
|
||||
const detail = reason.length > 0 ? reason.toString("utf8") : `code ${code}`;
|
||||
const err = new Error(`Tunnel closed (${detail})`);
|
||||
if (!handshakeDone) {
|
||||
handshakeDone = true;
|
||||
clearTimeout(handshakeTimer);
|
||||
rejectHandshake(err);
|
||||
}
|
||||
notifyClose(err);
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
ws.send(JSON.stringify({ type: "tunnel_hello", ticket: input.ticket }), (err) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
const handshake = await handshakePromise;
|
||||
if (handshake.type === "tunnel_error") {
|
||||
ws.close();
|
||||
notifyClose(new TunnelHandshakeError(handshake.code, handshake.message));
|
||||
throw new TunnelHandshakeError(handshake.code, handshake.message);
|
||||
}
|
||||
|
||||
return {
|
||||
ready: {
|
||||
maxFramePayloadBytes: handshake.maxFramePayloadBytes,
|
||||
initialStreamWindowBytes: handshake.initialStreamWindowBytes,
|
||||
initialConnectionWindowBytes: handshake.initialConnectionWindowBytes,
|
||||
},
|
||||
sendBinary: (bytes) =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
if (closed || ws.readyState !== WebSocket.OPEN) {
|
||||
reject(new Error("Tunnel WebSocket is not open"));
|
||||
return;
|
||||
}
|
||||
ws.send(bytes, { binary: true }, (err) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
}),
|
||||
onBinary: (handler) => {
|
||||
binaryListeners.add(handler);
|
||||
return () => {
|
||||
binaryListeners.delete(handler);
|
||||
};
|
||||
},
|
||||
onClose: (handler) => {
|
||||
if (closed) {
|
||||
handler();
|
||||
return () => {};
|
||||
}
|
||||
closeListeners.add(handler);
|
||||
return () => {
|
||||
closeListeners.delete(handler);
|
||||
};
|
||||
},
|
||||
close: () => {
|
||||
if (closed) return;
|
||||
try {
|
||||
if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
|
||||
ws.close();
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
notifyClose();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function openRelayE2eeTunnel(input: {
|
||||
target: Extract<BrowserProxyTarget, { type: "relay" }>;
|
||||
ticket: string;
|
||||
timeoutMs: number;
|
||||
}): Promise<TunnelWireConnection> {
|
||||
const wsUrl = buildRelayWebSocketUrl({
|
||||
endpoint: input.target.relayEndpoint,
|
||||
useTls: input.target.useTls ?? shouldUseTlsForDefaultHostedRelay(input.target.relayEndpoint),
|
||||
serverId: input.target.serverId,
|
||||
role: "client",
|
||||
});
|
||||
const rawWs = new WebSocket(wsUrl, { perMessageDeflate: false });
|
||||
await waitForWebSocketOpen(rawWs, input.timeoutMs);
|
||||
|
||||
const binaryListeners = new Set<(bytes: Uint8Array) => void>();
|
||||
const closeListeners = new Set<(error?: Error) => void>();
|
||||
let closed = false;
|
||||
let handshakeDone = false;
|
||||
let channel: SecureChannel | null = null;
|
||||
|
||||
const notifyClose = (error?: Error) => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
for (const listener of closeListeners) {
|
||||
listener(error);
|
||||
}
|
||||
closeListeners.clear();
|
||||
binaryListeners.clear();
|
||||
};
|
||||
|
||||
let resolveHandshake!: (response: WSTunnelHandshakeResponse) => void;
|
||||
let rejectHandshake!: (error: Error) => void;
|
||||
const handshakePromise = new Promise<WSTunnelHandshakeResponse>((resolve, reject) => {
|
||||
resolveHandshake = resolve;
|
||||
rejectHandshake = reject;
|
||||
});
|
||||
|
||||
const transport: RelayClientTransport = {
|
||||
send: (data) =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
if (rawWs.readyState !== WebSocket.OPEN) {
|
||||
reject(new Error("Relay tunnel WebSocket is not open"));
|
||||
return;
|
||||
}
|
||||
rawWs.send(data, (err) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
}),
|
||||
close: (code, reason) => {
|
||||
try {
|
||||
rawWs.close(code, reason);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
},
|
||||
onmessage: null,
|
||||
onclose: null,
|
||||
onerror: null,
|
||||
};
|
||||
|
||||
rawWs.on("message", (data: RawData, isBinary: boolean) => {
|
||||
if (!isBinary) {
|
||||
const text = Buffer.isBuffer(data) ? data.toString("utf8") : String(data);
|
||||
transport.onmessage?.({ data: text, isBinary: false });
|
||||
return;
|
||||
}
|
||||
const bytes = rawDataToUint8Array(data);
|
||||
const copy = new Uint8Array(bytes.byteLength);
|
||||
copy.set(bytes);
|
||||
transport.onmessage?.({ data: copy.buffer, isBinary: true });
|
||||
});
|
||||
rawWs.on("close", (code, reason) => {
|
||||
const detail = reason.toString("utf8");
|
||||
transport.onclose?.(code, detail);
|
||||
const err = new Error(`Relay tunnel closed (${code}${detail ? `: ${detail}` : ""})`);
|
||||
if (!handshakeDone) {
|
||||
handshakeDone = true;
|
||||
rejectHandshake(err);
|
||||
}
|
||||
notifyClose(err);
|
||||
});
|
||||
rawWs.on("error", (error) => {
|
||||
transport.onerror?.(error);
|
||||
if (!handshakeDone) {
|
||||
handshakeDone = true;
|
||||
rejectHandshake(error);
|
||||
}
|
||||
notifyClose(error);
|
||||
});
|
||||
|
||||
const handshakeTimer = setTimeout(() => {
|
||||
if (!handshakeDone) {
|
||||
handshakeDone = true;
|
||||
rejectHandshake(new Error("Timed out waiting for encrypted relay tunnel handshake"));
|
||||
try {
|
||||
rawWs.terminate();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
notifyClose(new Error("Relay tunnel handshake timeout"));
|
||||
}
|
||||
}, input.timeoutMs);
|
||||
handshakeTimer.unref?.();
|
||||
|
||||
try {
|
||||
channel = await openClientSecureChannel(transport, {
|
||||
daemonPublicKeyB64: input.target.daemonPublicKeyB64,
|
||||
...(input.target.minimumSecurityMode
|
||||
? { minimumMode: input.target.minimumSecurityMode }
|
||||
: {}),
|
||||
events: {
|
||||
onmessage: (data) => {
|
||||
if (!handshakeDone) {
|
||||
if (typeof data !== "string") {
|
||||
handshakeDone = true;
|
||||
clearTimeout(handshakeTimer);
|
||||
rejectHandshake(new Error("Received binary frame before tunnel_ready handshake"));
|
||||
channel?.close();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const parsed = WSTunnelHandshakeResponseSchema.parse(JSON.parse(data));
|
||||
handshakeDone = true;
|
||||
clearTimeout(handshakeTimer);
|
||||
resolveHandshake(parsed);
|
||||
} catch (error) {
|
||||
handshakeDone = true;
|
||||
clearTimeout(handshakeTimer);
|
||||
rejectHandshake(
|
||||
error instanceof Error ? error : new Error("Invalid tunnel handshake response"),
|
||||
);
|
||||
channel?.close();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof data === "string") {
|
||||
return;
|
||||
}
|
||||
const bytes = new Uint8Array(data);
|
||||
for (const listener of binaryListeners) {
|
||||
listener(bytes);
|
||||
}
|
||||
},
|
||||
onclose: (code, reason) => {
|
||||
const err = new Error(`Relay E2EE tunnel closed (${code}${reason ? `: ${reason}` : ""})`);
|
||||
if (!handshakeDone) {
|
||||
handshakeDone = true;
|
||||
clearTimeout(handshakeTimer);
|
||||
rejectHandshake(err);
|
||||
}
|
||||
notifyClose(err);
|
||||
},
|
||||
onerror: (error) => {
|
||||
if (!handshakeDone) {
|
||||
handshakeDone = true;
|
||||
clearTimeout(handshakeTimer);
|
||||
rejectHandshake(error);
|
||||
}
|
||||
notifyClose(error);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await channel.send(JSON.stringify({ type: "tunnel_hello", ticket: input.ticket }));
|
||||
const handshake = await handshakePromise;
|
||||
clearTimeout(handshakeTimer);
|
||||
|
||||
if (handshake.type === "tunnel_error") {
|
||||
channel.close();
|
||||
notifyClose(new TunnelHandshakeError(handshake.code, handshake.message));
|
||||
throw new TunnelHandshakeError(handshake.code, handshake.message);
|
||||
}
|
||||
|
||||
const activeChannel = channel;
|
||||
return {
|
||||
ready: {
|
||||
maxFramePayloadBytes: handshake.maxFramePayloadBytes,
|
||||
initialStreamWindowBytes: handshake.initialStreamWindowBytes,
|
||||
initialConnectionWindowBytes: handshake.initialConnectionWindowBytes,
|
||||
},
|
||||
sendBinary: async (bytes) => {
|
||||
if (closed) {
|
||||
throw new Error("Relay tunnel channel is closed");
|
||||
}
|
||||
const copy = new Uint8Array(bytes.byteLength);
|
||||
copy.set(bytes);
|
||||
await activeChannel.send(copy.buffer);
|
||||
},
|
||||
onBinary: (handler) => {
|
||||
binaryListeners.add(handler);
|
||||
return () => {
|
||||
binaryListeners.delete(handler);
|
||||
};
|
||||
},
|
||||
onClose: (handler) => {
|
||||
if (closed) {
|
||||
handler();
|
||||
return () => {};
|
||||
}
|
||||
closeListeners.add(handler);
|
||||
return () => {
|
||||
closeListeners.delete(handler);
|
||||
};
|
||||
},
|
||||
close: () => {
|
||||
if (closed) return;
|
||||
try {
|
||||
activeChannel.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
notifyClose();
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
clearTimeout(handshakeTimer);
|
||||
try {
|
||||
channel?.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
try {
|
||||
rawWs.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function openTunnelWireConnection(input: {
|
||||
target: BrowserProxyTarget;
|
||||
ticket: string;
|
||||
timeoutMs?: number;
|
||||
}): Promise<TunnelWireConnection> {
|
||||
const timeoutMs = input.timeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
|
||||
const { target, ticket } = input;
|
||||
|
||||
if (target.type === "directTcp") {
|
||||
return await openPlainWebSocketTunnel({
|
||||
url: buildDirectTcpWebSocketUrl(target),
|
||||
ticket,
|
||||
timeoutMs,
|
||||
});
|
||||
}
|
||||
|
||||
if (target.type === "remoteSsh") {
|
||||
const sshEndpoint = await createSshProxy({
|
||||
host: target.host,
|
||||
...(target.sshPort !== undefined ? { sshPort: target.sshPort } : {}),
|
||||
...(target.daemonPort !== undefined ? { daemonPort: target.daemonPort } : {}),
|
||||
});
|
||||
return await openPlainWebSocketTunnel({
|
||||
url: sshEndpoint.url,
|
||||
ticket,
|
||||
timeoutMs,
|
||||
cleanupTarget: sshEndpoint.close,
|
||||
getFailureDetail: sshEndpoint.failureDetail,
|
||||
});
|
||||
}
|
||||
|
||||
return await openRelayE2eeTunnel({ target, ticket, timeoutMs });
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
export {
|
||||
getHostBrowserProxyPartition,
|
||||
isHostBrowserProxyPartition,
|
||||
PASEO_BROWSER_HOST_PARTITION_PREFIX,
|
||||
} from "./internal/partition.js";
|
||||
@@ -1,6 +1,5 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { PASEO_BROWSER_PROFILE_PARTITION } from "../browser-profile.js";
|
||||
import { getHostBrowserProxyPartition } from "../browser-proxy/partition.js";
|
||||
import {
|
||||
getPaseoBrowserIdForWebContents,
|
||||
getPaseoBrowserWorkspaceId,
|
||||
@@ -45,69 +44,24 @@ class FakeBrowserGuest {
|
||||
}
|
||||
|
||||
describe("browser webview attachment", () => {
|
||||
test("accepts only allowed URLs on the shared profile or registered host proxy partitions", () => {
|
||||
const hostPartition = getHostBrowserProxyPartition("remote-host-a");
|
||||
const unregisteredHostPartition = getHostBrowserProxyPartition("remote-host-b");
|
||||
const isAllowedHostPartition = (partition: string) => partition === hostPartition;
|
||||
|
||||
test("accepts only allowed URLs on the shared profile partition", () => {
|
||||
expect(
|
||||
isPaseoBrowserWebviewAttach({
|
||||
src: "https://example.com",
|
||||
partition: PASEO_BROWSER_PROFILE_PARTITION,
|
||||
isAllowedHostPartition,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isPaseoBrowserWebviewAttach({
|
||||
src: "http://localhost:3000",
|
||||
partition: hostPartition,
|
||||
isAllowedHostPartition,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isPaseoBrowserWebviewAttach({
|
||||
src: "http://localhost:3000",
|
||||
partition: unregisteredHostPartition,
|
||||
isAllowedHostPartition,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isPaseoBrowserWebviewAttach({
|
||||
src: "https://example.com",
|
||||
partition: "persist:paseo-browser-tab-a",
|
||||
isAllowedHostPartition,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isPaseoBrowserWebviewAttach({
|
||||
src: "https://example.com",
|
||||
partition: "persist:foreign",
|
||||
isAllowedHostPartition,
|
||||
}),
|
||||
isPaseoBrowserWebviewAttach({ src: "https://example.com", partition: "persist:foreign" }),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("registers a guest attached to an allowed host proxy session", () => {
|
||||
const localSession = {};
|
||||
const proxiedSession = {};
|
||||
const renderer = new FakeRenderer(9);
|
||||
const guest = new FakeBrowserGuest(901, renderer, proxiedSession);
|
||||
|
||||
const registered = registerAttachedPaseoBrowser({
|
||||
browserId: "browser-proxied",
|
||||
workspaceId: "workspace-remote",
|
||||
webContentsId: guest.id,
|
||||
sender: renderer,
|
||||
profileSession: localSession,
|
||||
isAllowedSession: (session) => session === proxiedSession,
|
||||
findWebContents: () => guest,
|
||||
});
|
||||
|
||||
expect(registered).toBe(true);
|
||||
expect(getPaseoBrowserIdForWebContents(guest)).toBe("browser-proxied");
|
||||
unregisterPaseoBrowser("browser-proxied");
|
||||
});
|
||||
|
||||
test("binds explicit browser identity to the renderer that hosts the guest", () => {
|
||||
const profileSession = {};
|
||||
const renderer = new FakeRenderer(1);
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import { webContents as allWebContents, type WebContents } from "electron";
|
||||
import { PASEO_BROWSER_PROFILE_PARTITION } from "../browser-profile.js";
|
||||
import { isHostBrowserProxyPartition } from "../browser-proxy/partition.js";
|
||||
import {
|
||||
BROWSER_NEW_TAB_REQUEST_EVENT,
|
||||
buildBrowserPopupWebPreferences,
|
||||
decideBrowserWindowOpenRequest,
|
||||
isAllowedBrowserWebviewUrl,
|
||||
PendingBrowserWindowOpenRequests,
|
||||
@@ -12,7 +10,6 @@ import { PaseoBrowserWebviewRegistry } from "./registry.js";
|
||||
|
||||
export {
|
||||
BROWSER_NEW_TAB_REQUEST_EVENT,
|
||||
buildBrowserPopupWebPreferences,
|
||||
decideBrowserWindowOpenRequest,
|
||||
PendingBrowserWindowOpenRequests,
|
||||
};
|
||||
@@ -39,24 +36,12 @@ interface AttachedBrowserRegistration {
|
||||
interface RegisterAttachedBrowserInput extends AttachedBrowserRegistration {
|
||||
sender: BrowserWebContentsIdentity;
|
||||
profileSession: object;
|
||||
isAllowedSession?: (session: object) => boolean;
|
||||
findWebContents(webContentsId: number): RegisteredBrowserWebContents | null;
|
||||
}
|
||||
|
||||
export function isPaseoBrowserWebviewAttach(input: {
|
||||
src?: string;
|
||||
partition?: string;
|
||||
isAllowedHostPartition?: (partition: string) => boolean;
|
||||
}): boolean {
|
||||
if (!isAllowedBrowserWebviewUrl(input.src)) {
|
||||
return false;
|
||||
}
|
||||
if (input.partition === PASEO_BROWSER_PROFILE_PARTITION) {
|
||||
return true;
|
||||
}
|
||||
export function isPaseoBrowserWebviewAttach(input: { src?: string; partition?: string }): boolean {
|
||||
return (
|
||||
isHostBrowserProxyPartition(input.partition) &&
|
||||
(input.isAllowedHostPartition?.(input.partition) ?? false)
|
||||
isAllowedBrowserWebviewUrl(input.src) && input.partition === PASEO_BROWSER_PROFILE_PARTITION
|
||||
);
|
||||
}
|
||||
|
||||
@@ -79,10 +64,12 @@ export function preparePaseoBrowserWebContents(contents: RegisteredBrowserWebCon
|
||||
|
||||
export function registerAttachedPaseoBrowser(input: RegisterAttachedBrowserInput): boolean {
|
||||
const guest = input.findWebContents(input.webContentsId);
|
||||
const sessionAllowed =
|
||||
guest !== null &&
|
||||
(guest.session === input.profileSession || (input.isAllowedSession?.(guest.session) ?? false));
|
||||
if (!guest || guest.isDestroyed() || guest.hostWebContents !== input.sender || !sessionAllowed) {
|
||||
if (
|
||||
!guest ||
|
||||
guest.isDestroyed() ||
|
||||
guest.hostWebContents !== input.sender ||
|
||||
guest.session !== input.profileSession
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
buildBrowserPopupWebPreferences,
|
||||
decideBrowserWindowOpenRequest,
|
||||
PendingBrowserWindowOpenRequests,
|
||||
} from ".";
|
||||
import { decideBrowserWindowOpenRequest, PendingBrowserWindowOpenRequests } from ".";
|
||||
|
||||
describe("browser webview window-open requests", () => {
|
||||
it("routes foreground tabs to a Paseo workspace tab", () => {
|
||||
@@ -178,16 +174,3 @@ describe("pending browser window-open requests", () => {
|
||||
expect(pending.take(202)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildBrowserPopupWebPreferences", () => {
|
||||
it("inherits the opener guest session instead of hardcoding a partition", () => {
|
||||
const openerSession = { id: "proxied-host-session" };
|
||||
const prefs = buildBrowserPopupWebPreferences(openerSession);
|
||||
|
||||
expect(prefs.session).toBe(openerSession);
|
||||
expect("partition" in prefs).toBe(false);
|
||||
expect(prefs.sandbox).toBe(true);
|
||||
expect(prefs.contextIsolation).toBe(true);
|
||||
expect(prefs.nodeIntegration).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -166,27 +166,3 @@ function getBrowserWindowFeatureIntent(features: string): {
|
||||
function isEnabledWindowFeature(value: string): boolean {
|
||||
return value !== "0" && value !== "false" && value !== "no";
|
||||
}
|
||||
|
||||
export function buildBrowserPopupWebPreferences<TSession>(openerSession: TSession): {
|
||||
session: TSession;
|
||||
nodeIntegration: false;
|
||||
nodeIntegrationInSubFrames: false;
|
||||
nodeIntegrationInWorker: false;
|
||||
contextIsolation: true;
|
||||
sandbox: true;
|
||||
webSecurity: true;
|
||||
webviewTag: false;
|
||||
allowRunningInsecureContent: false;
|
||||
} {
|
||||
return {
|
||||
session: openerSession,
|
||||
nodeIntegration: false,
|
||||
nodeIntegrationInSubFrames: false,
|
||||
nodeIntegrationInWorker: false,
|
||||
contextIsolation: true,
|
||||
sandbox: true,
|
||||
webSecurity: true,
|
||||
webviewTag: false,
|
||||
allowRunningInsecureContent: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -63,7 +63,6 @@ import { resolveAppIconPath } from "./features/stamped-icon.js";
|
||||
import { setupApplicationMenu } from "./features/menu.js";
|
||||
import {
|
||||
BROWSER_NEW_TAB_REQUEST_EVENT,
|
||||
buildBrowserPopupWebPreferences,
|
||||
decideBrowserWindowOpenRequest,
|
||||
getPaseoBrowserIdForWebContents,
|
||||
getPaseoBrowserWebContentsForHostWindow,
|
||||
@@ -81,17 +80,12 @@ import {
|
||||
import {
|
||||
clearPaseoBrowserProfile,
|
||||
getLegacyPaseoBrowserProfileSession,
|
||||
PASEO_BROWSER_PROFILE_PARTITION,
|
||||
getPaseoBrowserProfileSession,
|
||||
getPaseoBrowserProfileSessions,
|
||||
listDiskHostBrowserProxyPartitions,
|
||||
listPaseoBrowserProfileGuests,
|
||||
readHostBrowserProxyPartitions,
|
||||
readLegacyPaseoBrowserIds,
|
||||
} from "./features/browser-profile.js";
|
||||
import {
|
||||
applyProxiedWebContentsPolicy,
|
||||
createElectronBrowserProxyController,
|
||||
} from "./features/browser-proxy/index.js";
|
||||
import { parseOpenProjectPathFromArgv } from "./open-project-routing.js";
|
||||
import {
|
||||
createDesktopWindowOwner,
|
||||
@@ -198,7 +192,6 @@ function readActiveBrowserInput(
|
||||
|
||||
const browserKeyboard = new BrowserKeyboard(getPaseoBrowserWebviewRegistry());
|
||||
browserKeyboard.registerIpc();
|
||||
const browserProxy = createElectronBrowserProxyController();
|
||||
|
||||
function showBrowserWebviewContextMenu(
|
||||
win: BrowserWindow,
|
||||
@@ -236,13 +229,22 @@ function showBrowserWebviewContextMenu(
|
||||
|
||||
function getBrowserPopupWindowOptions(
|
||||
mainWindow: BrowserWindow,
|
||||
openerSession: Electron.Session,
|
||||
): Electron.BrowserWindowConstructorOptions {
|
||||
return {
|
||||
parent: mainWindow,
|
||||
show: true,
|
||||
autoHideMenuBar: true,
|
||||
webPreferences: buildBrowserPopupWebPreferences(openerSession),
|
||||
webPreferences: {
|
||||
partition: PASEO_BROWSER_PROFILE_PARTITION,
|
||||
nodeIntegration: false,
|
||||
nodeIntegrationInSubFrames: false,
|
||||
nodeIntegrationInWorker: false,
|
||||
contextIsolation: true,
|
||||
sandbox: true,
|
||||
webSecurity: true,
|
||||
webviewTag: false,
|
||||
allowRunningInsecureContent: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -268,7 +270,7 @@ function installBrowserWindowOpenHandler(input: {
|
||||
if (decision.kind === "popup") {
|
||||
return {
|
||||
action: "allow",
|
||||
overrideBrowserWindowOptions: getBrowserPopupWindowOptions(mainWindow, contents.session),
|
||||
overrideBrowserWindowOptions: getBrowserPopupWindowOptions(mainWindow),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -286,7 +288,6 @@ function installBrowserWindowOpenHandler(input: {
|
||||
|
||||
contents.on("did-create-window", (popupWindow) => {
|
||||
const popupContents = popupWindow.webContents;
|
||||
applyProxiedWebContentsPolicy(popupContents, browserProxy.manager);
|
||||
registerBrowserWebviewNavigationGuards(popupContents);
|
||||
popupContents.on("context-menu", (_event, params) => {
|
||||
showBrowserWebviewContextMenu(popupWindow, popupContents, params);
|
||||
@@ -401,7 +402,6 @@ ipcMain.handle("paseo:browser:register-attached", (event, rawInput: unknown) =>
|
||||
...input,
|
||||
sender: event.sender,
|
||||
profileSession: getPaseoBrowserProfileSession(session),
|
||||
isAllowedSession: (candidate) => browserProxy.manager.isProxiedSession(candidate),
|
||||
findWebContents: (webContentsId) => webContents.fromId(webContentsId) ?? null,
|
||||
});
|
||||
if (!registered) {
|
||||
@@ -514,32 +514,24 @@ ipcMain.handle("paseo:browser:open-devtools", (event, browserId: unknown) => {
|
||||
return result;
|
||||
});
|
||||
|
||||
ipcMain.handle(
|
||||
"paseo:browser:clear-profile",
|
||||
async (_event, rawLegacyBrowserIds: unknown, rawHostServerIds?: unknown) => {
|
||||
const hostPartitions = [
|
||||
...browserProxy.manager.listKnownPartitions(),
|
||||
...readHostBrowserProxyPartitions(rawHostServerIds),
|
||||
...listDiskHostBrowserProxyPartitions(app.getPath("userData")),
|
||||
];
|
||||
const profileSessions = getPaseoBrowserProfileSessions(
|
||||
session,
|
||||
readLegacyPaseoBrowserIds(rawLegacyBrowserIds),
|
||||
hostPartitions,
|
||||
);
|
||||
await clearPaseoBrowserProfile({
|
||||
profileSessions,
|
||||
listGuests: () =>
|
||||
listPaseoBrowserProfileGuests({
|
||||
profileSessions,
|
||||
webContents: webContents.getAllWebContents(),
|
||||
}),
|
||||
logReloadError: (webContentsId, error) => {
|
||||
log.warn("[browser-profile] failed to reload guest", { webContentsId, error });
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
ipcMain.handle("paseo:browser:clear-profile", async (_event, rawLegacyBrowserIds: unknown) => {
|
||||
const profileSessions = getPaseoBrowserProfileSessions(
|
||||
session,
|
||||
readLegacyPaseoBrowserIds(rawLegacyBrowserIds),
|
||||
);
|
||||
const profileSession = profileSessions[0];
|
||||
await clearPaseoBrowserProfile({
|
||||
profileSessions,
|
||||
listGuests: () =>
|
||||
listPaseoBrowserProfileGuests({
|
||||
profileSession,
|
||||
webContents: webContents.getAllWebContents(),
|
||||
}),
|
||||
logReloadError: (webContentsId, error) => {
|
||||
log.warn("[browser-profile] failed to reload guest", { webContentsId, error });
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const browserCapture = createBrowserCaptureService<Electron.NativeImage>({
|
||||
findGuest: getPaseoBrowserWebContentsForHostWindow,
|
||||
@@ -766,14 +758,7 @@ async function createWindow(
|
||||
setupDefaultContextMenu(mainWindow);
|
||||
setupDragDropPrevention(mainWindow);
|
||||
mainWindow.webContents.on("will-attach-webview", (event, webPreferences, params) => {
|
||||
if (
|
||||
!isPaseoBrowserWebviewAttach({
|
||||
src: params.src,
|
||||
partition: params.partition,
|
||||
isAllowedHostPartition: (partition) =>
|
||||
browserProxy.manager.isAllowedHostPartition(partition),
|
||||
})
|
||||
) {
|
||||
if (!isPaseoBrowserWebviewAttach(params)) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
@@ -794,7 +779,6 @@ async function createWindow(
|
||||
webPreferences.preload = getBrowserKeyboardPreloadPath();
|
||||
});
|
||||
mainWindow.webContents.on("did-attach-webview", (_event, contents) => {
|
||||
applyProxiedWebContentsPolicy(contents, browserProxy.manager);
|
||||
preparePaseoBrowserWebContents(contents);
|
||||
contents.once("destroyed", () => {
|
||||
pendingBrowserWindowOpenRequests.delete(contents.id);
|
||||
@@ -1007,7 +991,6 @@ async function bootstrap(): Promise<void> {
|
||||
ipcMain.handle("paseo:opener:openUrl", (_event, value: unknown) => openExternalUrl(value));
|
||||
registerEditorTargetHandlers();
|
||||
registerBrowserAutomationIpc();
|
||||
browserProxy.registerIpc();
|
||||
|
||||
// In-app "Open in new window": opens a window that lands on the given project
|
||||
// via the same open-project flow as a CLI launch (no move, no ownership).
|
||||
@@ -1067,12 +1050,7 @@ function showDaemonShutdownDialog(): void {
|
||||
|
||||
const quitLifecycle = createQuitLifecycle({
|
||||
app,
|
||||
closeTransportSessions: () => {
|
||||
closeAllTransportSessions();
|
||||
void browserProxy.dispose().catch((error) => {
|
||||
log.warn("[browser-proxy] failed to dispose browser proxies on quit", error);
|
||||
});
|
||||
},
|
||||
closeTransportSessions: closeAllTransportSessions,
|
||||
stopDesktopManagedDaemonIfNeeded: () =>
|
||||
stopDesktopManagedDaemonOnQuitIfNeeded({
|
||||
settingsStore: getDesktopSettingsStore(),
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
import { contextBridge, ipcRenderer, webUtils } from "electron";
|
||||
import type { BrowserKeyboardPolicy } from "./features/browser-keyboard/index.js";
|
||||
import type {
|
||||
BrowserProxyStatusSnapshot,
|
||||
BrowserProxyTarget,
|
||||
} from "./features/browser-proxy/index.js";
|
||||
import type { DesktopWindowChromeMode } from "./window/chrome.js";
|
||||
|
||||
// This preload runs in Electron's sandbox and is tsc-compiled (not bundled), so it MUST
|
||||
@@ -137,28 +133,8 @@ contextBridge.exposeInMainWorld("paseoDesktop", {
|
||||
focus: (browserId: string) => ipcRenderer.invoke("paseo:browser:focus", browserId),
|
||||
openDevTools: (browserId: string) =>
|
||||
ipcRenderer.invoke("paseo:browser:open-devtools", browserId),
|
||||
clearProfile: (legacyBrowserIds: string[], hostServerIds?: string[]) =>
|
||||
ipcRenderer.invoke("paseo:browser:clear-profile", legacyBrowserIds, hostServerIds),
|
||||
ensureHostProxy: (input: {
|
||||
serverId: string;
|
||||
target: BrowserProxyTarget;
|
||||
forceReconnect?: boolean;
|
||||
}) =>
|
||||
ipcRenderer.invoke(
|
||||
"paseo:browser-proxy:ensure-host",
|
||||
input,
|
||||
) as Promise<BrowserProxyStatusSnapshot>,
|
||||
updateHostProxyTarget: (input: { serverId: string; target: BrowserProxyTarget }) =>
|
||||
ipcRenderer.invoke("paseo:browser-proxy:update-target", input),
|
||||
getHostProxyStatus: (serverId: string) =>
|
||||
ipcRenderer.invoke(
|
||||
"paseo:browser-proxy:get-status",
|
||||
serverId,
|
||||
) as Promise<BrowserProxyStatusSnapshot | null>,
|
||||
releaseHostProxy: (serverId: string) =>
|
||||
ipcRenderer.invoke("paseo:browser-proxy:release-host", serverId),
|
||||
deliverProxyTicket: (input: { requestId: string; ticket?: string; error?: string }) =>
|
||||
ipcRenderer.invoke("paseo:browser-proxy:deliver-ticket", input),
|
||||
clearProfile: (legacyBrowserIds: string[]) =>
|
||||
ipcRenderer.invoke("paseo:browser:clear-profile", legacyBrowserIds),
|
||||
executeAutomationCommand: (request: Record<string, unknown>) =>
|
||||
ipcRenderer.invoke("paseo:browser:execute-automation-command", request),
|
||||
captureElement: (
|
||||
|
||||
@@ -17,10 +17,6 @@
|
||||
"./addresses": {
|
||||
"types": "./dist/addresses.d.ts",
|
||||
"default": "./dist/addresses.js"
|
||||
},
|
||||
"./network-tunnel": {
|
||||
"types": "./dist/network-tunnel/index.d.ts",
|
||||
"default": "./dist/network-tunnel/index.js"
|
||||
}
|
||||
},
|
||||
"publishConfig": {
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
ServerInfoStatusPayloadSchema,
|
||||
WSInboundMessageSchema,
|
||||
WSTunnelHandshakeResponseSchema,
|
||||
} from "./messages.js";
|
||||
import { validateWSOutboundMessage } from "./validation/ws-outbound.js";
|
||||
|
||||
describe("network tunnel protocol messages", () => {
|
||||
it("accepts server_info with and without optional features.networkTunnel", () => {
|
||||
const base = { status: "server_info", serverId: "srv_1" };
|
||||
expect(ServerInfoStatusPayloadSchema.parse(base).features?.networkTunnel).toBeUndefined();
|
||||
expect(
|
||||
ServerInfoStatusPayloadSchema.parse({ ...base, features: { networkTunnel: true } }).features
|
||||
?.networkTunnel,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("validates network.tunnel.create_ticket.request and .response via zod-aot", () => {
|
||||
expect(
|
||||
WSInboundMessageSchema.parse({
|
||||
type: "session",
|
||||
message: {
|
||||
type: "network.tunnel.create_ticket.request",
|
||||
requestId: "req-1",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
type: "session",
|
||||
message: {
|
||||
type: "network.tunnel.create_ticket.request",
|
||||
requestId: "req-1",
|
||||
},
|
||||
});
|
||||
|
||||
const response = {
|
||||
type: "session",
|
||||
message: {
|
||||
type: "network.tunnel.create_ticket.response",
|
||||
payload: {
|
||||
requestId: "req-1",
|
||||
ticket: "tkt_abc123",
|
||||
expiresAtMs: 1_800_000_000_000,
|
||||
},
|
||||
},
|
||||
};
|
||||
expect(validateWSOutboundMessage(response)).toEqual({
|
||||
success: true,
|
||||
data: response,
|
||||
});
|
||||
});
|
||||
|
||||
it("validates dedicated tunnel handshake schemas", () => {
|
||||
expect(
|
||||
WSInboundMessageSchema.parse({
|
||||
type: "tunnel_hello",
|
||||
ticket: "tkt_secret",
|
||||
}),
|
||||
).toEqual({
|
||||
type: "tunnel_hello",
|
||||
ticket: "tkt_secret",
|
||||
});
|
||||
|
||||
expect(
|
||||
WSTunnelHandshakeResponseSchema.parse({
|
||||
type: "tunnel_ready",
|
||||
maxFramePayloadBytes: 65536,
|
||||
initialStreamWindowBytes: 524288,
|
||||
initialConnectionWindowBytes: 4194304,
|
||||
}),
|
||||
).toEqual({
|
||||
type: "tunnel_ready",
|
||||
maxFramePayloadBytes: 65536,
|
||||
initialStreamWindowBytes: 524288,
|
||||
initialConnectionWindowBytes: 4194304,
|
||||
});
|
||||
|
||||
expect(
|
||||
WSTunnelHandshakeResponseSchema.parse({
|
||||
type: "tunnel_error",
|
||||
code: "invalid_ticket",
|
||||
message: "Ticket expired or already used",
|
||||
}),
|
||||
).toEqual({
|
||||
type: "tunnel_error",
|
||||
code: "invalid_ticket",
|
||||
message: "Ticket expired or already used",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -3239,11 +3239,6 @@ export const FileDownloadTokenRequestSchema = z.object({
|
||||
requestId: z.string(),
|
||||
});
|
||||
|
||||
export const NetworkTunnelCreateTicketRequestSchema = z.object({
|
||||
type: z.literal("network.tunnel.create_ticket.request"),
|
||||
requestId: z.string(),
|
||||
});
|
||||
|
||||
export const FileUploadRequestSchema = z.object({
|
||||
type: z.literal("file.upload.request"),
|
||||
fileName: z.string().min(1),
|
||||
@@ -3607,7 +3602,6 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
|
||||
HostsRouteOpenRequestSchema,
|
||||
HostsRouteFrameRequestSchema,
|
||||
HostsRouteCloseRequestSchema,
|
||||
NetworkTunnelCreateTicketRequestSchema,
|
||||
|
||||
BrowserHostRegisterRequestSchema,
|
||||
SubscriptionReleaseRequestSchema,
|
||||
@@ -4257,8 +4251,6 @@ export const ServerInfoStatusPayloadSchema = z
|
||||
agentProfiles: z.boolean().optional(),
|
||||
// COMPAT(agentConfigApply): added in v0.3.2, remove gate after 2027-02-11.
|
||||
agentConfigApply: z.boolean().optional(),
|
||||
// COMPAT(networkTunnel): added in v0.17.6, remove gate after 2027-05-26.
|
||||
networkTunnel: z.boolean().optional(),
|
||||
})
|
||||
.optional(),
|
||||
})
|
||||
@@ -6835,15 +6827,6 @@ export const FileDownloadTokenResponseSchema = z.object({
|
||||
}),
|
||||
});
|
||||
|
||||
export const NetworkTunnelCreateTicketResponseSchema = z.object({
|
||||
type: z.literal("network.tunnel.create_ticket.response"),
|
||||
payload: z.object({
|
||||
requestId: z.string(),
|
||||
ticket: z.string().min(1),
|
||||
expiresAtMs: z.number().int(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const FileUploadResponseSchema = z.object({
|
||||
type: z.literal("file.upload.response"),
|
||||
payload: z.object({
|
||||
@@ -7799,7 +7782,6 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
|
||||
HostsRouteOpenResponseSchema,
|
||||
HostsRouteFrameSchema,
|
||||
HostsRouteClosedSchema,
|
||||
NetworkTunnelCreateTicketResponseSchema,
|
||||
|
||||
BrowserHostRegisterResponseSchema,
|
||||
SubscriptionReleaseResponseSchema,
|
||||
@@ -8503,13 +8485,6 @@ export type ProjectIconGetResponse = z.infer<typeof ProjectIconGetResponseSchema
|
||||
export type ProjectIcon = z.infer<typeof ProjectIconSchema>;
|
||||
export type FileDownloadTokenRequest = z.infer<typeof FileDownloadTokenRequestSchema>;
|
||||
export type FileDownloadTokenResponse = z.infer<typeof FileDownloadTokenResponseSchema>;
|
||||
export type NetworkTunnelCreateTicketRequest = z.infer<
|
||||
typeof NetworkTunnelCreateTicketRequestSchema
|
||||
>;
|
||||
export type NetworkTunnelCreateTicketResponse = z.infer<
|
||||
typeof NetworkTunnelCreateTicketResponseSchema
|
||||
>;
|
||||
export type NetworkTunnelCreateTicketPayload = NetworkTunnelCreateTicketResponse["payload"];
|
||||
export type FileUploadRequest = z.infer<typeof FileUploadRequestSchema>;
|
||||
export type FileUploadResponse = z.infer<typeof FileUploadResponseSchema>;
|
||||
export type RestartServerRequestMessage = z.infer<typeof RestartServerRequestMessageSchema>;
|
||||
@@ -8631,34 +8606,10 @@ export const WSHelloRejectedMessageSchema = z.object({
|
||||
accepts: z.array(z.literal("password")),
|
||||
});
|
||||
|
||||
export const WSTunnelHelloMessageSchema = z.object({
|
||||
type: z.literal("tunnel_hello"),
|
||||
ticket: z.string().min(1),
|
||||
});
|
||||
|
||||
export const WSTunnelReadyMessageSchema = z.object({
|
||||
type: z.literal("tunnel_ready"),
|
||||
maxFramePayloadBytes: z.number().int().positive(),
|
||||
initialStreamWindowBytes: z.number().int().positive(),
|
||||
initialConnectionWindowBytes: z.number().int().positive(),
|
||||
});
|
||||
|
||||
export const WSTunnelErrorMessageSchema = z.object({
|
||||
type: z.literal("tunnel_error"),
|
||||
code: z.string().min(1),
|
||||
message: z.string(),
|
||||
});
|
||||
|
||||
export const WSTunnelHandshakeResponseSchema = z.discriminatedUnion("type", [
|
||||
WSTunnelReadyMessageSchema,
|
||||
WSTunnelErrorMessageSchema,
|
||||
]);
|
||||
|
||||
// Complete WebSocket message schemas
|
||||
export const WSInboundMessageSchema = z.discriminatedUnion("type", [
|
||||
WSPingMessageSchema,
|
||||
WSHelloMessageSchema,
|
||||
WSTunnelHelloMessageSchema,
|
||||
WSRecordingStateMessageSchema,
|
||||
WSSessionInboundSchema,
|
||||
]);
|
||||
@@ -8672,10 +8623,6 @@ export const WSOutboundMessageSchema = z.discriminatedUnion("type", [
|
||||
export type WSInboundMessage = z.infer<typeof WSInboundMessageSchema>;
|
||||
export type WSOutboundMessage = z.infer<typeof WSOutboundMessageSchema>;
|
||||
export type WSHelloMessage = z.infer<typeof WSHelloMessageSchema>;
|
||||
export type WSTunnelHelloMessage = z.infer<typeof WSTunnelHelloMessageSchema>;
|
||||
export type WSTunnelReadyMessage = z.infer<typeof WSTunnelReadyMessageSchema>;
|
||||
export type WSTunnelErrorMessage = z.infer<typeof WSTunnelErrorMessageSchema>;
|
||||
export type WSTunnelHandshakeResponse = z.infer<typeof WSTunnelHandshakeResponseSchema>;
|
||||
|
||||
// ============================================================================
|
||||
// Helper functions for message conversion
|
||||
|
||||
@@ -1,264 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
decodeNetworkTunnelFrame,
|
||||
encodeNetworkTunnelFrame,
|
||||
NETWORK_TUNNEL_DEFAULT_INITIAL_CONNECTION_WINDOW_BYTES,
|
||||
NETWORK_TUNNEL_DEFAULT_INITIAL_STREAM_WINDOW_BYTES,
|
||||
NETWORK_TUNNEL_HEADER_BYTES,
|
||||
NETWORK_TUNNEL_MAX_CONCURRENT_STREAMS,
|
||||
NETWORK_TUNNEL_MAX_DATA_PAYLOAD_BYTES,
|
||||
NETWORK_TUNNEL_PROTOCOL_VERSION,
|
||||
NetworkTunnelCloseReason,
|
||||
NetworkTunnelCodecError,
|
||||
NetworkTunnelFrameType,
|
||||
type NetworkTunnelFrame,
|
||||
} from "./index.js";
|
||||
|
||||
describe("network-tunnel binary codec", () => {
|
||||
it("exposes expected protocol constants", () => {
|
||||
expect(NETWORK_TUNNEL_PROTOCOL_VERSION).toBe(1);
|
||||
expect(NETWORK_TUNNEL_HEADER_BYTES).toBe(16);
|
||||
expect(NETWORK_TUNNEL_MAX_DATA_PAYLOAD_BYTES).toBe(64 * 1024);
|
||||
expect(NETWORK_TUNNEL_DEFAULT_INITIAL_STREAM_WINDOW_BYTES).toBe(512 * 1024);
|
||||
expect(NETWORK_TUNNEL_DEFAULT_INITIAL_CONNECTION_WINDOW_BYTES).toBe(4 * 1024 * 1024);
|
||||
expect(NETWORK_TUNNEL_MAX_CONCURRENT_STREAMS).toBe(256);
|
||||
});
|
||||
|
||||
it.each<{ name: string; frame: NetworkTunnelFrame; expectedType: NetworkTunnelFrameType }>([
|
||||
{
|
||||
name: "Open with hostname and port",
|
||||
frame: { type: "open", streamId: 1, host: "localhost", port: 5173 },
|
||||
expectedType: NetworkTunnelFrameType.Open,
|
||||
},
|
||||
{
|
||||
name: "Open with IPv6 literal",
|
||||
frame: { type: "open", streamId: 42, host: "::1", port: 80 },
|
||||
expectedType: NetworkTunnelFrameType.Open,
|
||||
},
|
||||
{
|
||||
name: "Opened with initial window",
|
||||
frame: { type: "opened", streamId: 7, initialWindowBytes: 512 * 1024 },
|
||||
expectedType: NetworkTunnelFrameType.Opened,
|
||||
},
|
||||
{
|
||||
name: "Data with binary bytes",
|
||||
frame: {
|
||||
type: "data",
|
||||
streamId: 9,
|
||||
data: new Uint8Array([0, 1, 2, 254, 255]),
|
||||
},
|
||||
expectedType: NetworkTunnelFrameType.Data,
|
||||
},
|
||||
{
|
||||
name: "Data at exact 64 KiB max payload",
|
||||
frame: {
|
||||
type: "data",
|
||||
streamId: 10,
|
||||
data: new Uint8Array(64 * 1024).fill(0xab),
|
||||
},
|
||||
expectedType: NetworkTunnelFrameType.Data,
|
||||
},
|
||||
{
|
||||
name: "Data with empty payload",
|
||||
frame: {
|
||||
type: "data",
|
||||
streamId: 11,
|
||||
data: new Uint8Array(0),
|
||||
},
|
||||
expectedType: NetworkTunnelFrameType.Data,
|
||||
},
|
||||
{
|
||||
name: "Stream WindowUpdate",
|
||||
frame: { type: "window_update", streamId: 3, creditBytes: 65536 },
|
||||
expectedType: NetworkTunnelFrameType.WindowUpdate,
|
||||
},
|
||||
{
|
||||
name: "Connection WindowUpdate (streamId 0)",
|
||||
frame: { type: "window_update", streamId: 0, creditBytes: 1024 * 1024 },
|
||||
expectedType: NetworkTunnelFrameType.WindowUpdate,
|
||||
},
|
||||
{
|
||||
name: "HalfClose",
|
||||
frame: { type: "half_close", streamId: 5 },
|
||||
expectedType: NetworkTunnelFrameType.HalfClose,
|
||||
},
|
||||
{
|
||||
name: "Close without message",
|
||||
frame: { type: "close", streamId: 12, reason: NetworkTunnelCloseReason.Normal },
|
||||
expectedType: NetworkTunnelFrameType.Close,
|
||||
},
|
||||
{
|
||||
name: "Close with UTF-8 message",
|
||||
frame: {
|
||||
type: "close",
|
||||
streamId: 13,
|
||||
reason: NetworkTunnelCloseReason.PolicyDenied,
|
||||
message: "Destination blocked: metadata endpoint 🚫",
|
||||
},
|
||||
expectedType: NetworkTunnelFrameType.Close,
|
||||
},
|
||||
{
|
||||
name: "Ping without payload",
|
||||
frame: { type: "ping" },
|
||||
expectedType: NetworkTunnelFrameType.Ping,
|
||||
},
|
||||
{
|
||||
name: "Ping with nonce payload",
|
||||
frame: { type: "ping", payload: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]) },
|
||||
expectedType: NetworkTunnelFrameType.Ping,
|
||||
},
|
||||
{
|
||||
name: "Pong with nonce payload",
|
||||
frame: { type: "pong", payload: new Uint8Array([8, 7, 6, 5, 4, 3, 2, 1]) },
|
||||
expectedType: NetworkTunnelFrameType.Pong,
|
||||
},
|
||||
])("round-trips $name with fixed 16-byte header", ({ frame, expectedType }) => {
|
||||
const encoded = encodeNetworkTunnelFrame(frame);
|
||||
expect(encoded.byteLength).toBeGreaterThanOrEqual(NETWORK_TUNNEL_HEADER_BYTES);
|
||||
|
||||
const view = new DataView(encoded.buffer, encoded.byteOffset, encoded.byteLength);
|
||||
expect(view.getUint8(0)).toBe(NETWORK_TUNNEL_PROTOCOL_VERSION);
|
||||
expect(view.getUint8(1)).toBe(expectedType);
|
||||
expect(view.getUint16(2, false)).toBe(frame.flags ?? 0);
|
||||
expect(view.getUint32(8, false)).toBe(encoded.byteLength - NETWORK_TUNNEL_HEADER_BYTES);
|
||||
expect(view.getUint32(12, false)).toBe(0);
|
||||
|
||||
const decoded = decodeNetworkTunnelFrame(encoded);
|
||||
expect(decoded).toEqual({
|
||||
...frame,
|
||||
flags: frame.flags ?? 0,
|
||||
...(frame.type === "ping" || frame.type === "pong"
|
||||
? { payload: frame.payload ?? new Uint8Array(0) }
|
||||
: {}),
|
||||
});
|
||||
});
|
||||
|
||||
it("decodes cleanly from a non-zero byteOffset subarray", () => {
|
||||
const encoded = encodeNetworkTunnelFrame({
|
||||
type: "open",
|
||||
streamId: 99,
|
||||
host: "service.localhost",
|
||||
port: 3000,
|
||||
});
|
||||
const padded = new Uint8Array(encoded.byteLength + 10);
|
||||
padded.set(encoded, 5);
|
||||
const slice = padded.subarray(5, 5 + encoded.byteLength);
|
||||
|
||||
expect(decodeNetworkTunnelFrame(slice)).toEqual({
|
||||
type: "open",
|
||||
streamId: 99,
|
||||
host: "service.localhost",
|
||||
port: 3000,
|
||||
flags: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects truncated, mismatched, unknown, and oversized frames", () => {
|
||||
expect(() => decodeNetworkTunnelFrame(new Uint8Array(15))).toThrowError(
|
||||
NetworkTunnelCodecError,
|
||||
);
|
||||
|
||||
const valid = encodeNetworkTunnelFrame({ type: "half_close", streamId: 1 });
|
||||
|
||||
// Unsupported version
|
||||
const badVersion = valid.slice();
|
||||
badVersion[0] = 2;
|
||||
expect(() => decodeNetworkTunnelFrame(badVersion)).toThrowError(NetworkTunnelCodecError);
|
||||
|
||||
// Unknown frame type
|
||||
const badType = valid.slice();
|
||||
badType[1] = 99;
|
||||
expect(() => decodeNetworkTunnelFrame(badType)).toThrowError(NetworkTunnelCodecError);
|
||||
|
||||
// Payload length header mismatch
|
||||
const badLen = valid.slice();
|
||||
new DataView(badLen.buffer).setUint32(8, 4, false);
|
||||
expect(() => decodeNetworkTunnelFrame(badLen)).toThrowError(NetworkTunnelCodecError);
|
||||
|
||||
// Data payload over 64 KiB on encode
|
||||
expect(() =>
|
||||
encodeNetworkTunnelFrame({
|
||||
type: "data",
|
||||
streamId: 1,
|
||||
data: new Uint8Array(64 * 1024 + 1),
|
||||
}),
|
||||
).toThrowError(NetworkTunnelCodecError);
|
||||
|
||||
// Data payload over 64 KiB on decode
|
||||
const huge = new Uint8Array(NETWORK_TUNNEL_HEADER_BYTES + 64 * 1024 + 1);
|
||||
const hugeView = new DataView(huge.buffer);
|
||||
hugeView.setUint8(0, NETWORK_TUNNEL_PROTOCOL_VERSION);
|
||||
hugeView.setUint8(1, NetworkTunnelFrameType.Data);
|
||||
hugeView.setUint32(4, 1, false);
|
||||
hugeView.setUint32(8, 64 * 1024 + 1, false);
|
||||
expect(() => decodeNetworkTunnelFrame(huge)).toThrowError(NetworkTunnelCodecError);
|
||||
|
||||
// Invalid streamId 0 for stream-scoped frames
|
||||
expect(() =>
|
||||
encodeNetworkTunnelFrame({ type: "open", streamId: 0, host: "localhost", port: 80 }),
|
||||
).toThrowError(NetworkTunnelCodecError);
|
||||
expect(() =>
|
||||
encodeNetworkTunnelFrame({ type: "data", streamId: 0, data: new Uint8Array([1]) }),
|
||||
).toThrowError(NetworkTunnelCodecError);
|
||||
expect(() => encodeNetworkTunnelFrame({ type: "half_close", streamId: 0 })).toThrowError(
|
||||
NetworkTunnelCodecError,
|
||||
);
|
||||
|
||||
// Non-zero streamId on Ping on wire
|
||||
const badPing = encodeNetworkTunnelFrame({ type: "ping" }).slice();
|
||||
new DataView(badPing.buffer).setUint32(4, 5, false);
|
||||
expect(() => decodeNetworkTunnelFrame(badPing)).toThrowError(NetworkTunnelCodecError);
|
||||
|
||||
// Zero credit on WindowUpdate
|
||||
expect(() =>
|
||||
encodeNetworkTunnelFrame({ type: "window_update", streamId: 1, creditBytes: 0 }),
|
||||
).toThrowError(NetworkTunnelCodecError);
|
||||
|
||||
// Invalid port / empty host on Open
|
||||
expect(() =>
|
||||
encodeNetworkTunnelFrame({ type: "open", streamId: 1, host: "", port: 80 }),
|
||||
).toThrowError(NetworkTunnelCodecError);
|
||||
expect(() =>
|
||||
encodeNetworkTunnelFrame({ type: "open", streamId: 1, host: "localhost", port: 0 }),
|
||||
).toThrowError(NetworkTunnelCodecError);
|
||||
expect(() =>
|
||||
encodeNetworkTunnelFrame({ type: "open", streamId: 1, host: "localhost", port: 65536 }),
|
||||
).toThrowError(NetworkTunnelCodecError);
|
||||
|
||||
// Invalid UTF-8 in Close message
|
||||
const badClose = new Uint8Array(NETWORK_TUNNEL_HEADER_BYTES + 4);
|
||||
const badCloseView = new DataView(badClose.buffer);
|
||||
badCloseView.setUint8(0, NETWORK_TUNNEL_PROTOCOL_VERSION);
|
||||
badCloseView.setUint8(1, NetworkTunnelFrameType.Close);
|
||||
badCloseView.setUint32(4, 1, false);
|
||||
badCloseView.setUint32(8, 4, false);
|
||||
badCloseView.setUint16(16, NetworkTunnelCloseReason.InternalError, false);
|
||||
badClose[18] = 0xff;
|
||||
badClose[19] = 0xfe;
|
||||
expect(() => decodeNetworkTunnelFrame(badClose)).toThrowError(NetworkTunnelCodecError);
|
||||
|
||||
// Non-zero reserved bytes
|
||||
const badReserved = valid.slice();
|
||||
new DataView(badReserved.buffer).setUint32(12, 1, false);
|
||||
expect(() => decodeNetworkTunnelFrame(badReserved)).toThrowError(NetworkTunnelCodecError);
|
||||
});
|
||||
|
||||
it("handles deterministic malformed fuzz inputs without crashing", () => {
|
||||
let seed = 0x12345678;
|
||||
const nextByte = () => {
|
||||
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
|
||||
return seed & 0xff;
|
||||
};
|
||||
|
||||
for (let i = 0; i < 200; i += 1) {
|
||||
const length = i % 40;
|
||||
const bytes = new Uint8Array(length);
|
||||
for (let j = 0; j < length; j += 1) bytes[j] = nextByte();
|
||||
try {
|
||||
decodeNetworkTunnelFrame(bytes);
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(NetworkTunnelCodecError);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
export {
|
||||
decodeNetworkTunnelFrame,
|
||||
encodeNetworkTunnelFrame,
|
||||
NETWORK_TUNNEL_DEFAULT_INITIAL_CONNECTION_WINDOW_BYTES,
|
||||
NETWORK_TUNNEL_DEFAULT_INITIAL_STREAM_WINDOW_BYTES,
|
||||
NETWORK_TUNNEL_HEADER_BYTES,
|
||||
NETWORK_TUNNEL_MAX_CONCURRENT_STREAMS,
|
||||
NETWORK_TUNNEL_MAX_DATA_PAYLOAD_BYTES,
|
||||
NETWORK_TUNNEL_PROTOCOL_VERSION,
|
||||
NetworkTunnelCloseReason,
|
||||
NetworkTunnelCodecError,
|
||||
NetworkTunnelFrameType,
|
||||
type DecodedNetworkTunnelFrame,
|
||||
type NetworkTunnelCodecErrorCode,
|
||||
type NetworkTunnelFrame,
|
||||
} from "./internal/codec.js";
|
||||
@@ -1,559 +0,0 @@
|
||||
export const NETWORK_TUNNEL_PROTOCOL_VERSION = 1;
|
||||
export const NETWORK_TUNNEL_HEADER_BYTES = 16;
|
||||
export const NETWORK_TUNNEL_MAX_DATA_PAYLOAD_BYTES = 64 * 1024;
|
||||
export const NETWORK_TUNNEL_DEFAULT_INITIAL_STREAM_WINDOW_BYTES = 512 * 1024;
|
||||
export const NETWORK_TUNNEL_DEFAULT_INITIAL_CONNECTION_WINDOW_BYTES = 4 * 1024 * 1024;
|
||||
export const NETWORK_TUNNEL_MAX_CONCURRENT_STREAMS = 256;
|
||||
|
||||
const MAX_HOST_BYTES = 1024;
|
||||
const MAX_CLOSE_MESSAGE_BYTES = 1024;
|
||||
const MAX_PING_PAYLOAD_BYTES = 64;
|
||||
const MAX_UINT16 = 0xffff;
|
||||
const MAX_UINT32 = 0xffffffff;
|
||||
|
||||
export enum NetworkTunnelFrameType {
|
||||
Open = 1,
|
||||
Opened = 2,
|
||||
Data = 3,
|
||||
WindowUpdate = 4,
|
||||
HalfClose = 5,
|
||||
Close = 6,
|
||||
Ping = 7,
|
||||
Pong = 8,
|
||||
}
|
||||
|
||||
export enum NetworkTunnelCloseReason {
|
||||
Normal = 0,
|
||||
RemoteClosed = 1,
|
||||
ConnectRefused = 2,
|
||||
HostUnreachable = 3,
|
||||
DnsFailed = 4,
|
||||
PolicyDenied = 5,
|
||||
Timeout = 6,
|
||||
StreamLimitExceeded = 7,
|
||||
FlowControlError = 8,
|
||||
ProtocolError = 9,
|
||||
InternalError = 10,
|
||||
Reset = 11,
|
||||
}
|
||||
|
||||
export type NetworkTunnelCodecErrorCode =
|
||||
| "truncated_header"
|
||||
| "unsupported_version"
|
||||
| "unknown_frame_type"
|
||||
| "length_mismatch"
|
||||
| "payload_too_large"
|
||||
| "invalid_stream_id"
|
||||
| "invalid_flags"
|
||||
| "invalid_reserved"
|
||||
| "invalid_payload"
|
||||
| "invalid_utf8";
|
||||
|
||||
export class NetworkTunnelCodecError extends Error {
|
||||
readonly code: NetworkTunnelCodecErrorCode;
|
||||
|
||||
constructor(code: NetworkTunnelCodecErrorCode, message: string) {
|
||||
super(message);
|
||||
this.name = "NetworkTunnelCodecError";
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
export type NetworkTunnelFrame =
|
||||
| {
|
||||
type: "open";
|
||||
streamId: number;
|
||||
host: string;
|
||||
port: number;
|
||||
flags?: number;
|
||||
}
|
||||
| {
|
||||
type: "opened";
|
||||
streamId: number;
|
||||
initialWindowBytes: number;
|
||||
flags?: number;
|
||||
}
|
||||
| {
|
||||
type: "data";
|
||||
streamId: number;
|
||||
data: Uint8Array;
|
||||
flags?: number;
|
||||
}
|
||||
| {
|
||||
type: "window_update";
|
||||
streamId: number;
|
||||
creditBytes: number;
|
||||
flags?: number;
|
||||
}
|
||||
| {
|
||||
type: "half_close";
|
||||
streamId: number;
|
||||
flags?: number;
|
||||
}
|
||||
| {
|
||||
type: "close";
|
||||
streamId: number;
|
||||
reason: NetworkTunnelCloseReason;
|
||||
message?: string;
|
||||
flags?: number;
|
||||
}
|
||||
| {
|
||||
type: "ping";
|
||||
payload?: Uint8Array;
|
||||
flags?: number;
|
||||
}
|
||||
| {
|
||||
type: "pong";
|
||||
payload?: Uint8Array;
|
||||
flags?: number;
|
||||
};
|
||||
|
||||
export type DecodedNetworkTunnelFrame =
|
||||
| {
|
||||
type: "open";
|
||||
streamId: number;
|
||||
host: string;
|
||||
port: number;
|
||||
flags: number;
|
||||
}
|
||||
| {
|
||||
type: "opened";
|
||||
streamId: number;
|
||||
initialWindowBytes: number;
|
||||
flags: number;
|
||||
}
|
||||
| {
|
||||
type: "data";
|
||||
streamId: number;
|
||||
data: Uint8Array;
|
||||
flags: number;
|
||||
}
|
||||
| {
|
||||
type: "window_update";
|
||||
streamId: number;
|
||||
creditBytes: number;
|
||||
flags: number;
|
||||
}
|
||||
| {
|
||||
type: "half_close";
|
||||
streamId: number;
|
||||
flags: number;
|
||||
}
|
||||
| {
|
||||
type: "close";
|
||||
streamId: number;
|
||||
reason: NetworkTunnelCloseReason;
|
||||
message?: string;
|
||||
flags: number;
|
||||
}
|
||||
| {
|
||||
type: "ping";
|
||||
payload: Uint8Array;
|
||||
flags: number;
|
||||
}
|
||||
| {
|
||||
type: "pong";
|
||||
payload: Uint8Array;
|
||||
flags: number;
|
||||
};
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder("utf-8", { fatal: true });
|
||||
|
||||
function isValidCloseReason(value: number): value is NetworkTunnelCloseReason {
|
||||
return (
|
||||
Number.isInteger(value) &&
|
||||
value >= NetworkTunnelCloseReason.Normal &&
|
||||
value <= NetworkTunnelCloseReason.Reset
|
||||
);
|
||||
}
|
||||
|
||||
function assertUint16(value: number, code: NetworkTunnelCodecErrorCode, name: string): void {
|
||||
if (!Number.isInteger(value) || value < 0 || value > MAX_UINT16) {
|
||||
throw new NetworkTunnelCodecError(code, `Invalid ${name}: ${value}`);
|
||||
}
|
||||
}
|
||||
|
||||
function assertUint32(value: number, code: NetworkTunnelCodecErrorCode, name: string): void {
|
||||
if (!Number.isInteger(value) || value < 0 || value > MAX_UINT32) {
|
||||
throw new NetworkTunnelCodecError(code, `Invalid ${name}: ${value}`);
|
||||
}
|
||||
}
|
||||
|
||||
function assertPositiveStreamId(streamId: number): void {
|
||||
assertUint32(streamId, "invalid_stream_id", "streamId");
|
||||
if (streamId === 0) {
|
||||
throw new NetworkTunnelCodecError("invalid_stream_id", "Stream frame requires streamId >= 1");
|
||||
}
|
||||
}
|
||||
|
||||
function writeHeader(
|
||||
out: Uint8Array,
|
||||
frameType: NetworkTunnelFrameType,
|
||||
flags: number,
|
||||
streamId: number,
|
||||
payloadLength: number,
|
||||
): DataView {
|
||||
assertUint16(flags, "invalid_flags", "flags");
|
||||
assertUint32(streamId, "invalid_stream_id", "streamId");
|
||||
assertUint32(payloadLength, "invalid_payload", "payloadLength");
|
||||
const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
|
||||
view.setUint8(0, NETWORK_TUNNEL_PROTOCOL_VERSION);
|
||||
view.setUint8(1, frameType);
|
||||
view.setUint16(2, flags, false);
|
||||
view.setUint32(4, streamId, false);
|
||||
view.setUint32(8, payloadLength, false);
|
||||
view.setUint32(12, 0, false);
|
||||
return view;
|
||||
}
|
||||
|
||||
function decodeUtf8Strict(bytes: Uint8Array, label: string): string {
|
||||
try {
|
||||
return textDecoder.decode(bytes);
|
||||
} catch {
|
||||
throw new NetworkTunnelCodecError("invalid_utf8", `Invalid UTF-8 in ${label}`);
|
||||
}
|
||||
}
|
||||
|
||||
function encodeOpenFrame(
|
||||
frame: Extract<NetworkTunnelFrame, { type: "open" }>,
|
||||
flags: number,
|
||||
): Uint8Array {
|
||||
assertPositiveStreamId(frame.streamId);
|
||||
if (!Number.isInteger(frame.port) || frame.port < 1 || frame.port > MAX_UINT16) {
|
||||
throw new NetworkTunnelCodecError("invalid_payload", `Invalid port: ${frame.port}`);
|
||||
}
|
||||
const hostBytes = textEncoder.encode(frame.host);
|
||||
if (hostBytes.byteLength === 0 || hostBytes.byteLength > MAX_HOST_BYTES) {
|
||||
throw new NetworkTunnelCodecError(
|
||||
"invalid_payload",
|
||||
`Invalid host length: ${hostBytes.byteLength}`,
|
||||
);
|
||||
}
|
||||
const payloadLength = 4 + hostBytes.byteLength;
|
||||
const out = new Uint8Array(NETWORK_TUNNEL_HEADER_BYTES + payloadLength);
|
||||
const view = writeHeader(out, NetworkTunnelFrameType.Open, flags, frame.streamId, payloadLength);
|
||||
view.setUint16(NETWORK_TUNNEL_HEADER_BYTES, frame.port, false);
|
||||
view.setUint16(NETWORK_TUNNEL_HEADER_BYTES + 2, hostBytes.byteLength, false);
|
||||
out.set(hostBytes, NETWORK_TUNNEL_HEADER_BYTES + 4);
|
||||
return out;
|
||||
}
|
||||
|
||||
function encodeCloseFrame(
|
||||
frame: Extract<NetworkTunnelFrame, { type: "close" }>,
|
||||
flags: number,
|
||||
): Uint8Array {
|
||||
assertPositiveStreamId(frame.streamId);
|
||||
if (!isValidCloseReason(frame.reason)) {
|
||||
throw new NetworkTunnelCodecError("invalid_payload", `Invalid close reason: ${frame.reason}`);
|
||||
}
|
||||
const messageBytes =
|
||||
frame.message !== undefined ? textEncoder.encode(frame.message) : new Uint8Array(0);
|
||||
if (messageBytes.byteLength > MAX_CLOSE_MESSAGE_BYTES) {
|
||||
throw new NetworkTunnelCodecError(
|
||||
"payload_too_large",
|
||||
`Close message length ${messageBytes.byteLength} exceeds max ${MAX_CLOSE_MESSAGE_BYTES}`,
|
||||
);
|
||||
}
|
||||
const payloadLength = 2 + messageBytes.byteLength;
|
||||
const out = new Uint8Array(NETWORK_TUNNEL_HEADER_BYTES + payloadLength);
|
||||
const view = writeHeader(out, NetworkTunnelFrameType.Close, flags, frame.streamId, payloadLength);
|
||||
view.setUint16(NETWORK_TUNNEL_HEADER_BYTES, frame.reason, false);
|
||||
if (messageBytes.byteLength > 0) {
|
||||
out.set(messageBytes, NETWORK_TUNNEL_HEADER_BYTES + 2);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function encodePingPongFrame(
|
||||
frame: Extract<NetworkTunnelFrame, { type: "ping" | "pong" }>,
|
||||
flags: number,
|
||||
): Uint8Array {
|
||||
const payload = frame.payload ?? new Uint8Array(0);
|
||||
if (payload.byteLength > MAX_PING_PAYLOAD_BYTES) {
|
||||
throw new NetworkTunnelCodecError(
|
||||
"payload_too_large",
|
||||
`${frame.type} payload length ${payload.byteLength} exceeds max ${MAX_PING_PAYLOAD_BYTES}`,
|
||||
);
|
||||
}
|
||||
const out = new Uint8Array(NETWORK_TUNNEL_HEADER_BYTES + payload.byteLength);
|
||||
writeHeader(
|
||||
out,
|
||||
frame.type === "ping" ? NetworkTunnelFrameType.Ping : NetworkTunnelFrameType.Pong,
|
||||
flags,
|
||||
0,
|
||||
payload.byteLength,
|
||||
);
|
||||
if (payload.byteLength > 0) {
|
||||
out.set(payload, NETWORK_TUNNEL_HEADER_BYTES);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function encodeNetworkTunnelFrame(frame: NetworkTunnelFrame): Uint8Array {
|
||||
const flags = frame.flags ?? 0;
|
||||
|
||||
switch (frame.type) {
|
||||
case "open":
|
||||
return encodeOpenFrame(frame, flags);
|
||||
|
||||
case "opened": {
|
||||
assertPositiveStreamId(frame.streamId);
|
||||
assertUint32(frame.initialWindowBytes, "invalid_payload", "initialWindowBytes");
|
||||
const out = new Uint8Array(NETWORK_TUNNEL_HEADER_BYTES + 4);
|
||||
const view = writeHeader(out, NetworkTunnelFrameType.Opened, flags, frame.streamId, 4);
|
||||
view.setUint32(NETWORK_TUNNEL_HEADER_BYTES, frame.initialWindowBytes, false);
|
||||
return out;
|
||||
}
|
||||
|
||||
case "data": {
|
||||
assertPositiveStreamId(frame.streamId);
|
||||
if (frame.data.byteLength > NETWORK_TUNNEL_MAX_DATA_PAYLOAD_BYTES) {
|
||||
throw new NetworkTunnelCodecError(
|
||||
"payload_too_large",
|
||||
`Data payload ${frame.data.byteLength} exceeds max ${NETWORK_TUNNEL_MAX_DATA_PAYLOAD_BYTES}`,
|
||||
);
|
||||
}
|
||||
const out = new Uint8Array(NETWORK_TUNNEL_HEADER_BYTES + frame.data.byteLength);
|
||||
writeHeader(out, NetworkTunnelFrameType.Data, flags, frame.streamId, frame.data.byteLength);
|
||||
out.set(frame.data, NETWORK_TUNNEL_HEADER_BYTES);
|
||||
return out;
|
||||
}
|
||||
|
||||
case "window_update": {
|
||||
assertUint32(frame.streamId, "invalid_stream_id", "streamId");
|
||||
assertUint32(frame.creditBytes, "invalid_payload", "creditBytes");
|
||||
if (frame.creditBytes === 0) {
|
||||
throw new NetworkTunnelCodecError(
|
||||
"invalid_payload",
|
||||
"WindowUpdate creditBytes must be > 0",
|
||||
);
|
||||
}
|
||||
const out = new Uint8Array(NETWORK_TUNNEL_HEADER_BYTES + 4);
|
||||
const view = writeHeader(out, NetworkTunnelFrameType.WindowUpdate, flags, frame.streamId, 4);
|
||||
view.setUint32(NETWORK_TUNNEL_HEADER_BYTES, frame.creditBytes, false);
|
||||
return out;
|
||||
}
|
||||
|
||||
case "half_close": {
|
||||
assertPositiveStreamId(frame.streamId);
|
||||
const out = new Uint8Array(NETWORK_TUNNEL_HEADER_BYTES);
|
||||
writeHeader(out, NetworkTunnelFrameType.HalfClose, flags, frame.streamId, 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
case "close":
|
||||
return encodeCloseFrame(frame, flags);
|
||||
|
||||
case "ping":
|
||||
case "pong":
|
||||
return encodePingPongFrame(frame, flags);
|
||||
}
|
||||
}
|
||||
|
||||
interface DecodedHeader {
|
||||
frameType: number;
|
||||
flags: number;
|
||||
streamId: number;
|
||||
payloadLength: number;
|
||||
view: DataView;
|
||||
payload: Uint8Array;
|
||||
}
|
||||
|
||||
function parseHeader(bytes: Uint8Array): DecodedHeader {
|
||||
if (bytes.byteLength < NETWORK_TUNNEL_HEADER_BYTES) {
|
||||
throw new NetworkTunnelCodecError(
|
||||
"truncated_header",
|
||||
`Expected at least ${NETWORK_TUNNEL_HEADER_BYTES} bytes, got ${bytes.byteLength}`,
|
||||
);
|
||||
}
|
||||
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
const version = view.getUint8(0);
|
||||
if (version !== NETWORK_TUNNEL_PROTOCOL_VERSION) {
|
||||
throw new NetworkTunnelCodecError(
|
||||
"unsupported_version",
|
||||
`Unsupported network tunnel protocol version: ${version}`,
|
||||
);
|
||||
}
|
||||
|
||||
const frameType = view.getUint8(1);
|
||||
const flags = view.getUint16(2, false);
|
||||
const streamId = view.getUint32(4, false);
|
||||
const payloadLength = view.getUint32(8, false);
|
||||
const reserved = view.getUint32(12, false);
|
||||
|
||||
if (reserved !== 0) {
|
||||
throw new NetworkTunnelCodecError("invalid_reserved", "Reserved header bits must be 0");
|
||||
}
|
||||
|
||||
const actualPayloadLength = bytes.byteLength - NETWORK_TUNNEL_HEADER_BYTES;
|
||||
if (payloadLength !== actualPayloadLength) {
|
||||
throw new NetworkTunnelCodecError(
|
||||
"length_mismatch",
|
||||
`Header payloadLength ${payloadLength} does not match buffer payload length ${actualPayloadLength}`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
frameType,
|
||||
flags,
|
||||
streamId,
|
||||
payloadLength,
|
||||
view,
|
||||
payload: bytes.subarray(NETWORK_TUNNEL_HEADER_BYTES),
|
||||
};
|
||||
}
|
||||
|
||||
function decodeOpenFrame(header: DecodedHeader): DecodedNetworkTunnelFrame {
|
||||
if (header.streamId === 0) {
|
||||
throw new NetworkTunnelCodecError("invalid_stream_id", "Open requires streamId >= 1");
|
||||
}
|
||||
if (header.payloadLength < 4) {
|
||||
throw new NetworkTunnelCodecError("invalid_payload", "Open payload too short");
|
||||
}
|
||||
const port = header.view.getUint16(NETWORK_TUNNEL_HEADER_BYTES, false);
|
||||
const hostLength = header.view.getUint16(NETWORK_TUNNEL_HEADER_BYTES + 2, false);
|
||||
if (port < 1) {
|
||||
throw new NetworkTunnelCodecError("invalid_payload", `Invalid Open port: ${port}`);
|
||||
}
|
||||
if (hostLength === 0 || hostLength > MAX_HOST_BYTES) {
|
||||
throw new NetworkTunnelCodecError("invalid_payload", `Invalid Open host length: ${hostLength}`);
|
||||
}
|
||||
if (header.payloadLength !== 4 + hostLength) {
|
||||
throw new NetworkTunnelCodecError(
|
||||
"invalid_payload",
|
||||
`Open payload length ${header.payloadLength} does not match host length ${hostLength}`,
|
||||
);
|
||||
}
|
||||
const host = decodeUtf8Strict(header.payload.subarray(4, 4 + hostLength), "Open host");
|
||||
return { type: "open", streamId: header.streamId, host, port, flags: header.flags };
|
||||
}
|
||||
|
||||
function decodeCloseFrame(header: DecodedHeader): DecodedNetworkTunnelFrame {
|
||||
if (header.streamId === 0) {
|
||||
throw new NetworkTunnelCodecError("invalid_stream_id", "Close requires streamId >= 1");
|
||||
}
|
||||
if (header.payloadLength < 2) {
|
||||
throw new NetworkTunnelCodecError("invalid_payload", "Close payload too short");
|
||||
}
|
||||
if (header.payloadLength - 2 > MAX_CLOSE_MESSAGE_BYTES) {
|
||||
throw new NetworkTunnelCodecError(
|
||||
"payload_too_large",
|
||||
`Close message exceeds max ${MAX_CLOSE_MESSAGE_BYTES} bytes`,
|
||||
);
|
||||
}
|
||||
const reason = header.view.getUint16(NETWORK_TUNNEL_HEADER_BYTES, false);
|
||||
if (!isValidCloseReason(reason)) {
|
||||
throw new NetworkTunnelCodecError("invalid_payload", `Unknown close reason: ${reason}`);
|
||||
}
|
||||
if (header.payloadLength === 2) {
|
||||
return { type: "close", streamId: header.streamId, reason, flags: header.flags };
|
||||
}
|
||||
const message = decodeUtf8Strict(header.payload.subarray(2), "Close message");
|
||||
return { type: "close", streamId: header.streamId, reason, message, flags: header.flags };
|
||||
}
|
||||
|
||||
function decodePingPongFrame(
|
||||
type: "ping" | "pong",
|
||||
header: DecodedHeader,
|
||||
): DecodedNetworkTunnelFrame {
|
||||
if (header.streamId !== 0) {
|
||||
throw new NetworkTunnelCodecError("invalid_stream_id", `${type} requires streamId === 0`);
|
||||
}
|
||||
if (header.payloadLength > MAX_PING_PAYLOAD_BYTES) {
|
||||
throw new NetworkTunnelCodecError(
|
||||
"payload_too_large",
|
||||
`${type} payload exceeds max ${MAX_PING_PAYLOAD_BYTES} bytes`,
|
||||
);
|
||||
}
|
||||
return { type, payload: header.payload.slice(), flags: header.flags };
|
||||
}
|
||||
|
||||
function decodeOpenedFrame(header: DecodedHeader): DecodedNetworkTunnelFrame {
|
||||
if (header.streamId === 0) {
|
||||
throw new NetworkTunnelCodecError("invalid_stream_id", "Opened requires streamId >= 1");
|
||||
}
|
||||
if (header.payloadLength !== 4) {
|
||||
throw new NetworkTunnelCodecError("invalid_payload", "Opened payload must be 4 bytes");
|
||||
}
|
||||
const initialWindowBytes = header.view.getUint32(NETWORK_TUNNEL_HEADER_BYTES, false);
|
||||
return {
|
||||
type: "opened",
|
||||
streamId: header.streamId,
|
||||
initialWindowBytes,
|
||||
flags: header.flags,
|
||||
};
|
||||
}
|
||||
|
||||
function decodeDataFrame(header: DecodedHeader): DecodedNetworkTunnelFrame {
|
||||
if (header.streamId === 0) {
|
||||
throw new NetworkTunnelCodecError("invalid_stream_id", "Data requires streamId >= 1");
|
||||
}
|
||||
if (header.payloadLength > NETWORK_TUNNEL_MAX_DATA_PAYLOAD_BYTES) {
|
||||
throw new NetworkTunnelCodecError(
|
||||
"payload_too_large",
|
||||
`Data payload ${header.payloadLength} exceeds max ${NETWORK_TUNNEL_MAX_DATA_PAYLOAD_BYTES}`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
type: "data",
|
||||
streamId: header.streamId,
|
||||
data: header.payload.slice(),
|
||||
flags: header.flags,
|
||||
};
|
||||
}
|
||||
|
||||
function decodeWindowUpdateFrame(header: DecodedHeader): DecodedNetworkTunnelFrame {
|
||||
if (header.payloadLength !== 4) {
|
||||
throw new NetworkTunnelCodecError("invalid_payload", "WindowUpdate payload must be 4 bytes");
|
||||
}
|
||||
const creditBytes = header.view.getUint32(NETWORK_TUNNEL_HEADER_BYTES, false);
|
||||
if (creditBytes === 0) {
|
||||
throw new NetworkTunnelCodecError("invalid_payload", "WindowUpdate creditBytes must be > 0");
|
||||
}
|
||||
return {
|
||||
type: "window_update",
|
||||
streamId: header.streamId,
|
||||
creditBytes,
|
||||
flags: header.flags,
|
||||
};
|
||||
}
|
||||
|
||||
function decodeHalfCloseFrame(header: DecodedHeader): DecodedNetworkTunnelFrame {
|
||||
if (header.streamId === 0) {
|
||||
throw new NetworkTunnelCodecError("invalid_stream_id", "HalfClose requires streamId >= 1");
|
||||
}
|
||||
if (header.payloadLength !== 0) {
|
||||
throw new NetworkTunnelCodecError("invalid_payload", "HalfClose payload must be empty");
|
||||
}
|
||||
return { type: "half_close", streamId: header.streamId, flags: header.flags };
|
||||
}
|
||||
|
||||
export function decodeNetworkTunnelFrame(bytes: Uint8Array): DecodedNetworkTunnelFrame {
|
||||
const header = parseHeader(bytes);
|
||||
|
||||
switch (header.frameType) {
|
||||
case NetworkTunnelFrameType.Open:
|
||||
return decodeOpenFrame(header);
|
||||
case NetworkTunnelFrameType.Opened:
|
||||
return decodeOpenedFrame(header);
|
||||
case NetworkTunnelFrameType.Data:
|
||||
return decodeDataFrame(header);
|
||||
case NetworkTunnelFrameType.WindowUpdate:
|
||||
return decodeWindowUpdateFrame(header);
|
||||
case NetworkTunnelFrameType.HalfClose:
|
||||
return decodeHalfCloseFrame(header);
|
||||
case NetworkTunnelFrameType.Close:
|
||||
return decodeCloseFrame(header);
|
||||
case NetworkTunnelFrameType.Ping:
|
||||
return decodePingPongFrame("ping", header);
|
||||
case NetworkTunnelFrameType.Pong:
|
||||
return decodePingPongFrame("pong", header);
|
||||
default:
|
||||
throw new NetworkTunnelCodecError(
|
||||
"unknown_frame_type",
|
||||
`Unknown network tunnel frame type: ${header.frameType}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -133,7 +133,6 @@ const INBOUND_PERMISSION = {
|
||||
"loop/logs": "automation.manage",
|
||||
"loop/run": "automation.manage",
|
||||
"loop/stop": "automation.manage",
|
||||
"network.tunnel.create_ticket.request": "workspace.write",
|
||||
open_in_editor_request: "workspace.write",
|
||||
open_project_request: "workspace.manage",
|
||||
paseo_worktree_archive_request: "workspace.manage",
|
||||
@@ -392,7 +391,6 @@ const OUTBOUND_PERMISSION = {
|
||||
"loop/logs/response": "automation.manage",
|
||||
"loop/run/response": "automation.manage",
|
||||
"loop/stop/response": "automation.manage",
|
||||
"network.tunnel.create_ticket.response": "workspace.write",
|
||||
open_in_editor_response: "workspace.read",
|
||||
open_project_response: "workspace.manage",
|
||||
paseo_worktree_archive_response: "workspace.manage",
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
import type pino from "pino";
|
||||
import type { DaemonPermission } from "../authorization/index.js";
|
||||
import {
|
||||
NetworkTunnelTicketStore,
|
||||
type IssuedTunnelTicket,
|
||||
type NetworkTunnelTicketStoreOptions,
|
||||
type TunnelTicketIdentity,
|
||||
} from "./internal/ticket-store.js";
|
||||
import type { HostResolver } from "./internal/destination-policy.js";
|
||||
import { TunnelSession, type TunnelSocketLike } from "./internal/tunnel-session.js";
|
||||
|
||||
export type { IssuedTunnelTicket, TunnelSocketLike, TunnelTicketIdentity };
|
||||
|
||||
export interface NetworkTunnelServiceOptions {
|
||||
ticketStore?: NetworkTunnelTicketStoreOptions;
|
||||
maxConcurrentStreams?: number;
|
||||
maxFramePayloadBytes?: number;
|
||||
initialStreamWindowBytes?: number;
|
||||
initialConnectionWindowBytes?: number;
|
||||
connectTimeoutMs?: number;
|
||||
idleTimeoutMs?: number;
|
||||
idleCheckIntervalMs?: number;
|
||||
resolveHost?: HostResolver;
|
||||
}
|
||||
|
||||
export class NetworkTunnelService {
|
||||
private readonly tickets: NetworkTunnelTicketStore;
|
||||
private readonly activeSessions = new Set<TunnelSession>();
|
||||
private readonly options: NetworkTunnelServiceOptions;
|
||||
|
||||
constructor(options: NetworkTunnelServiceOptions = {}) {
|
||||
this.options = options;
|
||||
this.tickets = new NetworkTunnelTicketStore(options.ticketStore);
|
||||
}
|
||||
|
||||
get activeSessionCount(): number {
|
||||
return this.activeSessions.size;
|
||||
}
|
||||
|
||||
createTicket(identity: {
|
||||
principalId: string;
|
||||
permissions: readonly DaemonPermission[];
|
||||
}): IssuedTunnelTicket {
|
||||
return this.tickets.issue(identity);
|
||||
}
|
||||
|
||||
redeemTicket(ticket: string): TunnelTicketIdentity | null {
|
||||
return this.tickets.redeem(ticket);
|
||||
}
|
||||
|
||||
attachTunnelSocket(
|
||||
ws: TunnelSocketLike,
|
||||
params: {
|
||||
principalId: string;
|
||||
logger: pino.Logger;
|
||||
},
|
||||
): TunnelSession {
|
||||
const session = new TunnelSession({
|
||||
ws,
|
||||
principalId: params.principalId,
|
||||
logger: params.logger,
|
||||
maxConcurrentStreams: this.options.maxConcurrentStreams,
|
||||
maxFramePayloadBytes: this.options.maxFramePayloadBytes,
|
||||
initialStreamWindowBytes: this.options.initialStreamWindowBytes,
|
||||
initialConnectionWindowBytes: this.options.initialConnectionWindowBytes,
|
||||
connectTimeoutMs: this.options.connectTimeoutMs,
|
||||
idleTimeoutMs: this.options.idleTimeoutMs,
|
||||
idleCheckIntervalMs: this.options.idleCheckIntervalMs,
|
||||
resolveHost: this.options.resolveHost,
|
||||
onClose: () => {
|
||||
this.activeSessions.delete(session);
|
||||
},
|
||||
});
|
||||
if (!session.isClosed) {
|
||||
this.activeSessions.add(session);
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
revokePrincipal(principalId: string): void {
|
||||
this.tickets.revokePrincipal(principalId);
|
||||
for (const session of Array.from(this.activeSessions)) {
|
||||
if (session.principalId === principalId) {
|
||||
session.close(4401, "Tunnel permission revoked");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.tickets.clear();
|
||||
for (const session of Array.from(this.activeSessions)) {
|
||||
session.close(1001, "Server shutting down");
|
||||
}
|
||||
this.activeSessions.clear();
|
||||
}
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
isBlockedTunnelIp,
|
||||
resolveAndValidateTunnelDestination,
|
||||
type HostResolver,
|
||||
} from "./destination-policy.js";
|
||||
|
||||
describe("destination SSRF & DNS-rebinding policy", () => {
|
||||
it.each([
|
||||
"169.254.169.254",
|
||||
"169.254.0.1",
|
||||
"169.254.255.255",
|
||||
"100.100.100.200",
|
||||
"fe80::1",
|
||||
"FE80::abcd:1234",
|
||||
"febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
|
||||
"fe80::1%eth0",
|
||||
"fd00:ec2::254",
|
||||
"fd00:0ec2:0000:0000:0000:0000:0000:0254",
|
||||
"::ffff:169.254.169.254",
|
||||
"::ffff:a9fe:a9fe",
|
||||
"0:0:0:0:0:ffff:a9fe:a9fe",
|
||||
"::ffff:100.100.100.200",
|
||||
"::ffff:6464:64c8",
|
||||
])("blocks metadata and link-local address %s", (ip) => {
|
||||
expect(isBlockedTunnelIp(ip)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"127.0.0.1",
|
||||
"127.0.0.2",
|
||||
"::1",
|
||||
"::ffff:127.0.0.1",
|
||||
"10.0.0.5",
|
||||
"192.168.1.10",
|
||||
"172.16.0.1",
|
||||
"93.184.216.34",
|
||||
"2606:2800:220:1:248:1893:25c8:1946",
|
||||
"fc00::1",
|
||||
"fd00:ec2::253",
|
||||
"100.100.100.201",
|
||||
"169.253.255.255",
|
||||
"169.255.0.1",
|
||||
])("allows loopback, ordinary private, and public address %s", (ip) => {
|
||||
expect(isBlockedTunnelIp(ip)).toBe(false);
|
||||
});
|
||||
|
||||
it("blocks cloud metadata hostnames before DNS resolution", async () => {
|
||||
let called = false;
|
||||
const resolveHost: HostResolver = async () => {
|
||||
called = true;
|
||||
return [{ address: "127.0.0.1", family: 4 }];
|
||||
};
|
||||
|
||||
for (const host of [
|
||||
"metadata.google.internal",
|
||||
"METADATA.GOOGLE.INTERNAL.",
|
||||
"sub.metadata.google.internal",
|
||||
"metadata.goog",
|
||||
"metadata.goog.",
|
||||
]) {
|
||||
const result = await resolveAndValidateTunnelDestination(host, 80, resolveHost);
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
code: "policy_denied",
|
||||
message: expect.stringContaining("blocked"),
|
||||
});
|
||||
}
|
||||
expect(called).toBe(false);
|
||||
});
|
||||
|
||||
it("resolves hostname once and returns validated IPs so caller dials IP directly", async () => {
|
||||
let lookups = 0;
|
||||
const resolveHost: HostResolver = async (host) => {
|
||||
lookups += 1;
|
||||
expect(host).toBe("example.test");
|
||||
return [{ address: "93.184.216.34", family: 4 }];
|
||||
};
|
||||
|
||||
const result = await resolveAndValidateTunnelDestination("example.test", 443, resolveHost);
|
||||
expect(lookups).toBe(1);
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
addresses: [{ address: "93.184.216.34", family: 4 }],
|
||||
port: 443,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects hostnames that resolve to any blocked address (mixed DNS rebinding defense)", async () => {
|
||||
const resolveHost: HostResolver = async () => [
|
||||
{ address: "93.184.216.34", family: 4 },
|
||||
{ address: "::ffff:169.254.169.254", family: 6 },
|
||||
];
|
||||
|
||||
const result = await resolveAndValidateTunnelDestination(
|
||||
"rebind.attacker.test",
|
||||
80,
|
||||
resolveHost,
|
||||
);
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
code: "policy_denied",
|
||||
message: expect.stringContaining("blocked"),
|
||||
});
|
||||
});
|
||||
|
||||
it("allows bracketed IPv6 loopback and *.localhost fallback when DNS returns ENOTFOUND", async () => {
|
||||
const ipv6 = await resolveAndValidateTunnelDestination("[::1]", 5173, async () => {
|
||||
throw new Error("should not call DNS for IP literals");
|
||||
});
|
||||
expect(ipv6).toEqual({
|
||||
ok: true,
|
||||
addresses: [{ address: "::1", family: 6 }],
|
||||
port: 5173,
|
||||
});
|
||||
|
||||
const serviceLocalhost = await resolveAndValidateTunnelDestination(
|
||||
"web.localhost",
|
||||
6768,
|
||||
async () => {
|
||||
const err = new Error("ENOTFOUND") as NodeJS.ErrnoException;
|
||||
err.code = "ENOTFOUND";
|
||||
throw err;
|
||||
},
|
||||
);
|
||||
expect(serviceLocalhost).toEqual({
|
||||
ok: true,
|
||||
addresses: [{ address: "127.0.0.1", family: 4 }],
|
||||
port: 6768,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns dns_failed when non-localhost hostname resolution fails", async () => {
|
||||
const result = await resolveAndValidateTunnelDestination(
|
||||
"does-not-exist.invalid",
|
||||
80,
|
||||
async () => {
|
||||
const err = new Error("getaddrinfo ENOTFOUND") as NodeJS.ErrnoException;
|
||||
err.code = "ENOTFOUND";
|
||||
throw err;
|
||||
},
|
||||
);
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
code: "dns_failed",
|
||||
message: expect.stringContaining("ENOTFOUND"),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,243 +0,0 @@
|
||||
import { lookup } from "node:dns/promises";
|
||||
import { isIP } from "node:net";
|
||||
|
||||
export interface ResolvedAddress {
|
||||
address: string;
|
||||
family: 4 | 6;
|
||||
}
|
||||
|
||||
export type HostResolver = (host: string) => Promise<ResolvedAddress[]>;
|
||||
|
||||
export type TunnelDestinationResolution =
|
||||
| {
|
||||
ok: true;
|
||||
addresses: ResolvedAddress[];
|
||||
port: number;
|
||||
}
|
||||
| {
|
||||
ok: false;
|
||||
code: "policy_denied" | "dns_failed" | "invalid_destination";
|
||||
message: string;
|
||||
};
|
||||
|
||||
const BLOCKED_METADATA_HOSTS = new Set(["metadata.google.internal", "metadata.goog"]);
|
||||
// fd00:ec2::254/128 — AWS IPv6 IMDSv2
|
||||
const AWS_IPV6_METADATA_BYTES = new Uint8Array([
|
||||
0xfd, 0x00, 0x0e, 0xc2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x02, 0x54,
|
||||
]);
|
||||
// ::ffff:0:0/96 — IPv4-mapped IPv6 prefix (first 12 bytes)
|
||||
const IPV4_MAPPED_IPV6_PREFIX = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff]);
|
||||
|
||||
async function defaultHostResolver(host: string): Promise<ResolvedAddress[]> {
|
||||
const results = await lookup(host, { all: true, verbatim: true });
|
||||
return results.map((entry) => ({
|
||||
address: entry.address,
|
||||
family: entry.family === 6 ? 6 : 4,
|
||||
}));
|
||||
}
|
||||
|
||||
function stripIpv6Brackets(host: string): string {
|
||||
return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
|
||||
}
|
||||
|
||||
function normalizeHostname(host: string): string {
|
||||
return host.toLowerCase().replace(/\.+$/, "");
|
||||
}
|
||||
|
||||
function isLocalhostName(normalizedHost: string): boolean {
|
||||
return normalizedHost === "localhost" || normalizedHost.endsWith(".localhost");
|
||||
}
|
||||
|
||||
function isBlockedMetadataHostname(normalizedHost: string): boolean {
|
||||
if (BLOCKED_METADATA_HOSTS.has(normalizedHost)) return true;
|
||||
if (normalizedHost.endsWith(".metadata.google.internal")) return true;
|
||||
if (normalizedHost.endsWith(".metadata.goog")) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function bytesMatchPrefix(bytes: Uint8Array, prefix: Uint8Array): boolean {
|
||||
for (let i = 0; i < prefix.length; i += 1) {
|
||||
if (bytes[i] !== prefix[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function parseIpv4Bytes(ip: string): Uint8Array | null {
|
||||
const parts = ip.split(".");
|
||||
if (parts.length !== 4) return null;
|
||||
const out = new Uint8Array(4);
|
||||
for (let i = 0; i < 4; i += 1) {
|
||||
const part = parts[i]!;
|
||||
if (!/^(?:0|[1-9][0-9]{0,2})$/.test(part)) return null;
|
||||
const value = Number(part);
|
||||
if (value < 0 || value > 255) return null;
|
||||
out[i] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function parseIpv6Group(group: string): number | null {
|
||||
if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return null;
|
||||
return Number.parseInt(group, 16);
|
||||
}
|
||||
|
||||
function expandIpv6Half(half: string, allowEmbeddedIpv4: boolean): number[] | null {
|
||||
if (half.length === 0) return [];
|
||||
const tokens = half.split(":");
|
||||
const groups: number[] = [];
|
||||
for (let i = 0; i < tokens.length; i += 1) {
|
||||
const token = tokens[i]!;
|
||||
if (allowEmbeddedIpv4 && i === tokens.length - 1 && token.includes(".")) {
|
||||
const ipv4 = parseIpv4Bytes(token);
|
||||
if (!ipv4) return null;
|
||||
groups.push((ipv4[0]! << 8) | ipv4[1]!, (ipv4[2]! << 8) | ipv4[3]!);
|
||||
} else {
|
||||
const parsed = parseIpv6Group(token);
|
||||
if (parsed === null) return null;
|
||||
groups.push(parsed);
|
||||
}
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
function parseIpv6Bytes(rawIp: string): Uint8Array | null {
|
||||
const zoneIndex = rawIp.indexOf("%");
|
||||
const ip = zoneIndex >= 0 ? rawIp.slice(0, zoneIndex) : rawIp;
|
||||
if (ip.length === 0) return null;
|
||||
|
||||
const doubleColonParts = ip.split("::");
|
||||
if (doubleColonParts.length > 2) return null;
|
||||
|
||||
let groups: number[];
|
||||
if (doubleColonParts.length === 1) {
|
||||
const all = expandIpv6Half(doubleColonParts[0]!, true);
|
||||
if (!all || all.length !== 8) return null;
|
||||
groups = all;
|
||||
} else {
|
||||
const left = expandIpv6Half(doubleColonParts[0]!, false);
|
||||
const right = expandIpv6Half(doubleColonParts[1]!, true);
|
||||
if (!left || !right) return null;
|
||||
const missing = 8 - (left.length + right.length);
|
||||
if (missing < 1) return null;
|
||||
groups = [...left, ...Array.from({ length: missing }, () => 0), ...right];
|
||||
}
|
||||
|
||||
const out = new Uint8Array(16);
|
||||
for (let i = 0; i < 8; i += 1) {
|
||||
const value = groups[i]!;
|
||||
out[i * 2] = (value >> 8) & 0xff;
|
||||
out[i * 2 + 1] = value & 0xff;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function isBlockedIpv4Bytes(bytes: Uint8Array): boolean {
|
||||
const a = bytes[0]!;
|
||||
const b = bytes[1]!;
|
||||
const c = bytes[2]!;
|
||||
const d = bytes[3]!;
|
||||
// 169.254.0.0/16 — link-local & cloud metadata (AWS, GCP, Azure, DigitalOcean, etc.)
|
||||
if (a === 169 && b === 254) return true;
|
||||
// 100.100.100.200/32 — Alibaba Cloud metadata
|
||||
return a === 100 && b === 100 && c === 100 && d === 200;
|
||||
}
|
||||
|
||||
function isBlockedIpv6Bytes(bytes: Uint8Array): boolean {
|
||||
// fe80::/10 — IPv6 link-local (fe80:: through febf::)
|
||||
if (bytes[0] === 0xfe && (bytes[1]! & 0xc0) === 0x80) return true;
|
||||
// fd00:ec2::254/128 — AWS IPv6 IMDSv2
|
||||
if (bytesMatchPrefix(bytes, AWS_IPV6_METADATA_BYTES)) return true;
|
||||
// ::ffff:0:0/96 — IPv4-mapped IPv6
|
||||
if (bytesMatchPrefix(bytes, IPV4_MAPPED_IPV6_PREFIX)) {
|
||||
return isBlockedIpv4Bytes(bytes.subarray(12, 16));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function isBlockedTunnelIp(ip: string): boolean {
|
||||
const unbracketed = stripIpv6Brackets(ip.trim());
|
||||
const ipv4 = parseIpv4Bytes(unbracketed);
|
||||
if (ipv4) return isBlockedIpv4Bytes(ipv4);
|
||||
const ipv6 = parseIpv6Bytes(unbracketed);
|
||||
if (ipv6) return isBlockedIpv6Bytes(ipv6);
|
||||
// Unknown / unparseable IP fails closed.
|
||||
return true;
|
||||
}
|
||||
|
||||
async function resolveHostnameAddresses(
|
||||
normalized: string,
|
||||
resolveHost: HostResolver,
|
||||
): Promise<{ ok: true; addresses: ResolvedAddress[] } | { ok: false; message: string }> {
|
||||
try {
|
||||
const resolved = await resolveHost(normalized);
|
||||
if (resolved.length > 0) {
|
||||
return { ok: true, addresses: resolved };
|
||||
}
|
||||
if (isLocalhostName(normalized)) {
|
||||
return { ok: true, addresses: [{ address: "127.0.0.1", family: 4 }] };
|
||||
}
|
||||
return { ok: false, message: `No DNS records found for ${normalized}` };
|
||||
} catch (error) {
|
||||
// RFC 6761: *.localhost always maps to loopback even when the stub resolver lacks it.
|
||||
if (isLocalhostName(normalized)) {
|
||||
return { ok: true, addresses: [{ address: "127.0.0.1", family: 4 }] };
|
||||
}
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
return { ok: false, message: `Failed to resolve ${normalized}: ${message}` };
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveAndValidateTunnelDestination(
|
||||
rawHost: string,
|
||||
port: number,
|
||||
resolveHost: HostResolver = defaultHostResolver,
|
||||
): Promise<TunnelDestinationResolution> {
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
||||
return { ok: false, code: "invalid_destination", message: `Invalid destination port: ${port}` };
|
||||
}
|
||||
|
||||
const trimmed = rawHost.trim();
|
||||
if (trimmed.length === 0 || trimmed.includes("\0") || /\s/.test(trimmed)) {
|
||||
return { ok: false, code: "invalid_destination", message: "Invalid destination host" };
|
||||
}
|
||||
|
||||
const unbracketed = stripIpv6Brackets(trimmed);
|
||||
const ipVersion = isIP(unbracketed.split("%")[0] ?? unbracketed);
|
||||
if (ipVersion === 4 || ipVersion === 6) {
|
||||
if (isBlockedTunnelIp(unbracketed)) {
|
||||
return {
|
||||
ok: false,
|
||||
code: "policy_denied",
|
||||
message: `Destination address is blocked by daemon tunnel policy: ${unbracketed}`,
|
||||
};
|
||||
}
|
||||
return { ok: true, addresses: [{ address: unbracketed, family: ipVersion }], port };
|
||||
}
|
||||
|
||||
const normalized = normalizeHostname(unbracketed);
|
||||
if (isBlockedMetadataHostname(normalized)) {
|
||||
return {
|
||||
ok: false,
|
||||
code: "policy_denied",
|
||||
message: `Destination hostname is blocked by daemon tunnel policy: ${normalized}`,
|
||||
};
|
||||
}
|
||||
|
||||
const resolved = await resolveHostnameAddresses(normalized, resolveHost);
|
||||
if (!resolved.ok) {
|
||||
return { ok: false, code: "dns_failed", message: resolved.message };
|
||||
}
|
||||
|
||||
// Fail closed if ANY resolved record points to a blocked address.
|
||||
for (const entry of resolved.addresses) {
|
||||
if (isBlockedTunnelIp(entry.address)) {
|
||||
return {
|
||||
ok: false,
|
||||
code: "policy_denied",
|
||||
message: `Destination ${normalized} resolved to blocked address ${entry.address}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { ok: true, addresses: resolved.addresses, port };
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { NetworkTunnelTicketStore } from "./ticket-store.js";
|
||||
|
||||
describe("NetworkTunnelTicketStore", () => {
|
||||
it("issues single-use tickets with 30s TTL carrying principalId and permissions", () => {
|
||||
let now = 1_000_000;
|
||||
const store = new NetworkTunnelTicketStore({ clock: () => now });
|
||||
|
||||
const issued = store.issue({
|
||||
principalId: "principal-1",
|
||||
permissions: ["workspace.read", "workspace.write"],
|
||||
});
|
||||
expect(issued.ticket.length).toBeGreaterThanOrEqual(32);
|
||||
expect(issued.expiresAtMs).toBe(now + 30_000);
|
||||
|
||||
now += 15_000;
|
||||
const redeemed = store.redeem(issued.ticket);
|
||||
expect(redeemed).toEqual({
|
||||
principalId: "principal-1",
|
||||
permissions: ["workspace.read", "workspace.write"],
|
||||
});
|
||||
|
||||
// Replay must fail closed
|
||||
expect(store.redeem(issued.ticket)).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects expired tickets and purges them", () => {
|
||||
let now = 2_000_000;
|
||||
const store = new NetworkTunnelTicketStore({ clock: () => now, ttlMs: 30_000 });
|
||||
|
||||
const issued = store.issue({
|
||||
principalId: "principal-1",
|
||||
permissions: ["workspace.write"],
|
||||
});
|
||||
|
||||
now += 30_000;
|
||||
expect(store.redeem(issued.ticket)).toBeNull();
|
||||
expect(store.size).toBe(0);
|
||||
});
|
||||
|
||||
it("bounds stored ticket count by evicting expired then oldest tickets", () => {
|
||||
let now = 3_000_000;
|
||||
let seq = 0;
|
||||
const store = new NetworkTunnelTicketStore({
|
||||
clock: () => now,
|
||||
ttlMs: 30_000,
|
||||
maxTickets: 2,
|
||||
generateToken: () => `ticket-${++seq}`,
|
||||
});
|
||||
|
||||
const first = store.issue({ principalId: "p1", permissions: ["workspace.write"] });
|
||||
now += 1_000;
|
||||
const second = store.issue({ principalId: "p2", permissions: ["workspace.write"] });
|
||||
now += 1_000;
|
||||
const third = store.issue({ principalId: "p3", permissions: ["workspace.write"] });
|
||||
|
||||
expect(store.size).toBe(2);
|
||||
expect(store.redeem(first.ticket)).toBeNull();
|
||||
expect(store.redeem(second.ticket)?.principalId).toBe("p2");
|
||||
expect(store.redeem(third.ticket)?.principalId).toBe("p3");
|
||||
});
|
||||
|
||||
it("revokes all outstanding tickets for a principal", () => {
|
||||
const store = new NetworkTunnelTicketStore();
|
||||
const t1 = store.issue({ principalId: "p1", permissions: ["workspace.write"] });
|
||||
const t2 = store.issue({ principalId: "p1", permissions: ["workspace.write"] });
|
||||
const other = store.issue({ principalId: "p2", permissions: ["workspace.write"] });
|
||||
|
||||
store.revokePrincipal("p1");
|
||||
|
||||
expect(store.redeem(t1.ticket)).toBeNull();
|
||||
expect(store.redeem(t2.ticket)).toBeNull();
|
||||
expect(store.redeem(other.ticket)?.principalId).toBe("p2");
|
||||
});
|
||||
});
|
||||
@@ -1,98 +0,0 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import type { DaemonPermission } from "../../authorization/index.js";
|
||||
|
||||
export const DEFAULT_TUNNEL_TICKET_TTL_MS = 30_000;
|
||||
export const DEFAULT_MAX_TUNNEL_TICKETS = 1024;
|
||||
|
||||
export interface TunnelTicketIdentity {
|
||||
principalId: string;
|
||||
permissions: readonly DaemonPermission[];
|
||||
}
|
||||
|
||||
export interface IssuedTunnelTicket {
|
||||
ticket: string;
|
||||
expiresAtMs: number;
|
||||
}
|
||||
|
||||
interface StoredTunnelTicket extends TunnelTicketIdentity {
|
||||
expiresAtMs: number;
|
||||
}
|
||||
|
||||
export interface NetworkTunnelTicketStoreOptions {
|
||||
ttlMs?: number;
|
||||
maxTickets?: number;
|
||||
clock?: () => number;
|
||||
generateToken?: () => string;
|
||||
}
|
||||
|
||||
export class NetworkTunnelTicketStore {
|
||||
private readonly tickets = new Map<string, StoredTunnelTicket>();
|
||||
private readonly ttlMs: number;
|
||||
private readonly maxTickets: number;
|
||||
private readonly clock: () => number;
|
||||
private readonly generateToken: () => string;
|
||||
|
||||
constructor(options: NetworkTunnelTicketStoreOptions = {}) {
|
||||
this.ttlMs = options.ttlMs ?? DEFAULT_TUNNEL_TICKET_TTL_MS;
|
||||
this.maxTickets = options.maxTickets ?? DEFAULT_MAX_TUNNEL_TICKETS;
|
||||
this.clock = options.clock ?? Date.now;
|
||||
this.generateToken = options.generateToken ?? (() => randomBytes(32).toString("base64url"));
|
||||
}
|
||||
|
||||
get size(): number {
|
||||
return this.tickets.size;
|
||||
}
|
||||
|
||||
issue(identity: TunnelTicketIdentity): IssuedTunnelTicket {
|
||||
const now = this.clock();
|
||||
this.purgeExpired(now);
|
||||
while (this.tickets.size >= this.maxTickets) {
|
||||
const oldestKey = this.tickets.keys().next().value;
|
||||
if (oldestKey === undefined) break;
|
||||
this.tickets.delete(oldestKey);
|
||||
}
|
||||
|
||||
const ticket = this.generateToken();
|
||||
const expiresAtMs = now + this.ttlMs;
|
||||
this.tickets.set(ticket, {
|
||||
principalId: identity.principalId,
|
||||
permissions: [...identity.permissions],
|
||||
expiresAtMs,
|
||||
});
|
||||
return { ticket, expiresAtMs };
|
||||
}
|
||||
|
||||
redeem(ticket: string): TunnelTicketIdentity | null {
|
||||
const stored = this.tickets.get(ticket);
|
||||
if (!stored) return null;
|
||||
// Single-use: always delete immediately upon lookup.
|
||||
this.tickets.delete(ticket);
|
||||
if (this.clock() >= stored.expiresAtMs) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
principalId: stored.principalId,
|
||||
permissions: stored.permissions,
|
||||
};
|
||||
}
|
||||
|
||||
revokePrincipal(principalId: string): void {
|
||||
for (const [ticket, stored] of this.tickets) {
|
||||
if (stored.principalId === principalId) {
|
||||
this.tickets.delete(ticket);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.tickets.clear();
|
||||
}
|
||||
|
||||
private purgeExpired(now: number): void {
|
||||
for (const [ticket, stored] of this.tickets) {
|
||||
if (now >= stored.expiresAtMs) {
|
||||
this.tickets.delete(ticket);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,385 +0,0 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { createServer, type AddressInfo, type Server, type Socket } from "node:net";
|
||||
import pino from "pino";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
decodeNetworkTunnelFrame,
|
||||
encodeNetworkTunnelFrame,
|
||||
NetworkTunnelCloseReason,
|
||||
type DecodedNetworkTunnelFrame,
|
||||
type NetworkTunnelFrame,
|
||||
} from "@getpaseo/protocol/network-tunnel";
|
||||
import { TunnelSession, type TunnelSocketLike } from "./tunnel-session.js";
|
||||
|
||||
class InMemoryTunnelSocket implements TunnelSocketLike {
|
||||
readyState = 1;
|
||||
bufferedAmount = 0;
|
||||
readonly sentText: string[] = [];
|
||||
readonly sentFrames: DecodedNetworkTunnelFrame[] = [];
|
||||
readonly closes: Array<{ code?: number; reason?: string }> = [];
|
||||
private readonly emitter = new EventEmitter();
|
||||
private readonly frameWaiters: Array<{
|
||||
predicate: (frame: DecodedNetworkTunnelFrame) => boolean;
|
||||
resolve: (frame: DecodedNetworkTunnelFrame) => void;
|
||||
}> = [];
|
||||
|
||||
send(data: string | Uint8Array | ArrayBuffer, callback?: (error?: Error) => void): void {
|
||||
if (typeof data === "string") {
|
||||
this.sentText.push(data);
|
||||
} else {
|
||||
const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
|
||||
const decoded = decodeNetworkTunnelFrame(bytes);
|
||||
this.sentFrames.push(decoded);
|
||||
for (let i = 0; i < this.frameWaiters.length; i += 1) {
|
||||
const waiter = this.frameWaiters[i]!;
|
||||
if (waiter.predicate(decoded)) {
|
||||
this.frameWaiters.splice(i, 1);
|
||||
waiter.resolve(decoded);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
callback?.();
|
||||
}
|
||||
|
||||
close(code?: number, reason?: string): void {
|
||||
if (this.readyState === 3) return;
|
||||
this.readyState = 3;
|
||||
this.closes.push({ code, reason });
|
||||
this.emitter.emit("close", code ?? 1000, reason ?? "");
|
||||
}
|
||||
|
||||
terminate(): void {
|
||||
this.close(1006, "terminated");
|
||||
}
|
||||
|
||||
on(event: "message" | "close" | "error", listener: (...args: unknown[]) => void): void {
|
||||
this.emitter.on(event, listener);
|
||||
}
|
||||
|
||||
once(event: "close" | "error", listener: (...args: unknown[]) => void): void {
|
||||
this.emitter.once(event, listener);
|
||||
}
|
||||
|
||||
receiveFrame(frame: NetworkTunnelFrame): void {
|
||||
const encoded = encodeNetworkTunnelFrame(frame);
|
||||
this.emitter.emit("message", Buffer.from(encoded), true);
|
||||
}
|
||||
|
||||
waitForFrame(
|
||||
predicate: (frame: DecodedNetworkTunnelFrame) => boolean,
|
||||
timeoutMs = 5_000,
|
||||
): Promise<DecodedNetworkTunnelFrame> {
|
||||
const existing = this.sentFrames.find(predicate);
|
||||
if (existing) return Promise.resolve(existing);
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
reject(new Error("Timed out waiting for tunnel frame"));
|
||||
}, timeoutMs);
|
||||
this.frameWaiters.push({
|
||||
predicate,
|
||||
resolve: (frame) => {
|
||||
clearTimeout(timer);
|
||||
resolve(frame);
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const logger = pino({ level: "silent" });
|
||||
const servers: Server[] = [];
|
||||
const sessions: TunnelSession[] = [];
|
||||
|
||||
async function startTcpServer(onConnection: (socket: Socket) => void): Promise<{
|
||||
server: Server;
|
||||
port: number;
|
||||
}> {
|
||||
const server = createServer({ allowHalfOpen: true }, onConnection);
|
||||
servers.push(server);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => resolve());
|
||||
});
|
||||
return { server, port: (server.address() as AddressInfo).port };
|
||||
}
|
||||
|
||||
function attachEchoOnEndHandler(socket: Socket): void {
|
||||
const chunks: Buffer[] = [];
|
||||
socket.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
|
||||
socket.on("end", () => {
|
||||
const received = Buffer.concat(chunks).toString("utf8");
|
||||
socket.end(`echo:${received}`);
|
||||
});
|
||||
}
|
||||
|
||||
function collectSentData(ws: InMemoryTunnelSocket): Buffer {
|
||||
return Buffer.concat(
|
||||
ws.sentFrames
|
||||
.filter((f): f is Extract<DecodedNetworkTunnelFrame, { type: "data" }> => f.type === "data")
|
||||
.map((f) => Buffer.from(f.data)),
|
||||
);
|
||||
}
|
||||
|
||||
function waitForSentDataBytes(ws: InMemoryTunnelSocket, targetBytes: number): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const deadline = setTimeout(
|
||||
() => reject(new Error(`Timed out waiting for ${targetBytes} data bytes`)),
|
||||
3_000,
|
||||
);
|
||||
const check = setInterval(() => {
|
||||
if (collectSentData(ws).byteLength >= targetBytes) {
|
||||
clearInterval(check);
|
||||
clearTimeout(deadline);
|
||||
resolve();
|
||||
}
|
||||
}, 10);
|
||||
});
|
||||
}
|
||||
|
||||
function waitForSocketClose(socket: Socket): Promise<void> {
|
||||
if (socket.destroyed) return Promise.resolve();
|
||||
return new Promise((resolve) => {
|
||||
socket.once("close", () => resolve());
|
||||
});
|
||||
}
|
||||
|
||||
function attachKeepOpenHandler(serverSockets: Socket[], socket: Socket): void {
|
||||
serverSockets.push(socket);
|
||||
socket.resume();
|
||||
socket.once("end", () => socket.end());
|
||||
}
|
||||
|
||||
function attachDrainAndCollect(socket: Socket, receivedChunks: Buffer[], onDone: () => void): void {
|
||||
socket.on("data", (chunk) => receivedChunks.push(Buffer.from(chunk)));
|
||||
socket.on("end", () => {
|
||||
socket.end();
|
||||
onDone();
|
||||
});
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
for (const session of sessions.splice(0)) {
|
||||
session.close();
|
||||
}
|
||||
await Promise.all(
|
||||
servers.splice(0).map(
|
||||
(server) =>
|
||||
new Promise<void>((resolve) => {
|
||||
server.close(() => resolve());
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
describe("TunnelSession binary TCP multiplexer", () => {
|
||||
it("sends tunnel_ready, relays bidirectional TCP data and half-close, and echoes pings", async () => {
|
||||
const { port } = await startTcpServer(attachEchoOnEndHandler);
|
||||
|
||||
const ws = new InMemoryTunnelSocket();
|
||||
const session = new TunnelSession({
|
||||
ws,
|
||||
principalId: "owner",
|
||||
logger,
|
||||
});
|
||||
sessions.push(session);
|
||||
|
||||
expect(ws.sentText).toHaveLength(1);
|
||||
expect(JSON.parse(ws.sentText[0]!)).toEqual({
|
||||
type: "tunnel_ready",
|
||||
maxFramePayloadBytes: 64 * 1024,
|
||||
initialStreamWindowBytes: 512 * 1024,
|
||||
initialConnectionWindowBytes: 4 * 1024 * 1024,
|
||||
});
|
||||
|
||||
// Ping/Pong
|
||||
const nonce = new Uint8Array([1, 2, 3, 4]);
|
||||
ws.receiveFrame({ type: "ping", payload: nonce });
|
||||
const pong = await ws.waitForFrame((frame) => frame.type === "pong");
|
||||
expect(pong).toEqual({ type: "pong", payload: nonce, flags: 0 });
|
||||
|
||||
// Open -> Data -> HalfClose -> response Data -> HalfClose
|
||||
ws.receiveFrame({ type: "open", streamId: 1, host: "127.0.0.1", port });
|
||||
const opened = await ws.waitForFrame(
|
||||
(frame) => frame.type === "opened" && frame.streamId === 1,
|
||||
);
|
||||
expect(opened.type === "opened" && opened.initialWindowBytes).toBe(512 * 1024);
|
||||
|
||||
ws.receiveFrame({
|
||||
type: "data",
|
||||
streamId: 1,
|
||||
data: new TextEncoder().encode("hello half-close"),
|
||||
});
|
||||
ws.receiveFrame({ type: "half_close", streamId: 1 });
|
||||
|
||||
await ws.waitForFrame((frame) => frame.type === "half_close" && frame.streamId === 1);
|
||||
expect(collectSentData(ws).toString("utf8")).toBe("echo:hello half-close");
|
||||
});
|
||||
|
||||
it("enforces per-stream and connection credit windows with real TCP backpressure", async () => {
|
||||
const payloadSize = 24 * 1024;
|
||||
const expected = Buffer.alloc(payloadSize);
|
||||
for (let i = 0; i < payloadSize; i += 1) expected[i] = i % 251;
|
||||
|
||||
const { port } = await startTcpServer((socket) => {
|
||||
socket.end(expected);
|
||||
});
|
||||
|
||||
const ws = new InMemoryTunnelSocket();
|
||||
const session = new TunnelSession({
|
||||
ws,
|
||||
principalId: "owner",
|
||||
logger,
|
||||
maxFramePayloadBytes: 4 * 1024,
|
||||
initialStreamWindowBytes: 8 * 1024,
|
||||
initialConnectionWindowBytes: 8 * 1024,
|
||||
});
|
||||
sessions.push(session);
|
||||
|
||||
ws.receiveFrame({ type: "open", streamId: 1, host: "127.0.0.1", port });
|
||||
await ws.waitForFrame((frame) => frame.type === "opened" && frame.streamId === 1);
|
||||
|
||||
// Wait until the initial 8 KiB window is filled.
|
||||
await waitForSentDataBytes(ws, 8 * 1024);
|
||||
|
||||
// Pause briefly to verify the daemon does NOT exceed the 8 KiB credit window.
|
||||
await new Promise((resolve) => setTimeout(resolve, 60));
|
||||
expect(collectSentData(ws).byteLength).toBe(8 * 1024);
|
||||
expect(ws.sentFrames.some((f) => f.type === "half_close")).toBe(false);
|
||||
|
||||
// Grant connection + stream credit to drain the rest of the 24 KiB payload.
|
||||
ws.receiveFrame({ type: "window_update", streamId: 0, creditBytes: 16 * 1024 });
|
||||
ws.receiveFrame({ type: "window_update", streamId: 1, creditBytes: 16 * 1024 });
|
||||
|
||||
await ws.waitForFrame((frame) => frame.type === "half_close" && frame.streamId === 1);
|
||||
expect(Buffer.compare(collectSentData(ws), expected)).toBe(0);
|
||||
});
|
||||
|
||||
it("enforces concurrent stream cap and rejects blocked SSRF destinations", async () => {
|
||||
const serverSockets: Socket[] = [];
|
||||
const { port } = await startTcpServer((socket) => attachKeepOpenHandler(serverSockets, socket));
|
||||
|
||||
const ws = new InMemoryTunnelSocket();
|
||||
const session = new TunnelSession({
|
||||
ws,
|
||||
principalId: "owner",
|
||||
logger,
|
||||
maxConcurrentStreams: 2,
|
||||
});
|
||||
sessions.push(session);
|
||||
|
||||
// Blocked metadata IP
|
||||
ws.receiveFrame({ type: "open", streamId: 99, host: "169.254.169.254", port: 80 });
|
||||
const denied = await ws.waitForFrame(
|
||||
(frame) => frame.type === "close" && frame.streamId === 99,
|
||||
);
|
||||
expect(denied.type === "close" && denied.reason).toBe(NetworkTunnelCloseReason.PolicyDenied);
|
||||
|
||||
// Fill 2 concurrent streams
|
||||
ws.receiveFrame({ type: "open", streamId: 1, host: "127.0.0.1", port });
|
||||
ws.receiveFrame({ type: "open", streamId: 2, host: "127.0.0.1", port });
|
||||
await ws.waitForFrame((frame) => frame.type === "opened" && frame.streamId === 1);
|
||||
await ws.waitForFrame((frame) => frame.type === "opened" && frame.streamId === 2);
|
||||
|
||||
// 3rd stream exceeds cap
|
||||
ws.receiveFrame({ type: "open", streamId: 3, host: "127.0.0.1", port });
|
||||
const capped = await ws.waitForFrame((frame) => frame.type === "close" && frame.streamId === 3);
|
||||
expect(capped.type === "close" && capped.reason).toBe(
|
||||
NetworkTunnelCloseReason.StreamLimitExceeded,
|
||||
);
|
||||
|
||||
// Closing the tunnel WS tears down all active upstream TCP sockets cleanly
|
||||
const allClosed = Promise.all(serverSockets.map(waitForSocketClose));
|
||||
ws.close(1000, "done");
|
||||
await allClosed;
|
||||
expect(session.activeStreamCount).toBe(0);
|
||||
});
|
||||
|
||||
it("replenishes stream and connection receive windows as uploaded data drains to TCP", async () => {
|
||||
const receivedChunks: Buffer[] = [];
|
||||
let resolveDone!: () => void;
|
||||
const allReceived = new Promise<void>((resolve) => {
|
||||
resolveDone = resolve;
|
||||
});
|
||||
const { port } = await startTcpServer((socket) => {
|
||||
attachDrainAndCollect(socket, receivedChunks, resolveDone);
|
||||
});
|
||||
|
||||
const ws = new InMemoryTunnelSocket();
|
||||
const session = new TunnelSession({
|
||||
ws,
|
||||
principalId: "owner",
|
||||
logger,
|
||||
maxFramePayloadBytes: 4 * 1024,
|
||||
initialStreamWindowBytes: 8 * 1024,
|
||||
initialConnectionWindowBytes: 8 * 1024,
|
||||
});
|
||||
sessions.push(session);
|
||||
|
||||
ws.receiveFrame({ type: "open", streamId: 1, host: "127.0.0.1", port });
|
||||
await ws.waitForFrame((frame) => frame.type === "opened" && frame.streamId === 1);
|
||||
|
||||
// Send 4 chunks of 4 KiB each (16 KiB total > 8 KiB initial window).
|
||||
const totalPayload = Buffer.alloc(16 * 1024);
|
||||
for (let i = 0; i < totalPayload.length; i += 1) totalPayload[i] = (i * 7) & 0xff;
|
||||
|
||||
ws.receiveFrame({ type: "data", streamId: 1, data: totalPayload.subarray(0, 4 * 1024) });
|
||||
ws.receiveFrame({ type: "data", streamId: 1, data: totalPayload.subarray(4 * 1024, 8 * 1024) });
|
||||
|
||||
// Daemon must replenish both stream and connection windows after draining.
|
||||
const streamUpdate = await ws.waitForFrame(
|
||||
(frame) => frame.type === "window_update" && frame.streamId === 1,
|
||||
);
|
||||
const connUpdate = await ws.waitForFrame(
|
||||
(frame) => frame.type === "window_update" && frame.streamId === 0,
|
||||
);
|
||||
expect(streamUpdate.type === "window_update" && streamUpdate.creditBytes).toBeGreaterThan(0);
|
||||
expect(connUpdate.type === "window_update" && connUpdate.creditBytes).toBeGreaterThan(0);
|
||||
|
||||
ws.receiveFrame({
|
||||
type: "data",
|
||||
streamId: 1,
|
||||
data: totalPayload.subarray(8 * 1024, 12 * 1024),
|
||||
});
|
||||
ws.receiveFrame({
|
||||
type: "data",
|
||||
streamId: 1,
|
||||
data: totalPayload.subarray(12 * 1024, 16 * 1024),
|
||||
});
|
||||
ws.receiveFrame({ type: "half_close", streamId: 1 });
|
||||
|
||||
await allReceived;
|
||||
expect(Buffer.compare(Buffer.concat(receivedChunks), totalPayload)).toBe(0);
|
||||
});
|
||||
|
||||
it("closes an idle tunnel session and tears down active TCP sockets after liveness timeout", async () => {
|
||||
const serverSockets: Socket[] = [];
|
||||
const { port } = await startTcpServer((socket) => attachKeepOpenHandler(serverSockets, socket));
|
||||
|
||||
const ws = new InMemoryTunnelSocket();
|
||||
const session = new TunnelSession({
|
||||
ws,
|
||||
principalId: "owner",
|
||||
logger,
|
||||
idleTimeoutMs: 80,
|
||||
idleCheckIntervalMs: 20,
|
||||
});
|
||||
sessions.push(session);
|
||||
|
||||
ws.receiveFrame({ type: "open", streamId: 1, host: "127.0.0.1", port });
|
||||
await ws.waitForFrame((frame) => frame.type === "opened" && frame.streamId === 1);
|
||||
expect(session.activeStreamCount).toBe(1);
|
||||
|
||||
// Keep alive briefly with a ping; session must stay open while pings arrive.
|
||||
await new Promise((r) => setTimeout(r, 45));
|
||||
ws.receiveFrame({ type: "ping" });
|
||||
await ws.waitForFrame((frame) => frame.type === "pong");
|
||||
expect(session.isClosed).toBe(false);
|
||||
|
||||
// Stop sending frames -> session closes and tears down the upstream TCP socket.
|
||||
await waitForSocketClose(serverSockets[0]!);
|
||||
expect(session.isClosed).toBe(true);
|
||||
expect(session.activeStreamCount).toBe(0);
|
||||
expect(ws.closes.at(-1)).toMatchObject({ code: 1001 });
|
||||
});
|
||||
});
|
||||
@@ -1,826 +0,0 @@
|
||||
import { Socket } from "node:net";
|
||||
import type pino from "pino";
|
||||
import {
|
||||
decodeNetworkTunnelFrame,
|
||||
encodeNetworkTunnelFrame,
|
||||
NETWORK_TUNNEL_DEFAULT_INITIAL_CONNECTION_WINDOW_BYTES,
|
||||
NETWORK_TUNNEL_DEFAULT_INITIAL_STREAM_WINDOW_BYTES,
|
||||
NETWORK_TUNNEL_MAX_CONCURRENT_STREAMS,
|
||||
NETWORK_TUNNEL_MAX_DATA_PAYLOAD_BYTES,
|
||||
NetworkTunnelCloseReason,
|
||||
NetworkTunnelCodecError,
|
||||
type DecodedNetworkTunnelFrame,
|
||||
type NetworkTunnelFrame,
|
||||
} from "@getpaseo/protocol/network-tunnel";
|
||||
import type { WSTunnelReadyMessage } from "@getpaseo/protocol/messages";
|
||||
import { sendBoundedPhysicalFrame } from "../../websocket/physical-socket.js";
|
||||
import {
|
||||
resolveAndValidateTunnelDestination,
|
||||
type HostResolver,
|
||||
type ResolvedAddress,
|
||||
} from "./destination-policy.js";
|
||||
|
||||
const DEFAULT_CONNECT_TIMEOUT_MS = 15_000;
|
||||
const DEFAULT_IDLE_TIMEOUT_MS = 45_000;
|
||||
const DEFAULT_IDLE_CHECK_INTERVAL_MS = 15_000;
|
||||
const MAX_WINDOW_BYTES = 0x7fffffff;
|
||||
|
||||
export interface TunnelSocketLike {
|
||||
readyState: number;
|
||||
bufferedAmount?: number;
|
||||
send: (
|
||||
data: string | Uint8Array | ArrayBuffer,
|
||||
callback?: (error?: Error) => void,
|
||||
) => void | Promise<void>;
|
||||
close: (code?: number, reason?: string) => void;
|
||||
terminate?: () => void;
|
||||
on: (event: "message" | "close" | "error", listener: (...args: unknown[]) => void) => void;
|
||||
once: (event: "close" | "error", listener: (...args: unknown[]) => void) => void;
|
||||
}
|
||||
|
||||
export interface TunnelSessionOptions {
|
||||
ws: TunnelSocketLike;
|
||||
principalId: string;
|
||||
logger: pino.Logger;
|
||||
maxConcurrentStreams?: number;
|
||||
maxFramePayloadBytes?: number;
|
||||
initialStreamWindowBytes?: number;
|
||||
initialConnectionWindowBytes?: number;
|
||||
connectTimeoutMs?: number;
|
||||
idleTimeoutMs?: number;
|
||||
idleCheckIntervalMs?: number;
|
||||
resolveHost?: HostResolver;
|
||||
onClose?: () => void;
|
||||
}
|
||||
|
||||
interface TunnelStreamState {
|
||||
readonly streamId: number;
|
||||
state: "connecting" | "open" | "closed";
|
||||
socket: Socket | null;
|
||||
sendWindowBytes: number;
|
||||
recvWindowBytes: number;
|
||||
uncreditedRecvBytes: number;
|
||||
pendingDrainBytes: number;
|
||||
pendingOutboundChunks: Uint8Array[];
|
||||
pendingOutboundBytes: number;
|
||||
remoteEnded: boolean;
|
||||
remoteHalfCloseSent: boolean;
|
||||
clientHalfClosed: boolean;
|
||||
tcpPaused: boolean;
|
||||
}
|
||||
|
||||
function toUint8Array(data: unknown): Uint8Array | null {
|
||||
if (Buffer.isBuffer(data)) {
|
||||
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
||||
}
|
||||
if (data instanceof Uint8Array) {
|
||||
return data;
|
||||
}
|
||||
if (data instanceof ArrayBuffer) {
|
||||
return new Uint8Array(data);
|
||||
}
|
||||
if (ArrayBuffer.isView(data)) {
|
||||
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
||||
}
|
||||
if (Array.isArray(data)) {
|
||||
const buffers: Buffer[] = [];
|
||||
for (const part of data) {
|
||||
if (Buffer.isBuffer(part)) {
|
||||
buffers.push(part);
|
||||
} else if (part instanceof ArrayBuffer) {
|
||||
buffers.push(Buffer.from(part));
|
||||
} else if (ArrayBuffer.isView(part)) {
|
||||
buffers.push(Buffer.from(part.buffer, part.byteOffset, part.byteLength));
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const merged = Buffer.concat(buffers);
|
||||
return new Uint8Array(merged.buffer, merged.byteOffset, merged.byteLength);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function mapPolicyCodeToCloseReason(
|
||||
code: "policy_denied" | "dns_failed" | "invalid_destination",
|
||||
): NetworkTunnelCloseReason {
|
||||
if (code === "policy_denied") return NetworkTunnelCloseReason.PolicyDenied;
|
||||
if (code === "dns_failed") return NetworkTunnelCloseReason.DnsFailed;
|
||||
return NetworkTunnelCloseReason.ProtocolError;
|
||||
}
|
||||
|
||||
function mapErrnoToCloseReason(error: unknown): NetworkTunnelCloseReason {
|
||||
const code = (error as NodeJS.ErrnoException | undefined)?.code;
|
||||
switch (code) {
|
||||
case "ECONNREFUSED":
|
||||
return NetworkTunnelCloseReason.ConnectRefused;
|
||||
case "EHOSTUNREACH":
|
||||
case "ENETUNREACH":
|
||||
case "EADDRNOTAVAIL":
|
||||
return NetworkTunnelCloseReason.HostUnreachable;
|
||||
case "ETIMEDOUT":
|
||||
return NetworkTunnelCloseReason.Timeout;
|
||||
case "ECONNRESET":
|
||||
case "EPIPE":
|
||||
return NetworkTunnelCloseReason.Reset;
|
||||
case "ENOTFOUND":
|
||||
case "EAI_AGAIN":
|
||||
return NetworkTunnelCloseReason.DnsFailed;
|
||||
default:
|
||||
return NetworkTunnelCloseReason.InternalError;
|
||||
}
|
||||
}
|
||||
|
||||
export class TunnelSession {
|
||||
readonly principalId: string;
|
||||
private readonly ws: TunnelSocketLike;
|
||||
private readonly logger: pino.Logger;
|
||||
private readonly maxConcurrentStreams: number;
|
||||
private readonly maxFramePayloadBytes: number;
|
||||
private readonly initialStreamWindowBytes: number;
|
||||
private readonly initialConnectionWindowBytes: number;
|
||||
private readonly streamWindowUpdateThreshold: number;
|
||||
private readonly connectionWindowUpdateThreshold: number;
|
||||
private readonly connectTimeoutMs: number;
|
||||
private readonly idleTimeoutMs: number;
|
||||
private readonly resolveHost: HostResolver | undefined;
|
||||
private readonly onCloseCallback: (() => void) | undefined;
|
||||
|
||||
private readonly streams = new Map<number, TunnelStreamState>();
|
||||
private connectionSendWindowBytes: number;
|
||||
private connectionRecvWindowBytes: number;
|
||||
private uncreditedConnectionRecvBytes = 0;
|
||||
private lastInboundAt = Date.now();
|
||||
private idleTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private closed = false;
|
||||
|
||||
constructor(options: TunnelSessionOptions) {
|
||||
this.ws = options.ws;
|
||||
this.principalId = options.principalId;
|
||||
this.logger = options.logger.child({ module: "network-tunnel-session" });
|
||||
this.maxConcurrentStreams =
|
||||
options.maxConcurrentStreams ?? NETWORK_TUNNEL_MAX_CONCURRENT_STREAMS;
|
||||
this.maxFramePayloadBytes =
|
||||
options.maxFramePayloadBytes ?? NETWORK_TUNNEL_MAX_DATA_PAYLOAD_BYTES;
|
||||
this.initialStreamWindowBytes =
|
||||
options.initialStreamWindowBytes ?? NETWORK_TUNNEL_DEFAULT_INITIAL_STREAM_WINDOW_BYTES;
|
||||
this.initialConnectionWindowBytes =
|
||||
options.initialConnectionWindowBytes ??
|
||||
NETWORK_TUNNEL_DEFAULT_INITIAL_CONNECTION_WINDOW_BYTES;
|
||||
this.streamWindowUpdateThreshold = Math.max(1, Math.floor(this.initialStreamWindowBytes / 4));
|
||||
this.connectionWindowUpdateThreshold = Math.max(
|
||||
1,
|
||||
Math.floor(this.initialConnectionWindowBytes / 4),
|
||||
);
|
||||
this.connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
|
||||
this.idleTimeoutMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
|
||||
const idleCheckIntervalMs =
|
||||
options.idleCheckIntervalMs ??
|
||||
Math.min(DEFAULT_IDLE_CHECK_INTERVAL_MS, Math.max(10, Math.floor(this.idleTimeoutMs / 3)));
|
||||
this.resolveHost = options.resolveHost;
|
||||
this.onCloseCallback = options.onClose;
|
||||
|
||||
this.connectionSendWindowBytes = this.initialConnectionWindowBytes;
|
||||
this.connectionRecvWindowBytes = this.initialConnectionWindowBytes;
|
||||
|
||||
this.bindSocket();
|
||||
this.sendReadyHandshake();
|
||||
|
||||
if (!this.closed && this.idleTimeoutMs > 0) {
|
||||
this.idleTimer = setInterval(() => {
|
||||
if (this.closed) return;
|
||||
if (Date.now() - this.lastInboundAt >= this.idleTimeoutMs) {
|
||||
this.logger.warn(
|
||||
{ idleTimeoutMs: this.idleTimeoutMs },
|
||||
"Closing idle network tunnel session after liveness timeout",
|
||||
);
|
||||
this.close(1001, "Tunnel liveness timeout");
|
||||
}
|
||||
}, idleCheckIntervalMs);
|
||||
this.idleTimer.unref?.();
|
||||
}
|
||||
}
|
||||
|
||||
get activeStreamCount(): number {
|
||||
return this.streams.size;
|
||||
}
|
||||
|
||||
get isClosed(): boolean {
|
||||
return this.closed;
|
||||
}
|
||||
|
||||
close(code = 1000, reason = "Tunnel closed"): void {
|
||||
if (this.closed) return;
|
||||
this.teardown();
|
||||
try {
|
||||
if (this.ws.readyState === 1) {
|
||||
this.ws.close(code, reason);
|
||||
}
|
||||
} catch {
|
||||
// ignore close errors on already-closing transport
|
||||
}
|
||||
}
|
||||
|
||||
private bindSocket(): void {
|
||||
this.ws.on("message", (...args: unknown[]) => {
|
||||
if (this.closed) return;
|
||||
const data = args[0];
|
||||
const isBinaryArg = args[1];
|
||||
const isBinary =
|
||||
isBinaryArg === true || (isBinaryArg === undefined && typeof data !== "string");
|
||||
if (!isBinary) {
|
||||
this.logger.warn("Received non-binary frame on active tunnel socket; closing");
|
||||
this.close(1002, "Expected binary tunnel frame");
|
||||
return;
|
||||
}
|
||||
const bytes = toUint8Array(data);
|
||||
if (!bytes) {
|
||||
this.close(1002, "Invalid binary tunnel frame");
|
||||
return;
|
||||
}
|
||||
let frame: DecodedNetworkTunnelFrame;
|
||||
try {
|
||||
frame = decodeNetworkTunnelFrame(bytes);
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof NetworkTunnelCodecError ? error.message : "Invalid tunnel frame";
|
||||
this.logger.warn({ err: error }, "Malformed tunnel frame; closing tunnel");
|
||||
this.close(1002, message);
|
||||
return;
|
||||
}
|
||||
this.lastInboundAt = Date.now();
|
||||
this.handleFrame(frame);
|
||||
});
|
||||
|
||||
this.ws.on("close", () => {
|
||||
this.teardown();
|
||||
});
|
||||
|
||||
this.ws.on("error", (error: unknown) => {
|
||||
this.logger.warn({ err: error }, "Tunnel WebSocket error");
|
||||
this.teardown();
|
||||
});
|
||||
}
|
||||
|
||||
private sendReadyHandshake(): void {
|
||||
const ready: WSTunnelReadyMessage = {
|
||||
type: "tunnel_ready",
|
||||
maxFramePayloadBytes: this.maxFramePayloadBytes,
|
||||
initialStreamWindowBytes: this.initialStreamWindowBytes,
|
||||
initialConnectionWindowBytes: this.initialConnectionWindowBytes,
|
||||
};
|
||||
const ok = sendBoundedPhysicalFrame({
|
||||
socket: this.ws,
|
||||
frame: JSON.stringify(ready),
|
||||
onHighWater: () => this.terminateForHighWater(),
|
||||
});
|
||||
if (!ok) {
|
||||
this.teardown();
|
||||
}
|
||||
}
|
||||
|
||||
private sendFrame(frame: NetworkTunnelFrame): boolean {
|
||||
if (this.closed || this.ws.readyState !== 1) return false;
|
||||
const encoded = encodeNetworkTunnelFrame(frame);
|
||||
const ok = sendBoundedPhysicalFrame({
|
||||
socket: this.ws,
|
||||
frame: encoded,
|
||||
frameBytes: encoded.byteLength,
|
||||
onHighWater: () => this.terminateForHighWater(),
|
||||
});
|
||||
if (!ok) {
|
||||
this.teardown();
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
private terminateForHighWater(): void {
|
||||
this.logger.warn("Terminating tunnel WebSocket at outbound high-water mark");
|
||||
this.teardown();
|
||||
try {
|
||||
if (this.ws.terminate) {
|
||||
this.ws.terminate();
|
||||
} else {
|
||||
this.ws.close(1008, "Outbound buffer limit exceeded");
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
private handleFrame(frame: DecodedNetworkTunnelFrame): void {
|
||||
switch (frame.type) {
|
||||
case "ping":
|
||||
this.sendFrame({ type: "pong", payload: frame.payload });
|
||||
return;
|
||||
|
||||
case "pong":
|
||||
return;
|
||||
|
||||
case "open":
|
||||
void this.handleOpen(frame.streamId, frame.host, frame.port);
|
||||
return;
|
||||
|
||||
case "data":
|
||||
this.handleInboundData(frame.streamId, frame.data);
|
||||
return;
|
||||
|
||||
case "window_update":
|
||||
this.handleWindowUpdate(frame.streamId, frame.creditBytes);
|
||||
return;
|
||||
|
||||
case "half_close":
|
||||
this.handleClientHalfClose(frame.streamId);
|
||||
return;
|
||||
|
||||
case "close":
|
||||
this.handleClientClose(frame.streamId);
|
||||
return;
|
||||
|
||||
case "opened":
|
||||
// Client must never send Opened to daemon.
|
||||
this.close(1002, "Unexpected Opened frame from client");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private async handleOpen(streamId: number, host: string, port: number): Promise<void> {
|
||||
if (this.closed) return;
|
||||
|
||||
if (this.streams.has(streamId)) {
|
||||
this.sendFrame({
|
||||
type: "close",
|
||||
streamId,
|
||||
reason: NetworkTunnelCloseReason.ProtocolError,
|
||||
message: `Duplicate streamId ${streamId}`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.streams.size >= this.maxConcurrentStreams) {
|
||||
this.sendFrame({
|
||||
type: "close",
|
||||
streamId,
|
||||
reason: NetworkTunnelCloseReason.StreamLimitExceeded,
|
||||
message: `Max concurrent streams (${this.maxConcurrentStreams}) exceeded`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Reserve stream slot before async DNS resolution so burst Opens cannot bypass the cap.
|
||||
const stream: TunnelStreamState = {
|
||||
streamId,
|
||||
state: "connecting",
|
||||
socket: null,
|
||||
sendWindowBytes: this.initialStreamWindowBytes,
|
||||
recvWindowBytes: this.initialStreamWindowBytes,
|
||||
uncreditedRecvBytes: 0,
|
||||
pendingDrainBytes: 0,
|
||||
pendingOutboundChunks: [],
|
||||
pendingOutboundBytes: 0,
|
||||
remoteEnded: false,
|
||||
remoteHalfCloseSent: false,
|
||||
clientHalfClosed: false,
|
||||
tcpPaused: false,
|
||||
};
|
||||
this.streams.set(streamId, stream);
|
||||
|
||||
const resolution = await resolveAndValidateTunnelDestination(host, port, this.resolveHost);
|
||||
if (this.isStreamInactive(stream)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!resolution.ok) {
|
||||
const reason = mapPolicyCodeToCloseReason(resolution.code);
|
||||
this.cleanupStream(stream);
|
||||
this.sendFrame({
|
||||
type: "close",
|
||||
streamId,
|
||||
reason,
|
||||
message: resolution.message,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const socket = await this.dialValidatedAddresses(
|
||||
stream,
|
||||
resolution.addresses,
|
||||
resolution.port,
|
||||
);
|
||||
if (this.isStreamInactive(stream)) {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
stream.state = "open";
|
||||
stream.socket = socket;
|
||||
socket.setNoDelay(true);
|
||||
this.attachTcpSocketHandlers(stream, socket);
|
||||
|
||||
this.sendFrame({
|
||||
type: "opened",
|
||||
streamId,
|
||||
initialWindowBytes: this.initialStreamWindowBytes,
|
||||
});
|
||||
} catch (error) {
|
||||
if (this.isStreamInactive(stream)) {
|
||||
return;
|
||||
}
|
||||
const reason = mapErrnoToCloseReason(error);
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
this.cleanupStream(stream);
|
||||
this.sendFrame({
|
||||
type: "close",
|
||||
streamId,
|
||||
reason,
|
||||
message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private isStreamInactive(stream: TunnelStreamState): boolean {
|
||||
return this.closed || stream.state === "closed" || this.streams.get(stream.streamId) !== stream;
|
||||
}
|
||||
|
||||
private async dialValidatedAddresses(
|
||||
stream: TunnelStreamState,
|
||||
addresses: ResolvedAddress[],
|
||||
port: number,
|
||||
): Promise<Socket> {
|
||||
let lastError: unknown = new Error("No addresses to dial");
|
||||
const deadlineMs = Date.now() + this.connectTimeoutMs;
|
||||
|
||||
for (const entry of addresses) {
|
||||
if (this.closed || stream.state === "closed") {
|
||||
throw new Error("Stream closed during connect");
|
||||
}
|
||||
const remainingMs = Math.max(100, deadlineMs - Date.now());
|
||||
try {
|
||||
return await this.dialSingleAddress(stream, entry, port, remainingMs);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
private dialSingleAddress(
|
||||
stream: TunnelStreamState,
|
||||
address: ResolvedAddress,
|
||||
port: number,
|
||||
timeoutMs: number,
|
||||
): Promise<Socket> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = new Socket({ allowHalfOpen: true });
|
||||
stream.socket = socket;
|
||||
let settled = false;
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
socket.destroy();
|
||||
const err = new Error(
|
||||
`TCP connect timed out after ${timeoutMs}ms`,
|
||||
) as NodeJS.ErrnoException;
|
||||
err.code = "ETIMEDOUT";
|
||||
reject(err);
|
||||
}, timeoutMs);
|
||||
|
||||
const finish = (cb: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
socket.removeListener("connect", onConnect);
|
||||
socket.removeListener("error", onError);
|
||||
socket.removeListener("close", onClose);
|
||||
cb();
|
||||
};
|
||||
|
||||
const onConnect = () => finish(() => resolve(socket));
|
||||
const onError = (err: Error) =>
|
||||
finish(() => {
|
||||
socket.destroy();
|
||||
reject(err);
|
||||
});
|
||||
const onClose = () =>
|
||||
finish(() => {
|
||||
reject(new Error("TCP socket closed before connect completed"));
|
||||
});
|
||||
|
||||
socket.once("connect", onConnect);
|
||||
socket.once("error", onError);
|
||||
socket.once("close", onClose);
|
||||
|
||||
// Pass the already-validated IP directly with a pinned lookup callback so Node never re-resolves DNS.
|
||||
socket.connect({
|
||||
host: address.address,
|
||||
port,
|
||||
family: address.family,
|
||||
lookup: (_hostname, _options, callback) => {
|
||||
callback(null, address.address, address.family);
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private attachTcpSocketHandlers(stream: TunnelStreamState, socket: Socket): void {
|
||||
socket.on("data", (chunk: Buffer) => {
|
||||
if (this.closed || stream.state !== "open") return;
|
||||
if (chunk.byteLength === 0) return;
|
||||
const bytes = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
|
||||
stream.pendingOutboundChunks.push(bytes.slice());
|
||||
stream.pendingOutboundBytes += bytes.byteLength;
|
||||
this.flushStreamOutbound(stream);
|
||||
});
|
||||
|
||||
socket.on("drain", () => {
|
||||
if (this.closed || stream.state !== "open") return;
|
||||
if (stream.pendingDrainBytes > 0) {
|
||||
const drained = stream.pendingDrainBytes;
|
||||
stream.pendingDrainBytes = 0;
|
||||
this.creditInboundConsumed(stream, drained);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("end", () => {
|
||||
if (this.closed || stream.state !== "open") return;
|
||||
stream.remoteEnded = true;
|
||||
this.flushStreamOutbound(stream);
|
||||
});
|
||||
|
||||
socket.on("error", (error: Error) => {
|
||||
if (this.closed || stream.state === "closed") return;
|
||||
const reason = mapErrnoToCloseReason(error);
|
||||
this.cleanupStream(stream);
|
||||
this.sendFrame({
|
||||
type: "close",
|
||||
streamId: stream.streamId,
|
||||
reason,
|
||||
message: error.message,
|
||||
});
|
||||
});
|
||||
|
||||
socket.on("close", (hadError: boolean) => {
|
||||
if (this.closed || stream.state === "closed") return;
|
||||
if (!hadError && stream.remoteEnded && stream.pendingOutboundBytes > 0) {
|
||||
// TCP FIN arrived; keep draining buffered outbound chunks until credit lets us flush them.
|
||||
return;
|
||||
}
|
||||
const reason = hadError
|
||||
? NetworkTunnelCloseReason.Reset
|
||||
: NetworkTunnelCloseReason.RemoteClosed;
|
||||
this.cleanupStream(stream);
|
||||
this.sendFrame({
|
||||
type: "close",
|
||||
streamId: stream.streamId,
|
||||
reason,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private flushStreamOutbound(stream: TunnelStreamState): void {
|
||||
if (this.closed || stream.state !== "open") return;
|
||||
|
||||
while (
|
||||
stream.pendingOutboundChunks.length > 0 &&
|
||||
stream.sendWindowBytes > 0 &&
|
||||
this.connectionSendWindowBytes > 0
|
||||
) {
|
||||
const budget = Math.min(
|
||||
this.maxFramePayloadBytes,
|
||||
stream.sendWindowBytes,
|
||||
this.connectionSendWindowBytes,
|
||||
);
|
||||
const head = stream.pendingOutboundChunks[0]!;
|
||||
let slice: Uint8Array;
|
||||
if (head.byteLength <= budget) {
|
||||
slice = head;
|
||||
stream.pendingOutboundChunks.shift();
|
||||
} else {
|
||||
slice = head.subarray(0, budget);
|
||||
stream.pendingOutboundChunks[0] = head.subarray(budget);
|
||||
}
|
||||
stream.pendingOutboundBytes -= slice.byteLength;
|
||||
stream.sendWindowBytes -= slice.byteLength;
|
||||
this.connectionSendWindowBytes -= slice.byteLength;
|
||||
|
||||
if (!this.sendFrame({ type: "data", streamId: stream.streamId, data: slice })) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (stream.pendingOutboundBytes > 0) {
|
||||
this.pauseStreamSocket(stream);
|
||||
return;
|
||||
}
|
||||
|
||||
this.resumeStreamSocketIfReady(stream);
|
||||
this.maybeSendRemoteHalfClose(stream);
|
||||
}
|
||||
|
||||
private pauseStreamSocket(stream: TunnelStreamState): void {
|
||||
if (!stream.tcpPaused && stream.socket && !stream.socket.destroyed) {
|
||||
stream.tcpPaused = true;
|
||||
stream.socket.pause();
|
||||
}
|
||||
}
|
||||
|
||||
private resumeStreamSocketIfReady(stream: TunnelStreamState): void {
|
||||
const hasCredit = stream.sendWindowBytes > 0 && this.connectionSendWindowBytes > 0;
|
||||
if (
|
||||
stream.tcpPaused &&
|
||||
!stream.remoteEnded &&
|
||||
hasCredit &&
|
||||
stream.socket &&
|
||||
!stream.socket.destroyed
|
||||
) {
|
||||
stream.tcpPaused = false;
|
||||
stream.socket.resume();
|
||||
}
|
||||
}
|
||||
|
||||
private maybeSendRemoteHalfClose(stream: TunnelStreamState): void {
|
||||
// Deliver HalfClose only after all queued TCP data has been sent in order.
|
||||
if (stream.remoteEnded && !stream.remoteHalfCloseSent) {
|
||||
stream.remoteHalfCloseSent = true;
|
||||
this.sendFrame({ type: "half_close", streamId: stream.streamId });
|
||||
if (stream.clientHalfClosed) {
|
||||
this.cleanupStream(stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private flushAllOutbound(): void {
|
||||
if (this.closed || this.connectionSendWindowBytes <= 0) return;
|
||||
// Iterate in insertion order; if connection window exhausts mid-way, remaining streams stay paused.
|
||||
for (const stream of Array.from(this.streams.values())) {
|
||||
if (this.closed) return;
|
||||
if (stream.state === "open") {
|
||||
this.flushStreamOutbound(stream);
|
||||
}
|
||||
if (this.connectionSendWindowBytes <= 0) break;
|
||||
}
|
||||
}
|
||||
|
||||
private handleInboundData(streamId: number, data: Uint8Array): void {
|
||||
const stream = this.streams.get(streamId);
|
||||
if (!stream || stream.state !== "open" || !stream.socket) {
|
||||
this.sendFrame({
|
||||
type: "close",
|
||||
streamId,
|
||||
reason: NetworkTunnelCloseReason.ProtocolError,
|
||||
message: `Data for unknown or unopened stream ${streamId}`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (stream.clientHalfClosed) {
|
||||
this.cleanupStream(stream);
|
||||
this.sendFrame({
|
||||
type: "close",
|
||||
streamId,
|
||||
reason: NetworkTunnelCloseReason.ProtocolError,
|
||||
message: `Data received after HalfClose on stream ${streamId}`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const len = data.byteLength;
|
||||
if (len > this.connectionRecvWindowBytes) {
|
||||
this.close(1008, "Connection receive window exceeded");
|
||||
return;
|
||||
}
|
||||
if (len > stream.recvWindowBytes) {
|
||||
this.cleanupStream(stream);
|
||||
this.sendFrame({
|
||||
type: "close",
|
||||
streamId,
|
||||
reason: NetworkTunnelCloseReason.FlowControlError,
|
||||
message: `Stream ${streamId} receive window exceeded`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (len === 0) return;
|
||||
|
||||
stream.recvWindowBytes -= len;
|
||||
this.connectionRecvWindowBytes -= len;
|
||||
|
||||
const accepted = stream.socket.write(data);
|
||||
if (accepted && stream.pendingDrainBytes === 0) {
|
||||
this.creditInboundConsumed(stream, len);
|
||||
} else {
|
||||
stream.pendingDrainBytes += len;
|
||||
}
|
||||
}
|
||||
|
||||
private creditInboundConsumed(stream: TunnelStreamState, bytes: number): void {
|
||||
stream.uncreditedRecvBytes += bytes;
|
||||
this.uncreditedConnectionRecvBytes += bytes;
|
||||
|
||||
if (stream.state === "open" && stream.uncreditedRecvBytes >= this.streamWindowUpdateThreshold) {
|
||||
const grant = stream.uncreditedRecvBytes;
|
||||
stream.uncreditedRecvBytes = 0;
|
||||
stream.recvWindowBytes += grant;
|
||||
this.sendFrame({ type: "window_update", streamId: stream.streamId, creditBytes: grant });
|
||||
}
|
||||
|
||||
this.maybeFlushConnectionRecvWindow();
|
||||
}
|
||||
|
||||
private maybeFlushConnectionRecvWindow(): void {
|
||||
if (this.uncreditedConnectionRecvBytes >= this.connectionWindowUpdateThreshold) {
|
||||
const grant = this.uncreditedConnectionRecvBytes;
|
||||
this.uncreditedConnectionRecvBytes = 0;
|
||||
this.connectionRecvWindowBytes += grant;
|
||||
this.sendFrame({ type: "window_update", streamId: 0, creditBytes: grant });
|
||||
}
|
||||
}
|
||||
|
||||
private handleWindowUpdate(streamId: number, creditBytes: number): void {
|
||||
if (streamId === 0) {
|
||||
if (this.connectionSendWindowBytes + creditBytes > MAX_WINDOW_BYTES) {
|
||||
this.close(1008, "Connection send window overflow");
|
||||
return;
|
||||
}
|
||||
this.connectionSendWindowBytes += creditBytes;
|
||||
this.flushAllOutbound();
|
||||
return;
|
||||
}
|
||||
|
||||
const stream = this.streams.get(streamId);
|
||||
if (!stream || stream.state !== "open") {
|
||||
// Late window updates for an already-closed stream are harmless; ignore.
|
||||
return;
|
||||
}
|
||||
if (stream.sendWindowBytes + creditBytes > MAX_WINDOW_BYTES) {
|
||||
this.cleanupStream(stream);
|
||||
this.sendFrame({
|
||||
type: "close",
|
||||
streamId,
|
||||
reason: NetworkTunnelCloseReason.FlowControlError,
|
||||
message: `Stream ${streamId} send window overflow`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
stream.sendWindowBytes += creditBytes;
|
||||
this.flushStreamOutbound(stream);
|
||||
}
|
||||
|
||||
private handleClientHalfClose(streamId: number): void {
|
||||
const stream = this.streams.get(streamId);
|
||||
if (!stream || stream.state !== "open" || !stream.socket) {
|
||||
return;
|
||||
}
|
||||
if (stream.clientHalfClosed) return;
|
||||
stream.clientHalfClosed = true;
|
||||
stream.socket.end();
|
||||
if (stream.remoteHalfCloseSent) {
|
||||
this.cleanupStream(stream);
|
||||
}
|
||||
}
|
||||
|
||||
private handleClientClose(streamId: number): void {
|
||||
const stream = this.streams.get(streamId);
|
||||
if (!stream) return;
|
||||
this.cleanupStream(stream);
|
||||
}
|
||||
|
||||
private cleanupStream(stream: TunnelStreamState): void {
|
||||
if (stream.state === "closed") return;
|
||||
stream.state = "closed";
|
||||
this.streams.delete(stream.streamId);
|
||||
stream.pendingOutboundChunks.length = 0;
|
||||
stream.pendingOutboundBytes = 0;
|
||||
|
||||
// Never leak connection-level receive credit when a stream closes with un-drained bytes.
|
||||
if (stream.pendingDrainBytes > 0) {
|
||||
this.uncreditedConnectionRecvBytes += stream.pendingDrainBytes;
|
||||
stream.pendingDrainBytes = 0;
|
||||
if (!this.closed) {
|
||||
this.maybeFlushConnectionRecvWindow();
|
||||
}
|
||||
}
|
||||
|
||||
const socket = stream.socket;
|
||||
stream.socket = null;
|
||||
if (socket && !socket.destroyed) {
|
||||
socket.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
private teardown(): void {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
if (this.idleTimer) {
|
||||
clearInterval(this.idleTimer);
|
||||
this.idleTimer = null;
|
||||
}
|
||||
for (const stream of Array.from(this.streams.values())) {
|
||||
this.cleanupStream(stream);
|
||||
}
|
||||
this.streams.clear();
|
||||
this.onCloseCallback?.();
|
||||
}
|
||||
}
|
||||
@@ -515,10 +515,6 @@ export interface SessionOptions {
|
||||
publishScriptStatusUpdate?: (message: ScriptStatusUpdateMessage) => void;
|
||||
logger: pino.Logger;
|
||||
downloadTokenStore: DownloadTokenStore;
|
||||
createNetworkTunnelTicket?: (permissions: readonly DaemonPermission[]) => {
|
||||
ticket: string;
|
||||
expiresAtMs: number;
|
||||
};
|
||||
pushNotifications: PushNotifications;
|
||||
paseoHome: string;
|
||||
worktreesRoot?: string;
|
||||
@@ -808,7 +804,6 @@ export class Session {
|
||||
),
|
||||
);
|
||||
private readonly browserToolsBroker: SessionOptions["browserToolsBroker"];
|
||||
private readonly createNetworkTunnelTicket: SessionOptions["createNetworkTunnelTicket"];
|
||||
private readonly clientId: string;
|
||||
private readonly authorization: SessionAuthorization;
|
||||
private appVersion: string | null;
|
||||
@@ -943,7 +938,6 @@ export class Session {
|
||||
publishScriptStatusUpdate,
|
||||
logger,
|
||||
downloadTokenStore,
|
||||
createNetworkTunnelTicket,
|
||||
pushNotifications,
|
||||
paseoHome,
|
||||
worktreesRoot,
|
||||
@@ -989,7 +983,6 @@ export class Session {
|
||||
getWebSocketRuntimeMetrics,
|
||||
} = options;
|
||||
this.browserToolsBroker = options.browserToolsBroker;
|
||||
this.createNetworkTunnelTicket = createNetworkTunnelTicket;
|
||||
this.clientId = clientId;
|
||||
this.authorization = new SessionAuthorization(permissions);
|
||||
|
||||
@@ -3745,21 +3738,6 @@ export class Session {
|
||||
payload: { requestId: msg.requestId },
|
||||
});
|
||||
return;
|
||||
case "network.tunnel.create_ticket.request": {
|
||||
if (!this.createNetworkTunnelTicket) {
|
||||
throw new Error("Network tunnel is not available on this session");
|
||||
}
|
||||
const issued = this.createNetworkTunnelTicket(this.getPermissions());
|
||||
this.emit({
|
||||
type: "network.tunnel.create_ticket.response",
|
||||
payload: {
|
||||
requestId: msg.requestId,
|
||||
ticket: issued.ticket,
|
||||
expiresAtMs: issued.expiresAtMs,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,800 +0,0 @@
|
||||
import { createServer as createHttpServer, type Server as HttpServer } from "node:http";
|
||||
import {
|
||||
createServer as createTcpServer,
|
||||
type AddressInfo,
|
||||
type Server as TcpServer,
|
||||
} from "node:net";
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
import { WebSocket, WebSocketServer, type RawData } from "ws";
|
||||
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { buildRelayWebSocketUrl } from "@getpaseo/protocol/daemon-endpoints";
|
||||
import {
|
||||
decodeNetworkTunnelFrame,
|
||||
encodeNetworkTunnelFrame,
|
||||
NetworkTunnelCloseReason,
|
||||
type DecodedNetworkTunnelFrame,
|
||||
type NetworkTunnelFrame,
|
||||
} from "@getpaseo/protocol/network-tunnel";
|
||||
import {
|
||||
openClientSecureChannel,
|
||||
type SecureChannel,
|
||||
type Transport as RelayClientTransport,
|
||||
} from "@getpaseo/relay/e2ee";
|
||||
import { loadOrCreateDaemonKeyPair } from "./daemon-keypair.js";
|
||||
import {
|
||||
WSOutboundMessageSchema,
|
||||
WSTunnelHandshakeResponseSchema,
|
||||
type WSOutboundMessage,
|
||||
type WSTunnelHandshakeResponse,
|
||||
} from "./messages.js";
|
||||
import { createTestPaseoDaemon, type TestPaseoDaemon } from "./test-utils/index.js";
|
||||
|
||||
const TEST_TIMEOUT_MS = 30_000;
|
||||
|
||||
interface TunnelClientHandle {
|
||||
ready: Extract<WSTunnelHandshakeResponse, { type: "tunnel_ready" }>;
|
||||
receivedTextAfterReady: string[];
|
||||
sendFrame: (frame: NetworkTunnelFrame) => Promise<void>;
|
||||
waitForFrame: (
|
||||
predicate: (frame: DecodedNetworkTunnelFrame) => boolean,
|
||||
) => Promise<DecodedNetworkTunnelFrame>;
|
||||
collectStreamBytesUntilHalfClose: (streamId: number) => Promise<Buffer>;
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
let daemon: TestPaseoDaemon | undefined;
|
||||
const httpServers: HttpServer[] = [];
|
||||
const tcpServers: TcpServer[] = [];
|
||||
const wsServers: WebSocketServer[] = [];
|
||||
const openWebSockets: WebSocket[] = [];
|
||||
const daemonClients: DaemonClient[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
for (const client of daemonClients.splice(0)) {
|
||||
await client.close().catch(() => undefined);
|
||||
}
|
||||
for (const ws of openWebSockets.splice(0)) {
|
||||
try {
|
||||
ws.terminate();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
await daemon?.close();
|
||||
daemon = undefined;
|
||||
await Promise.all([
|
||||
...httpServers.splice(0).map(
|
||||
(server) =>
|
||||
new Promise<void>((resolve) => {
|
||||
server.closeAllConnections?.();
|
||||
server.close(() => resolve());
|
||||
}),
|
||||
),
|
||||
...tcpServers.splice(0).map(
|
||||
(server) =>
|
||||
new Promise<void>((resolve) => {
|
||||
server.close(() => resolve());
|
||||
}),
|
||||
),
|
||||
...wsServers.splice(0).map(
|
||||
(server) =>
|
||||
new Promise<void>((resolve) => {
|
||||
server.close(() => resolve());
|
||||
}),
|
||||
),
|
||||
]);
|
||||
});
|
||||
|
||||
async function startLocalHttpTarget(): Promise<{ port: number }> {
|
||||
const server = createHttpServer((req, res) => {
|
||||
if (req.url === "/hello") {
|
||||
res.writeHead(200, { "content-type": "text/plain", connection: "close" });
|
||||
res.end("hello from remote daemon target");
|
||||
return;
|
||||
}
|
||||
res.writeHead(404, { connection: "close" });
|
||||
res.end("not found");
|
||||
});
|
||||
httpServers.push(server);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => resolve());
|
||||
});
|
||||
return { port: (server.address() as AddressInfo).port };
|
||||
}
|
||||
|
||||
async function startLocalHalfCloseTcpTarget(): Promise<{ port: number }> {
|
||||
const server = createTcpServer({ allowHalfOpen: true }, (socket) => {
|
||||
const chunks: Buffer[] = [];
|
||||
socket.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
|
||||
socket.on("end", () => {
|
||||
const full = Buffer.concat(chunks);
|
||||
// Stream response in two chunks to prove streaming + half-close ordering.
|
||||
socket.write(Buffer.from("ACK:"));
|
||||
setTimeout(() => {
|
||||
socket.end(full);
|
||||
}, 15);
|
||||
});
|
||||
});
|
||||
tcpServers.push(server);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => resolve());
|
||||
});
|
||||
return { port: (server.address() as AddressInfo).port };
|
||||
}
|
||||
|
||||
async function startLocalRelayBridge(): Promise<{
|
||||
port: number;
|
||||
waitForServerControl: () => Promise<void>;
|
||||
}> {
|
||||
const server = createHttpServer();
|
||||
const wss = new WebSocketServer({ server, path: "/ws" });
|
||||
httpServers.push(server);
|
||||
wsServers.push(wss);
|
||||
|
||||
let controlSocket: WebSocket | null = null;
|
||||
let resolveControlReady!: () => void;
|
||||
const controlReady = new Promise<void>((resolve) => {
|
||||
resolveControlReady = resolve;
|
||||
});
|
||||
|
||||
let nextConnectionSeq = 0;
|
||||
const clientSockets = new Map<string, WebSocket>();
|
||||
const pendingClientMessages = new Map<string, Array<{ data: RawData; isBinary: boolean }>>();
|
||||
|
||||
wss.on("connection", (ws, req) => {
|
||||
openWebSockets.push(ws);
|
||||
const url = new URL(req.url ?? "/ws", "http://127.0.0.1");
|
||||
const role = url.searchParams.get("role");
|
||||
const connectionId = url.searchParams.get("connectionId");
|
||||
|
||||
if (role === "server" && !connectionId) {
|
||||
controlSocket = ws;
|
||||
ws.send(JSON.stringify({ type: "sync", connectionIds: [] }));
|
||||
resolveControlReady();
|
||||
return;
|
||||
}
|
||||
|
||||
if (role === "client") {
|
||||
const id = `conn-${++nextConnectionSeq}`;
|
||||
clientSockets.set(id, ws);
|
||||
const buffered: Array<{ data: RawData; isBinary: boolean }> = [];
|
||||
pendingClientMessages.set(id, buffered);
|
||||
ws.on("message", (data, isBinary) => {
|
||||
const queue = pendingClientMessages.get(id);
|
||||
if (queue) {
|
||||
queue.push({ data, isBinary });
|
||||
}
|
||||
});
|
||||
controlSocket?.send(JSON.stringify({ type: "connected", connectionId: id }));
|
||||
return;
|
||||
}
|
||||
|
||||
if (role === "server" && connectionId) {
|
||||
const clientWs = clientSockets.get(connectionId);
|
||||
if (!clientWs) {
|
||||
ws.close(1008, "Unknown connectionId");
|
||||
return;
|
||||
}
|
||||
const queued = pendingClientMessages.get(connectionId) ?? [];
|
||||
pendingClientMessages.delete(connectionId);
|
||||
|
||||
// Forward queued client messages to server data socket.
|
||||
for (const item of queued) {
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(item.data, { binary: item.isBinary });
|
||||
}
|
||||
}
|
||||
|
||||
// Bridge live traffic transparently without decrypting (untrusted relay).
|
||||
clientWs.removeAllListeners("message");
|
||||
clientWs.on("message", (data, isBinary) => {
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(data, { binary: isBinary });
|
||||
}
|
||||
});
|
||||
ws.on("message", (data, isBinary) => {
|
||||
if (clientWs.readyState === WebSocket.OPEN) {
|
||||
clientWs.send(data, { binary: isBinary });
|
||||
}
|
||||
});
|
||||
clientWs.on("close", (code, reason) => {
|
||||
if (ws.readyState === WebSocket.OPEN) ws.close(code, reason.toString());
|
||||
});
|
||||
ws.on("close", (code, reason) => {
|
||||
if (clientWs.readyState === WebSocket.OPEN) clientWs.close(code, reason.toString());
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => resolve());
|
||||
});
|
||||
|
||||
return {
|
||||
port: (server.address() as AddressInfo).port,
|
||||
waitForServerControl: () => controlReady,
|
||||
};
|
||||
}
|
||||
|
||||
async function connectDirectDaemonClient(port: number, clientId: string): Promise<DaemonClient> {
|
||||
const client = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${port}/ws`,
|
||||
clientId,
|
||||
webSocketFactory: (url) => {
|
||||
const ws = new WebSocket(url);
|
||||
openWebSockets.push(ws);
|
||||
return ws as unknown as NonNullable<
|
||||
ConstructorParameters<typeof DaemonClient>[0]["webSocketFactory"]
|
||||
> extends (u: string) => infer R
|
||||
? R
|
||||
: never;
|
||||
},
|
||||
});
|
||||
daemonClients.push(client);
|
||||
await client.connect();
|
||||
return client;
|
||||
}
|
||||
|
||||
async function openDirectTunnel(port: number, ticket: string): Promise<TunnelClientHandle> {
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`);
|
||||
openWebSockets.push(ws);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
ws.once("open", resolve);
|
||||
ws.once("error", reject);
|
||||
});
|
||||
|
||||
const frames: DecodedNetworkTunnelFrame[] = [];
|
||||
const receivedTextAfterReady: string[] = [];
|
||||
const waiters: Array<{
|
||||
predicate: (frame: DecodedNetworkTunnelFrame) => boolean;
|
||||
resolve: (frame: DecodedNetworkTunnelFrame) => void;
|
||||
}> = [];
|
||||
|
||||
let readyResolved = false;
|
||||
let resolveHandshake!: (msg: WSTunnelHandshakeResponse) => void;
|
||||
const handshakePromise = new Promise<WSTunnelHandshakeResponse>((resolve) => {
|
||||
resolveHandshake = resolve;
|
||||
});
|
||||
|
||||
ws.on("message", (data, isBinary) => {
|
||||
if (!isBinary) {
|
||||
const text = Buffer.isBuffer(data) ? data.toString("utf8") : String(data);
|
||||
if (!readyResolved) {
|
||||
readyResolved = true;
|
||||
resolveHandshake(WSTunnelHandshakeResponseSchema.parse(JSON.parse(text)));
|
||||
} else {
|
||||
receivedTextAfterReady.push(text);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data as ArrayBuffer);
|
||||
const decoded = decodeNetworkTunnelFrame(
|
||||
new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength),
|
||||
);
|
||||
frames.push(decoded);
|
||||
for (let i = 0; i < waiters.length; i += 1) {
|
||||
const waiter = waiters[i]!;
|
||||
if (waiter.predicate(decoded)) {
|
||||
waiters.splice(i, 1);
|
||||
waiter.resolve(decoded);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
ws.send(JSON.stringify({ type: "tunnel_hello", ticket }));
|
||||
const handshake = await handshakePromise;
|
||||
if (handshake.type !== "tunnel_ready") {
|
||||
throw new Error(`Expected tunnel_ready, got ${handshake.type}: ${handshake.code}`);
|
||||
}
|
||||
|
||||
return createTunnelHandle({
|
||||
ready: handshake,
|
||||
frames,
|
||||
waiters,
|
||||
receivedTextAfterReady,
|
||||
sendBinary: async (bytes) => {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
ws.send(bytes, (err) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
},
|
||||
close: () => ws.close(),
|
||||
});
|
||||
}
|
||||
|
||||
async function openRelayE2eeTunnel(params: {
|
||||
relayPort: number;
|
||||
serverId: string;
|
||||
daemonPublicKeyB64: string;
|
||||
ticket: string;
|
||||
}): Promise<TunnelClientHandle> {
|
||||
const wsUrl = buildRelayWebSocketUrl({
|
||||
endpoint: `127.0.0.1:${params.relayPort}`,
|
||||
useTls: false,
|
||||
serverId: params.serverId,
|
||||
role: "client",
|
||||
});
|
||||
const rawWs = new WebSocket(wsUrl);
|
||||
openWebSockets.push(rawWs);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
rawWs.once("open", resolve);
|
||||
rawWs.once("error", reject);
|
||||
});
|
||||
|
||||
const transport: RelayClientTransport = {
|
||||
send: (data) =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
rawWs.send(data, (err) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
}),
|
||||
close: (code, reason) => rawWs.close(code, reason),
|
||||
onmessage: null,
|
||||
onclose: null,
|
||||
onerror: null,
|
||||
};
|
||||
rawWs.on("message", (data, isBinary) => {
|
||||
if (!isBinary) {
|
||||
const text = Buffer.isBuffer(data) ? data.toString("utf8") : String(data);
|
||||
transport.onmessage?.({ data: text, isBinary: false });
|
||||
return;
|
||||
}
|
||||
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data as ArrayBuffer);
|
||||
const copy = new Uint8Array(buf.byteLength);
|
||||
copy.set(buf);
|
||||
transport.onmessage?.({ data: copy.buffer, isBinary: true });
|
||||
});
|
||||
rawWs.on("close", (code, reason) => transport.onclose?.(code, reason.toString()));
|
||||
rawWs.on("error", (err) => transport.onerror?.(err));
|
||||
|
||||
const frames: DecodedNetworkTunnelFrame[] = [];
|
||||
const receivedTextAfterReady: string[] = [];
|
||||
const waiters: Array<{
|
||||
predicate: (frame: DecodedNetworkTunnelFrame) => boolean;
|
||||
resolve: (frame: DecodedNetworkTunnelFrame) => void;
|
||||
}> = [];
|
||||
|
||||
let readyResolved = false;
|
||||
let resolveHandshake!: (msg: WSTunnelHandshakeResponse) => void;
|
||||
const handshakePromise = new Promise<WSTunnelHandshakeResponse>((resolve) => {
|
||||
resolveHandshake = resolve;
|
||||
});
|
||||
|
||||
const channel: SecureChannel = await openClientSecureChannel(transport, {
|
||||
daemonPublicKeyB64: params.daemonPublicKeyB64,
|
||||
minimumMode: "protected",
|
||||
events: {
|
||||
onmessage: (data) => {
|
||||
if (typeof data === "string") {
|
||||
if (!readyResolved) {
|
||||
readyResolved = true;
|
||||
resolveHandshake(WSTunnelHandshakeResponseSchema.parse(JSON.parse(data)));
|
||||
} else {
|
||||
receivedTextAfterReady.push(data);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const decoded = decodeNetworkTunnelFrame(new Uint8Array(data));
|
||||
frames.push(decoded);
|
||||
for (let i = 0; i < waiters.length; i += 1) {
|
||||
const waiter = waiters[i]!;
|
||||
if (waiter.predicate(decoded)) {
|
||||
waiters.splice(i, 1);
|
||||
waiter.resolve(decoded);
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await channel.send(JSON.stringify({ type: "tunnel_hello", ticket: params.ticket }));
|
||||
const handshake = await handshakePromise;
|
||||
if (handshake.type !== "tunnel_ready") {
|
||||
throw new Error(`Expected tunnel_ready, got ${handshake.type}: ${handshake.code}`);
|
||||
}
|
||||
|
||||
return createTunnelHandle({
|
||||
ready: handshake,
|
||||
frames,
|
||||
waiters,
|
||||
receivedTextAfterReady,
|
||||
sendBinary: async (bytes) => {
|
||||
const copy = new Uint8Array(bytes.byteLength);
|
||||
copy.set(bytes);
|
||||
await channel.send(copy.buffer);
|
||||
},
|
||||
close: () => channel.close(),
|
||||
});
|
||||
}
|
||||
|
||||
function createTunnelHandle(params: {
|
||||
ready: Extract<WSTunnelHandshakeResponse, { type: "tunnel_ready" }>;
|
||||
frames: DecodedNetworkTunnelFrame[];
|
||||
waiters: Array<{
|
||||
predicate: (frame: DecodedNetworkTunnelFrame) => boolean;
|
||||
resolve: (frame: DecodedNetworkTunnelFrame) => void;
|
||||
}>;
|
||||
receivedTextAfterReady: string[];
|
||||
sendBinary: (bytes: Uint8Array) => Promise<void>;
|
||||
close: () => void;
|
||||
}): TunnelClientHandle {
|
||||
const waitForFrame = (predicate: (frame: DecodedNetworkTunnelFrame) => boolean) => {
|
||||
const existing = params.frames.find(predicate);
|
||||
if (existing) return Promise.resolve(existing);
|
||||
return new Promise<DecodedNetworkTunnelFrame>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
reject(new Error("Timed out waiting for tunnel frame"));
|
||||
}, 10_000);
|
||||
params.waiters.push({
|
||||
predicate,
|
||||
resolve: (frame) => {
|
||||
clearTimeout(timer);
|
||||
resolve(frame);
|
||||
},
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
ready: params.ready,
|
||||
receivedTextAfterReady: params.receivedTextAfterReady,
|
||||
sendFrame: (frame) => params.sendBinary(encodeNetworkTunnelFrame(frame)),
|
||||
waitForFrame,
|
||||
collectStreamBytesUntilHalfClose: async (streamId: number) => {
|
||||
await waitForFrame(
|
||||
(frame) =>
|
||||
(frame.type === "half_close" || frame.type === "close") && frame.streamId === streamId,
|
||||
);
|
||||
return Buffer.concat(
|
||||
params.frames
|
||||
.filter(
|
||||
(frame): frame is Extract<DecodedNetworkTunnelFrame, { type: "data" }> =>
|
||||
frame.type === "data" && frame.streamId === streamId,
|
||||
)
|
||||
.map((frame) => Buffer.from(frame.data)),
|
||||
);
|
||||
},
|
||||
close: params.close,
|
||||
};
|
||||
}
|
||||
|
||||
describe("WebSocketServer network tunnel E2E", () => {
|
||||
test(
|
||||
"direct secondary WS tunnels HTTP + streaming TCP half-close, blocks replay & SSRF, and receives zero control broadcasts",
|
||||
async () => {
|
||||
const httpTarget = await startLocalHttpTarget();
|
||||
const tcpTarget = await startLocalHalfCloseTcpTarget();
|
||||
daemon = await createTestPaseoDaemon();
|
||||
|
||||
const control = await connectDirectDaemonClient(daemon.port, "tunnel-control-client");
|
||||
expect(control.getLastServerInfoMessage()?.features?.networkTunnel).toBe(true);
|
||||
|
||||
const ticketResult = await control.createNetworkTunnelTicket();
|
||||
expect(ticketResult.ticket.length).toBeGreaterThanOrEqual(32);
|
||||
expect(ticketResult.expiresAtMs).toBeGreaterThan(Date.now());
|
||||
|
||||
const tunnel = await openDirectTunnel(daemon.port, ticketResult.ticket);
|
||||
expect(tunnel.ready).toEqual({
|
||||
type: "tunnel_ready",
|
||||
maxFramePayloadBytes: 64 * 1024,
|
||||
initialStreamWindowBytes: 512 * 1024,
|
||||
initialConnectionWindowBytes: 4 * 1024 * 1024,
|
||||
});
|
||||
|
||||
// Stream 1: real HTTP/1.1 request to local HTTP server
|
||||
await tunnel.sendFrame({
|
||||
type: "open",
|
||||
streamId: 1,
|
||||
host: "127.0.0.1",
|
||||
port: httpTarget.port,
|
||||
});
|
||||
await tunnel.waitForFrame((f) => f.type === "opened" && f.streamId === 1);
|
||||
await tunnel.sendFrame({
|
||||
type: "data",
|
||||
streamId: 1,
|
||||
data: new TextEncoder().encode(
|
||||
"GET /hello HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n",
|
||||
),
|
||||
});
|
||||
const httpResponse = (await tunnel.collectStreamBytesUntilHalfClose(1)).toString("utf8");
|
||||
expect(httpResponse).toContain("HTTP/1.1 200 OK");
|
||||
expect(httpResponse).toContain("hello from remote daemon target");
|
||||
|
||||
// Stream 2: streaming TCP + half-close
|
||||
await tunnel.sendFrame({
|
||||
type: "open",
|
||||
streamId: 2,
|
||||
host: "localhost",
|
||||
port: tcpTarget.port,
|
||||
});
|
||||
await tunnel.waitForFrame((f) => f.type === "opened" && f.streamId === 2);
|
||||
await tunnel.sendFrame({
|
||||
type: "data",
|
||||
streamId: 2,
|
||||
data: new TextEncoder().encode("part1-"),
|
||||
});
|
||||
await tunnel.sendFrame({
|
||||
type: "data",
|
||||
streamId: 2,
|
||||
data: new TextEncoder().encode("part2"),
|
||||
});
|
||||
await tunnel.sendFrame({ type: "half_close", streamId: 2 });
|
||||
const tcpResponse = (await tunnel.collectStreamBytesUntilHalfClose(2)).toString("utf8");
|
||||
expect(tcpResponse).toBe("ACK:part1-part2");
|
||||
|
||||
// Stream 3 & 4: cloud metadata endpoints must be rejected
|
||||
await tunnel.sendFrame({ type: "open", streamId: 3, host: "169.254.169.254", port: 80 });
|
||||
const blockedIp = await tunnel.waitForFrame((f) => f.type === "close" && f.streamId === 3);
|
||||
expect(blockedIp.type === "close" && blockedIp.reason).toBe(
|
||||
NetworkTunnelCloseReason.PolicyDenied,
|
||||
);
|
||||
|
||||
await tunnel.sendFrame({
|
||||
type: "open",
|
||||
streamId: 4,
|
||||
host: "metadata.google.internal",
|
||||
port: 80,
|
||||
});
|
||||
const blockedHost = await tunnel.waitForFrame((f) => f.type === "close" && f.streamId === 4);
|
||||
expect(blockedHost.type === "close" && blockedHost.reason).toBe(
|
||||
NetworkTunnelCloseReason.PolicyDenied,
|
||||
);
|
||||
|
||||
// Replay of the already-used ticket must fail closed with tunnel_error + 4401
|
||||
const replayWs = new WebSocket(`ws://127.0.0.1:${daemon.port}/ws`);
|
||||
openWebSockets.push(replayWs);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
replayWs.once("open", resolve);
|
||||
replayWs.once("error", reject);
|
||||
});
|
||||
const replayOutcome = new Promise<{ error: WSTunnelHandshakeResponse; closeCode: number }>(
|
||||
(resolve, reject) => {
|
||||
let errorMsg: WSTunnelHandshakeResponse | null = null;
|
||||
replayWs.on("message", (data, isBinary) => {
|
||||
if (isBinary) return;
|
||||
errorMsg = WSTunnelHandshakeResponseSchema.parse(JSON.parse(data.toString()));
|
||||
});
|
||||
replayWs.once("close", (code) => {
|
||||
if (!errorMsg) {
|
||||
reject(new Error(`Replay closed (${code}) without tunnel_error`));
|
||||
return;
|
||||
}
|
||||
resolve({ error: errorMsg, closeCode: code });
|
||||
});
|
||||
},
|
||||
);
|
||||
replayWs.send(JSON.stringify({ type: "tunnel_hello", ticket: ticketResult.ticket }));
|
||||
const replay = await replayOutcome;
|
||||
expect(replay.error).toEqual({
|
||||
type: "tunnel_error",
|
||||
code: "invalid_ticket",
|
||||
message: expect.any(String),
|
||||
});
|
||||
expect(replay.closeCode).toBe(4401);
|
||||
|
||||
// Trigger a daemon-wide config broadcast and confirm a control observer receives it
|
||||
// while the tunnel WS receives ZERO control broadcasts.
|
||||
const broadcastObserver = new WebSocket(`ws://127.0.0.1:${daemon.port}/ws`);
|
||||
openWebSockets.push(broadcastObserver);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
broadcastObserver.once("open", resolve);
|
||||
broadcastObserver.once("error", reject);
|
||||
});
|
||||
const observerReceivedConfigBroadcast = new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(
|
||||
() => reject(new Error("Timed out waiting for daemon_config_changed broadcast")),
|
||||
5_000,
|
||||
);
|
||||
broadcastObserver.on("message", (data, isBinary) => {
|
||||
if (isBinary) return;
|
||||
const parsed = WSOutboundMessageSchema.safeParse(JSON.parse(data.toString()));
|
||||
if (
|
||||
parsed.success &&
|
||||
parsed.data.type === "session" &&
|
||||
parsed.data.message.type === "status" &&
|
||||
parsed.data.message.payload.status === "daemon_config_changed"
|
||||
) {
|
||||
clearTimeout(timer);
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(
|
||||
() => reject(new Error("Timed out waiting for observer hello")),
|
||||
5_000,
|
||||
);
|
||||
const onMsg = (data: RawData, isBinary: boolean) => {
|
||||
if (isBinary) return;
|
||||
const parsed = WSOutboundMessageSchema.safeParse(JSON.parse(data.toString()));
|
||||
if (
|
||||
parsed.success &&
|
||||
parsed.data.type === "session" &&
|
||||
parsed.data.message.type === "status" &&
|
||||
parsed.data.message.payload.status === "server_info"
|
||||
) {
|
||||
clearTimeout(timer);
|
||||
broadcastObserver.off("message", onMsg);
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
broadcastObserver.on("message", onMsg);
|
||||
broadcastObserver.send(
|
||||
JSON.stringify({
|
||||
type: "hello",
|
||||
clientId: "broadcast-observer-client",
|
||||
clientType: "browser",
|
||||
protocolVersion: 1,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
await control.patchDaemonConfig({ resumeOnStartup: true });
|
||||
await observerReceivedConfigBroadcast;
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
expect(tunnel.receivedTextAfterReady).toEqual([]);
|
||||
|
||||
tunnel.close();
|
||||
},
|
||||
TEST_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
test(
|
||||
"E2EE relay secondary WS authenticates via tunnel_hello and pipes HTTP + streaming TCP over encrypted binary frames",
|
||||
async () => {
|
||||
const httpTarget = await startLocalHttpTarget();
|
||||
const tcpTarget = await startLocalHalfCloseTcpTarget();
|
||||
const relay = await startLocalRelayBridge();
|
||||
|
||||
daemon = await createTestPaseoDaemon({
|
||||
relayEnabled: true,
|
||||
relayEndpoint: `127.0.0.1:${relay.port}`,
|
||||
relayUseTls: false,
|
||||
relayRequireProtectedSecurity: true,
|
||||
});
|
||||
await relay.waitForServerControl();
|
||||
|
||||
const keyPair = await loadOrCreateDaemonKeyPair(daemon.paseoHome);
|
||||
const control = await connectDirectDaemonClient(daemon.port, "relay-tunnel-control");
|
||||
const { ticket } = await control.createNetworkTunnelTicket();
|
||||
|
||||
const tunnel = await openRelayE2eeTunnel({
|
||||
relayPort: relay.port,
|
||||
serverId: daemon.daemon.getServerId(),
|
||||
daemonPublicKeyB64: keyPair.publicKeyB64,
|
||||
ticket,
|
||||
});
|
||||
expect(tunnel.ready.maxFramePayloadBytes).toBe(64 * 1024);
|
||||
|
||||
// HTTP over E2EE relay binary tunnel
|
||||
await tunnel.sendFrame({
|
||||
type: "open",
|
||||
streamId: 1,
|
||||
host: "127.0.0.1",
|
||||
port: httpTarget.port,
|
||||
});
|
||||
await tunnel.waitForFrame((f) => f.type === "opened" && f.streamId === 1);
|
||||
await tunnel.sendFrame({
|
||||
type: "data",
|
||||
streamId: 1,
|
||||
data: new TextEncoder().encode(
|
||||
"GET /hello HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n",
|
||||
),
|
||||
});
|
||||
const httpResponse = (await tunnel.collectStreamBytesUntilHalfClose(1)).toString("utf8");
|
||||
expect(httpResponse).toContain("hello from remote daemon target");
|
||||
|
||||
// Streaming TCP + half-close over E2EE relay binary tunnel
|
||||
await tunnel.sendFrame({
|
||||
type: "open",
|
||||
streamId: 2,
|
||||
host: "127.0.0.1",
|
||||
port: tcpTarget.port,
|
||||
});
|
||||
await tunnel.waitForFrame((f) => f.type === "opened" && f.streamId === 2);
|
||||
await tunnel.sendFrame({
|
||||
type: "data",
|
||||
streamId: 2,
|
||||
data: new TextEncoder().encode("relay-e2ee-stream"),
|
||||
});
|
||||
await tunnel.sendFrame({ type: "half_close", streamId: 2 });
|
||||
const tcpResponse = (await tunnel.collectStreamBytesUntilHalfClose(2)).toString("utf8");
|
||||
expect(tcpResponse).toBe("ACK:relay-e2ee-stream");
|
||||
|
||||
expect(tunnel.receivedTextAfterReady).toEqual([]);
|
||||
tunnel.close();
|
||||
},
|
||||
TEST_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
test(
|
||||
"denies network.tunnel.create_ticket.request when principal lacks workspace.write permission",
|
||||
async () => {
|
||||
daemon = await createTestPaseoDaemon();
|
||||
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${daemon.port}/ws`);
|
||||
openWebSockets.push(ws);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
ws.once("open", resolve);
|
||||
ws.once("error", reject);
|
||||
});
|
||||
|
||||
const sendAndWait = (
|
||||
payload: unknown,
|
||||
matches: (msg: WSOutboundMessage) => boolean,
|
||||
): Promise<WSOutboundMessage> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(
|
||||
() => reject(new Error("Timed out waiting for WS reply")),
|
||||
5_000,
|
||||
);
|
||||
const onMsg = (data: RawData, isBinary: boolean) => {
|
||||
if (isBinary) return;
|
||||
const parsed = WSOutboundMessageSchema.safeParse(JSON.parse(data.toString()));
|
||||
if (!parsed.success || !matches(parsed.data)) return;
|
||||
clearTimeout(timer);
|
||||
ws.off("message", onMsg);
|
||||
resolve(parsed.data);
|
||||
};
|
||||
ws.on("message", onMsg);
|
||||
ws.send(JSON.stringify(payload));
|
||||
});
|
||||
|
||||
// Attenuate session permissions to read-only (no workspace.write).
|
||||
await sendAndWait(
|
||||
{
|
||||
type: "hello",
|
||||
clientId: "read-only-client",
|
||||
clientType: "browser",
|
||||
protocolVersion: 1,
|
||||
sessionPermissions: ["daemon.read", "workspace.read"],
|
||||
},
|
||||
(msg) =>
|
||||
msg.type === "session" &&
|
||||
msg.message.type === "status" &&
|
||||
msg.message.payload.status === "server_info",
|
||||
);
|
||||
|
||||
const denied = await sendAndWait(
|
||||
{
|
||||
type: "session",
|
||||
message: {
|
||||
type: "network.tunnel.create_ticket.request",
|
||||
requestId: "req-denied-ticket",
|
||||
},
|
||||
},
|
||||
(msg) =>
|
||||
msg.type === "session" &&
|
||||
msg.message.type === "rpc_error" &&
|
||||
msg.message.payload.requestId === "req-denied-ticket",
|
||||
);
|
||||
|
||||
expect(denied).toMatchObject({
|
||||
type: "session",
|
||||
message: {
|
||||
type: "rpc_error",
|
||||
payload: {
|
||||
requestId: "req-denied-ticket",
|
||||
requestType: "network.tunnel.create_ticket.request",
|
||||
code: "access_denied",
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
TEST_TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
@@ -54,10 +54,8 @@ import {
|
||||
type ServerCapabilityState,
|
||||
type ServerCapabilities,
|
||||
type WSOutboundMessage,
|
||||
type WSTunnelHelloMessage,
|
||||
wrapSessionMessage,
|
||||
} from "./messages.js";
|
||||
import { NetworkTunnelService } from "./network-tunnel/index.js";
|
||||
import { asUint8Array, decodeBinaryFrame } from "@getpaseo/protocol/binary-frames/index";
|
||||
import type { TerminalActivity } from "@getpaseo/protocol/terminal-activity";
|
||||
import { MAX_WEBSOCKET_MESSAGE_BYTES } from "@getpaseo/protocol/websocket-message-limit";
|
||||
@@ -510,7 +508,6 @@ interface PluginSessionConnection extends SessionConnectionBase {
|
||||
type SessionConnection = ReconnectableSessionConnection | PluginSessionConnection;
|
||||
|
||||
interface SocketSessionOptions {
|
||||
principalId: string;
|
||||
sourceId?: string;
|
||||
clientId: string;
|
||||
appVersion: string | null;
|
||||
@@ -598,8 +595,6 @@ export class VoiceAssistantWebSocketServer {
|
||||
private readonly logger: pino.Logger;
|
||||
private readonly wss: WebSocketServer;
|
||||
private readonly hostLinks = new Map<WebSocketLike, DaemonLinkEndpoint>();
|
||||
private readonly networkTunnel = new NetworkTunnelService();
|
||||
private readonly handedOffTunnelSockets = new WeakSet<WebSocketLike>();
|
||||
private readonly pendingConnections: Map<WebSocketLike, PendingConnection> = new Map();
|
||||
private readonly sessions: Map<WebSocketLike, SessionConnection> = new Map();
|
||||
private readonly socketLocalEndpoints = new WeakMap<object, string>();
|
||||
@@ -1204,9 +1199,6 @@ export class VoiceAssistantWebSocketServer {
|
||||
principalId: string,
|
||||
permissions: readonly DaemonPermission[],
|
||||
): void {
|
||||
if (!permissions.includes("workspace.write")) {
|
||||
this.networkTunnel.revokePrincipal(principalId);
|
||||
}
|
||||
for (const [socket, link] of this.hostLinks) {
|
||||
if (this.sessions.get(socket)?.principalId === principalId) {
|
||||
link.close("permission_denied");
|
||||
@@ -1241,7 +1233,6 @@ export class VoiceAssistantWebSocketServer {
|
||||
|
||||
public async close(): Promise<void> {
|
||||
this.prepareForShutdown();
|
||||
this.networkTunnel.close();
|
||||
await this.agentMessages.close();
|
||||
await this.connectedHosts.close();
|
||||
this.unsubscribeSpeechReadiness?.();
|
||||
@@ -1646,7 +1637,6 @@ export class VoiceAssistantWebSocketServer {
|
||||
let connection: SessionConnection | null = null;
|
||||
|
||||
const session = this.createSocketSession({
|
||||
principalId: admission.principalId,
|
||||
clientId,
|
||||
appVersion,
|
||||
clientCapabilities,
|
||||
@@ -1759,11 +1749,6 @@ export class VoiceAssistantWebSocketServer {
|
||||
},
|
||||
publishScriptStatusUpdate: (message) => this.publishScriptStatusUpdate(message),
|
||||
downloadTokenStore: this.downloadTokenStore,
|
||||
createNetworkTunnelTicket: (permissions) =>
|
||||
this.networkTunnel.createTicket({
|
||||
principalId: options.principalId,
|
||||
permissions,
|
||||
}),
|
||||
pushNotifications: this.pushNotifications,
|
||||
paseoHome: this.paseoHome,
|
||||
worktreesRoot: this.worktreesRoot,
|
||||
@@ -2337,8 +2322,6 @@ export class VoiceAssistantWebSocketServer {
|
||||
agentProfiles: true,
|
||||
// COMPAT(agentConfigApply): added in v0.3.2, remove gate after 2027-02-11.
|
||||
agentConfigApply: true,
|
||||
// COMPAT(networkTunnel): added in v0.17.6, remove gate after 2027-05-26.
|
||||
networkTunnel: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -2384,7 +2367,6 @@ export class VoiceAssistantWebSocketServer {
|
||||
|
||||
private bindSocketHandlers(ws: WebSocketLike): void {
|
||||
ws.on("message", (...args: unknown[]) => {
|
||||
if (this.handedOffTunnelSockets.has(ws)) return;
|
||||
const data = args[0] as Buffer | ArrayBuffer | Buffer[] | string;
|
||||
try {
|
||||
this.chunkedSocket(ws).receive(typeof data === "string" ? data : bufferFromWsData(data));
|
||||
@@ -2395,7 +2377,6 @@ export class VoiceAssistantWebSocketServer {
|
||||
});
|
||||
|
||||
ws.on("close", async (...args: unknown[]) => {
|
||||
if (this.handedOffTunnelSockets.has(ws)) return;
|
||||
this.chunkedSockets.get(ws)?.close();
|
||||
const code = args[0];
|
||||
const reason = args[1];
|
||||
@@ -2406,7 +2387,6 @@ export class VoiceAssistantWebSocketServer {
|
||||
});
|
||||
|
||||
ws.on("error", async (...args: unknown[]) => {
|
||||
if (this.handedOffTunnelSockets.has(ws)) return;
|
||||
const error = args[0];
|
||||
const err = error instanceof Error ? error : new Error(String(error));
|
||||
const active = this.sessions.get(ws);
|
||||
@@ -2678,15 +2658,6 @@ export class VoiceAssistantWebSocketServer {
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "tunnel_hello" && !pendingConnection.authenticating) {
|
||||
this.handleTunnelHello({
|
||||
ws,
|
||||
message,
|
||||
pending: pendingConnection,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
pendingConnection.connectionLogger.warn(
|
||||
{
|
||||
messageType: message.type,
|
||||
@@ -2702,72 +2673,6 @@ export class VoiceAssistantWebSocketServer {
|
||||
}
|
||||
}
|
||||
|
||||
private handleTunnelHello(params: {
|
||||
ws: WebSocketLike;
|
||||
message: WSTunnelHelloMessage;
|
||||
pending: PendingConnection;
|
||||
}): void {
|
||||
const { ws, message, pending } = params;
|
||||
this.clearPendingConnection(ws);
|
||||
this.socketIdentities.delete(ws);
|
||||
this.applicationSocketLease.release(ws);
|
||||
|
||||
const redeemed = this.networkTunnel.redeemTicket(message.ticket);
|
||||
if (!redeemed) {
|
||||
pending.connectionLogger.warn("Rejected tunnel_hello with invalid or expired ticket");
|
||||
this.rejectTunnelHello(
|
||||
ws,
|
||||
"invalid_ticket",
|
||||
"Tunnel ticket is invalid, expired, or already used",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!redeemed.permissions.includes("workspace.write")) {
|
||||
pending.connectionLogger.warn(
|
||||
{ principalId: redeemed.principalId },
|
||||
"Rejected tunnel_hello lacking workspace.write permission",
|
||||
);
|
||||
this.rejectTunnelHello(
|
||||
ws,
|
||||
"unauthorized",
|
||||
"Principal is not authorized to open network tunnels",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Mark handed off synchronously before attaching TunnelSession so subsequent
|
||||
// binary frames (including pipelined frames on EncryptedRelaySocket) bypass
|
||||
// WebSocketServer and ChunkedTransport completely.
|
||||
this.handedOffTunnelSockets.add(ws);
|
||||
this.chunkedSockets.delete(ws);
|
||||
this.networkTunnel.attachTunnelSocket(ws, {
|
||||
principalId: redeemed.principalId,
|
||||
logger: pending.connectionLogger,
|
||||
});
|
||||
}
|
||||
|
||||
private rejectTunnelHello(ws: WebSocketLike, code: string, message: string): void {
|
||||
const closeSocket = () => {
|
||||
try {
|
||||
ws.close(WS_CLOSE_DAEMON_AUTH_FAILED, message);
|
||||
} catch {
|
||||
// ignore close errors
|
||||
}
|
||||
};
|
||||
try {
|
||||
const payload = JSON.stringify({ type: "tunnel_error", code, message });
|
||||
const sendResult = ws.send(payload);
|
||||
if (sendResult && typeof sendResult.then === "function") {
|
||||
void sendResult.catch(() => undefined).finally(closeSocket);
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// fall through to close
|
||||
}
|
||||
closeSocket();
|
||||
}
|
||||
|
||||
private handleRawMessage(
|
||||
ws: WebSocketLike,
|
||||
data: Buffer | ArrayBuffer | Buffer[] | string,
|
||||
@@ -2844,12 +2749,9 @@ export class VoiceAssistantWebSocketServer {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isHandshakeMessage(message)) {
|
||||
if (message.type === "hello") {
|
||||
this.incrementRuntimeCounter("unexpectedHelloOnActiveConnection");
|
||||
activeConnection.connectionLogger.warn(
|
||||
{ messageType: message.type },
|
||||
"Received unexpected handshake on active connection",
|
||||
);
|
||||
activeConnection.connectionLogger.warn("Received hello on active connection");
|
||||
try {
|
||||
ws.close(WS_CLOSE_INVALID_HELLO, "Unexpected hello");
|
||||
} catch {
|
||||
@@ -3431,10 +3333,6 @@ function createWebSocketConnectionIdentity(
|
||||
};
|
||||
}
|
||||
|
||||
function isHandshakeMessage(message: WSInboundMessage): boolean {
|
||||
return message.type === "hello" || message.type === "tunnel_hello";
|
||||
}
|
||||
|
||||
function sessionConnectionKey(principalId: string, clientId: string): string {
|
||||
return JSON.stringify([principalId, clientId]);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user