Compare commits

...
Author SHA1 Message Date
Mohamed Boudra ced52acef4 Ignore inherited object keys when reading bound host profile partitions 2026-12-02 16:23:18 +01:00
Mohamed Boudra 62da5b9463 Let browser profiles work on host-proxied tabs
A browser tab's Electron partition is now the pair (route, profile).
Host-proxied tabs show the profile picker, and each profile on a host
gets its own persistent partition bound to that host's one SOCKS5 server
and tunnel. Clear, Remove, and startup pruning cover every route.

One module, browser-partition.ts, owns the partition names. The existing
local and host Default names are unchanged.
2026-12-02 16:17:22 +01:00
23 changed files with 1098 additions and 435 deletions
+8 -1
View File
@@ -219,7 +219,14 @@ file after the daemon confirms persistence.
> **Window-state v1 limitation:** only the _first_ window of a session restores and persists saved geometry (size/position/maximized). Windows opened via ⌘⇧N / second-instance / "Open in new window" open at the default size, OS-cascaded, and do not persist — this avoids every window stacking on the same restored bounds and fighting over the single window-state store. Lifting this needs per-window state keys.
>
> **In-app browser profiles.** Each local browser tab runs in a persistent Electron partition and can switch profiles at any time; switching replaces the `<webview>` under the new partition and reloads the current URL in that profile's session. Partition names are the identity: `persist:paseo-browser` is **Default** and preserves cookies from before profiles; `persist:paseo-profile-<slug>` is a named profile. Display names and colors live in the main-owned catalog `<userData>/browser-profiles.json`, so editing a profile's name or color keeps sign-ins intact and updates open tabs live. Main admits only `persist:paseo-browser`, `persist:paseo-profile-<slug>`, and active host-proxy partitions (`persist:paseo-browser-host-<16hex>`) at `will-attach-webview`. The tab's chosen profile slug lives in its `workspace-browser-store` record. After every `did-attach`, the renderer registers its browser id, workspace id, partition, and current guest `WebContents` id, and main accepts it only when that guest belongs to the calling renderer and its session matches the partition. Registration is intentionally repeated because reparenting a retained `<webview>` can replace its guest without replacing the DOM element. Settings > Chat & panes manages profiles: clearing a profile clears its storage/cache and reloads its open tabs; removing a named profile closes its open tabs, removes it from the catalog, clears its session, and deletes its `Partitions/paseo-profile-<slug>` directory from disk. Default cannot be removed.
> **In-app browser profiles.** A browser tab's Electron partition is the pair (route, profile). The route is local, or a host's browser proxy. The profile is **Default** or a named profile. Electron sets the proxy per session (`session.setProxy`), not per `<webview>`, so the route is part of the partition name. Partition names are the identity, and `packages/desktop/src/features/browser-partition.ts` owns them:
>
> | Route | Default | Named profile |
> | ----- | ------------------------------------ | --------------------------------------------------- |
> | Local | `persist:paseo-browser` | `persist:paseo-profile-<slug>` |
> | Host | `persist:paseo-browser-host-<16hex>` | `persist:paseo-browser-host-<16hex>-profile-<slug>` |
>
> `persist:paseo-browser` keeps cookies from before profiles, and the host Default name predates profiles; do not rename either. A host runs one loopback SOCKS5 server and one tunnel. Every profile session on that host points `setProxy` at the same port, so a new profile never opens a second tunnel. Main binds a host profile's session when the renderer calls `ensureHostProxy` with its slug, and verifies it with `resolveProxy`. The status snapshot lists bound sessions in `profilePartitions`, and the tab mounts only after its profile appears there. A tab can switch profile and route at any time: the `<webview>` is replaced under the new partition and reloads the current URL. Display names and colors live in the main-owned catalog `<userData>/browser-profiles.json`, so editing a name or color keeps sign-ins intact and updates open tabs live. At `will-attach-webview`, main admits local partitions and only those host partitions whose session it bound. The tab's chosen profile slug lives in its `workspace-browser-store` record. After every `did-attach`, the renderer registers its browser id, workspace id, partition, and current guest `WebContents` id. Main accepts it only when that guest belongs to the calling renderer and its session matches the partition, and for a host partition, only when the session is bound to the proxy. Registration is repeated on purpose, because reparenting a retained `<webview>` can replace its guest without replacing the DOM element. Settings > Chat & panes manages profiles on every route: clearing a profile clears its storage and cache on the local route and on each host, then reloads its open tabs. Removing a named profile closes its open tabs, removes it from the catalog, clears its sessions, and deletes each of its `Partitions/` directories. Startup deletes the directories of profiles that are no longer in the catalog. Default cannot be removed.
>
> **In-app browser window opens.** Ordinary link opens, including Shift-clicked links, become Paseo workspace tabs and inherit the opener tab's browser profile. Script-created opens with popup features or a named window target and POST-backed opens remain secured Electron child windows in the opener’s browser profile, preserving `window.opener`, `postMessage`, named-window reuse, request bodies, and `window.close()` for OAuth, payment, and similar popup protocols. Unsupported URL schemes are denied before either path.
>
@@ -1,8 +1,4 @@
import {
DEFAULT_BROWSER_PROFILE_SLUG,
getBrowserProfilePartition,
useBrowserProfileCatalog,
} from "../profiles";
import { DEFAULT_BROWSER_PROFILE_SLUG, useBrowserProfileCatalog } from "../profiles";
import { ProfileSelector } from "./profile-selector.electron";
import {
useCallback,
@@ -831,16 +827,12 @@ export function BrowserPane({
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 isLocalProfileMode =
proxyState.kind === "ready" && proxyState.effectiveRoutingMode === "local";
let activePartition: string | null = null;
if (proxyState.kind === "ready") {
activePartition =
proxyState.effectiveRoutingMode === "host"
? proxyState.partition
: getBrowserProfilePartition(profileSlug);
}
const proxyState = useHostBrowserProxy({
serverId,
routingMode: browser?.routingMode,
profileSlug,
});
const activePartition = proxyState.kind === "ready" ? proxyState.partition : null;
const browserViewport = browser?.viewport ?? RESPONSIVE_BROWSER_VIEWPORT;
const browserViewportRef = useRef(browserViewport);
browserViewportRef.current = browserViewport;
@@ -1813,15 +1805,13 @@ export function BrowserPane({
initialValue={draftUrl}
/>
</View>
{isLocalProfileMode ? (
<ProfileSelector
selectedSlug={profileSlug}
catalog={catalog.data ?? []}
triggerStyle={profileTriggerStyle}
onSelect={selectProfile}
refresh={refreshProfiles}
/>
) : null}
<ProfileSelector
selectedSlug={profileSlug}
catalog={catalog.data ?? []}
triggerStyle={profileTriggerStyle}
onSelect={selectProfile}
refresh={refreshProfiles}
/>
<View style={styles.chromeRight}>
<DeviceSizeMenu
selectedId={selectedDeviceSizeId}
@@ -1,4 +1,5 @@
import { getIsElectron } from "@/constants/platform";
import { DEFAULT_BROWSER_PROFILE_SLUG } from "@/desktop/browser/profiles";
import {
getDesktopHost,
type DesktopBrowserProxyStatusSnapshot,
@@ -35,13 +36,18 @@ function notifyStatusListeners(serverId: string): void {
}
}
function hasSameProfilePartitions(a: Record<string, string>, b: Record<string, string>): boolean {
const slugs = Object.keys(a);
return slugs.length === Object.keys(b).length && slugs.every((slug) => a[slug] === b[slug]);
}
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 &&
hasSameProfilePartitions(existing.profilePartitions, snapshot.profilePartitions) &&
existing.socksPort === snapshot.socksPort
) {
return;
@@ -53,9 +59,12 @@ function setCachedStatus(snapshot: DesktopBrowserProxyStatusSnapshot): void {
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>;
const profilePartitions = record.profilePartitions;
return (
typeof record.serverId === "string" &&
typeof record.partition === "string" &&
typeof profilePartitions === "object" &&
profilePartitions !== null &&
Object.values(profilePartitions).every((partition) => typeof partition === "string") &&
typeof record.status === "string"
);
}
@@ -268,6 +277,7 @@ export function subscribeBrowserProxyStatus(serverId: string, listener: () => vo
export async function ensureHostBrowserProxy(input: {
serverId: string;
target: SupportedTarget;
profileSlug?: string;
forceReconnect?: boolean;
}): Promise<DesktopBrowserProxyStatusSnapshot | null> {
installBrowserProxyRendererBridge();
@@ -345,14 +355,15 @@ export async function prepareHostBrowserPartition(
message: "Browser proxy bridge is unavailable in this desktop build.",
};
}
if (status.status !== "ready") {
const partition = status.profilePartitions[DEFAULT_BROWSER_PROFILE_SLUG];
if (status.status !== "ready" || !partition) {
return {
ok: false,
reason: "proxy_error",
message: status.error ?? "Unable to connect browser proxy.",
};
}
return { ok: true, partition: status.partition, isRemoteHost: true };
return { ok: true, partition, isRemoteHost: true };
} catch (error) {
return {
ok: false,
@@ -9,7 +9,7 @@ describe("resolveBrowserProxyPaneState", () => {
resolveBrowserProxyPaneState({
routing: { kind: "remote", support: "host_connecting" },
effectiveRoutingMode: "host",
localPartition: "persist:paseo-browser",
profileSlug: "default",
hostLabel: "devbox",
proxyStatusSnapshot: null,
ensureError: null,
@@ -27,11 +27,11 @@ describe("resolveBrowserProxyPaneState", () => {
resolveBrowserProxyPaneState({
routing: { kind: "remote", support: "host_offline" },
effectiveRoutingMode: "host",
localPartition: "persist:paseo-browser",
profileSlug: "default",
hostLabel: "devbox",
proxyStatusSnapshot: {
serverId: "srv-remote",
partition: "persist:paseo-browser-host-0123456789abcdef",
profilePartitions: { default: "persist:paseo-browser-host-0123456789abcdef" },
status: "connecting",
error: null,
socksPort: null,
@@ -50,7 +50,7 @@ describe("resolveBrowserProxyPaneState", () => {
it("keeps the prepared host partition mounted across transient host disconnects and reconnects", () => {
const preparedSnapshot = {
serverId: "srv-remote",
partition: "persist:paseo-browser-host-0123456789abcdef",
profilePartitions: { default: "persist:paseo-browser-host-0123456789abcdef" },
status: "ready" as const,
error: null,
socksPort: 41234,
@@ -60,7 +60,7 @@ describe("resolveBrowserProxyPaneState", () => {
resolveBrowserProxyPaneState({
routing: { kind: "remote", support: "host_offline" },
effectiveRoutingMode: "host",
localPartition: "persist:paseo-browser",
profileSlug: "default",
hostLabel: "devbox",
proxyStatusSnapshot: preparedSnapshot,
ensureError: null,
@@ -68,7 +68,7 @@ describe("resolveBrowserProxyPaneState", () => {
}),
).toEqual({
kind: "ready",
partition: preparedSnapshot.partition,
partition: preparedSnapshot.profilePartitions.default,
isRemoteHost: true,
effectiveRoutingMode: "host",
hostLabel: "devbox",
@@ -79,7 +79,7 @@ describe("resolveBrowserProxyPaneState", () => {
resolveBrowserProxyPaneState({
routing: { kind: "remote", support: "host_connecting" },
effectiveRoutingMode: "host",
localPartition: "persist:paseo-browser",
profileSlug: "default",
hostLabel: "devbox",
proxyStatusSnapshot: preparedSnapshot,
ensureError: null,
@@ -87,7 +87,7 @@ describe("resolveBrowserProxyPaneState", () => {
}),
).toEqual({
kind: "ready",
partition: preparedSnapshot.partition,
partition: preparedSnapshot.profilePartitions.default,
isRemoteHost: true,
effectiveRoutingMode: "host",
hostLabel: "devbox",
@@ -106,11 +106,11 @@ describe("resolveBrowserProxyPaneState", () => {
resolveBrowserProxyPaneState({
routing: supportedRouting,
effectiveRoutingMode: "host",
localPartition: "persist:paseo-browser",
profileSlug: "default",
hostLabel: "devbox",
proxyStatusSnapshot: {
serverId: "srv-remote",
partition: "persist:paseo-browser-host-0123456789abcdef",
profilePartitions: { default: "persist:paseo-browser-host-0123456789abcdef" },
status: "error",
error: "Host disconnected",
socksPort: 41234,
@@ -133,11 +133,11 @@ describe("resolveBrowserProxyPaneState", () => {
resolveBrowserProxyPaneState({
routing: supportedRouting,
effectiveRoutingMode: "host",
localPartition: "persist:paseo-browser",
profileSlug: "default",
hostLabel: "devbox",
proxyStatusSnapshot: {
serverId: "srv-remote",
partition: "persist:paseo-browser-host-0123456789abcdef",
profilePartitions: { default: "persist:paseo-browser-host-0123456789abcdef" },
status: "ready",
error: null,
socksPort: 41234,
@@ -159,11 +159,11 @@ describe("resolveBrowserProxyPaneState", () => {
resolveBrowserProxyPaneState({
routing: supportedRouting,
effectiveRoutingMode: "host",
localPartition: "persist:paseo-browser",
profileSlug: "default",
hostLabel: "devbox",
proxyStatusSnapshot: {
serverId: "srv-remote",
partition: "persist:paseo-browser-host-0123456789abcdef",
profilePartitions: { default: "persist:paseo-browser-host-0123456789abcdef" },
status: "error",
error: "Unable to create ticket",
socksPort: null,
@@ -185,7 +185,7 @@ describe("resolveBrowserProxyPaneState", () => {
const routedTarget = { via: "unix:///tmp/paseo.sock", serverId: "srv-dev" };
const input = {
effectiveRoutingMode: "host" as const,
localPartition: "persist:paseo-browser",
profileSlug: "default",
hostLabel: "dev",
ensureError: null,
onRetry: noop,
@@ -212,7 +212,7 @@ describe("resolveBrowserProxyPaneState", () => {
routing,
proxyStatusSnapshot: {
serverId: "srv-dev",
partition: "persist:paseo-browser-host-dev",
profilePartitions: { default: "persist:paseo-browser-host-dev" },
status: "ready",
error: null,
socksPort: 41000,
@@ -250,7 +250,7 @@ describe("resolveBrowserProxyPaneState", () => {
routing: { kind: "remote", support: "host_connecting" },
proxyStatusSnapshot: {
serverId: "srv-dev",
partition: "persist:paseo-browser-host-dev",
profilePartitions: { default: "persist:paseo-browser-host-dev" },
status: "ready",
error: null,
socksPort: 41000,
@@ -259,4 +259,102 @@ describe("resolveBrowserProxyPaneState", () => {
).toMatchObject({ kind: "ready", proxyStatus: "reconnecting" });
});
});
describe("browser profiles", () => {
const hostDefault = "persist:paseo-browser-host-0123456789abcdef";
const hostWork = `${hostDefault}-profile-work`;
const supportedRouting = {
kind: "remote" as const,
support: "supported" as const,
target: "tcp://10.0.0.5:6767",
};
const base = {
hostLabel: "devbox",
ensureError: null,
onRetry: noop,
};
it("mounts the local partition of the tab's profile when routing locally", () => {
expect(
resolveBrowserProxyPaneState({
...base,
routing: supportedRouting,
effectiveRoutingMode: "local",
profileSlug: "work",
proxyStatusSnapshot: null,
}),
).toMatchObject({ kind: "ready", partition: "persist:paseo-profile-work" });
});
it("waits for the host to bind the profile's session instead of mounting another profile", () => {
expect(
resolveBrowserProxyPaneState({
...base,
routing: supportedRouting,
effectiveRoutingMode: "host",
profileSlug: "work",
proxyStatusSnapshot: {
serverId: "srv-remote",
profilePartitions: { default: hostDefault },
status: "ready",
error: null,
socksPort: 41234,
},
}),
).toMatchObject({ kind: "connecting", effectiveRoutingMode: "host" });
});
it("waits for a profile whose slug matches an Object property name", () => {
expect(
resolveBrowserProxyPaneState({
...base,
routing: supportedRouting,
effectiveRoutingMode: "host",
profileSlug: "constructor",
proxyStatusSnapshot: {
serverId: "srv-remote",
profilePartitions: { default: hostDefault },
status: "ready",
error: null,
socksPort: 41234,
},
}),
).toMatchObject({ kind: "connecting", effectiveRoutingMode: "host" });
});
it("mounts the host partition of the tab's profile once it is bound", () => {
const snapshot = {
serverId: "srv-remote",
profilePartitions: { default: hostDefault, work: hostWork },
status: "ready" as const,
error: null,
socksPort: 41234,
};
expect(
resolveBrowserProxyPaneState({
...base,
routing: supportedRouting,
effectiveRoutingMode: "host",
profileSlug: "work",
proxyStatusSnapshot: snapshot,
}),
).toEqual({
kind: "ready",
partition: hostWork,
isRemoteHost: true,
effectiveRoutingMode: "host",
hostLabel: "devbox",
proxyStatus: "ready",
});
expect(
resolveBrowserProxyPaneState({
...base,
routing: { kind: "remote", support: "host_offline" },
effectiveRoutingMode: "host",
profileSlug: "work",
proxyStatusSnapshot: snapshot,
}),
).toMatchObject({ kind: "ready", partition: hostWork, proxyStatus: "reconnecting" });
});
});
});
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { getIsElectron } from "@/constants/platform";
import { getDesktopHost, type DesktopBrowserProxyStatus } from "@/desktop/host";
import type { DesktopBrowserProxyStatus } from "@/desktop/host";
import { getBrowserProfilePartition } from "@/desktop/browser/profiles";
import { resolveBrowserRoutingMode, type BrowserRoutingMode } from "@/desktop/browser/store";
import { useHosts } from "@/runtime/host-runtime";
import { normalizeHostLabel } from "@/types/host-connection";
@@ -51,29 +52,35 @@ export type BrowserProxyPaneState =
retry: () => void;
};
function hasPreparedHostPartition(
/** The profile's host partition, once main has bound its session to the host's SOCKS5 port. */
function readPreparedHostPartition(
snapshot: ReturnType<typeof getCachedBrowserProxyStatus>,
): snapshot is NonNullable<ReturnType<typeof getCachedBrowserProxyStatus>> & {
partition: string;
socksPort: number;
} {
return Boolean(snapshot?.partition && snapshot.socksPort !== null);
profileSlug: string,
): string | null {
if (
!snapshot ||
snapshot.socksPort === null ||
!Object.hasOwn(snapshot.profilePartitions, profileSlug)
) {
return null;
}
return snapshot.profilePartitions[profileSlug] ?? null;
}
function resolveRemoteUnavailablePaneState(
support: Exclude<Extract<HostBrowserRouting, { kind: "remote" }>["support"], "supported">,
hostLabel: string,
proxyStatusSnapshot: ReturnType<typeof getCachedBrowserProxyStatus>,
preparedPartition: string | null,
): 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.
// Once Electron main has verified and bound this profile's session to the host's
// fixed SOCKS5 port, 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)) {
if (isTransientDisconnect && preparedPartition) {
return {
kind: "ready",
partition: proxyStatusSnapshot.partition,
partition: preparedPartition,
isRemoteHost: true,
effectiveRoutingMode: "host",
hostLabel,
@@ -109,7 +116,7 @@ function resolvePreparedHostPaneStatus(
export function resolveBrowserProxyPaneState(input: {
routing: HostBrowserRouting;
effectiveRoutingMode: BrowserRoutingMode;
localPartition: string;
profileSlug: string;
hostLabel: string;
proxyStatusSnapshot: ReturnType<typeof getCachedBrowserProxyStatus>;
ensureError: string | null;
@@ -118,7 +125,7 @@ export function resolveBrowserProxyPaneState(input: {
const {
routing,
effectiveRoutingMode,
localPartition,
profileSlug,
hostLabel,
proxyStatusSnapshot,
ensureError,
@@ -128,7 +135,7 @@ export function resolveBrowserProxyPaneState(input: {
if (routing.kind === "local" || effectiveRoutingMode === "local") {
return {
kind: "ready",
partition: localPartition,
partition: getBrowserProfilePartition(profileSlug),
isRemoteHost: routing.kind === "remote",
effectiveRoutingMode: "local",
hostLabel,
@@ -136,17 +143,18 @@ export function resolveBrowserProxyPaneState(input: {
};
}
const preparedPartition = readPreparedHostPartition(proxyStatusSnapshot, profileSlug);
if (routing.support !== "supported") {
return resolveRemoteUnavailablePaneState(routing.support, hostLabel, proxyStatusSnapshot);
return resolveRemoteUnavailablePaneState(routing.support, hostLabel, preparedPartition);
}
// 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)) {
// Once the profile's session is bound to the fixed-port SOCKS5 proxy, 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 (proxyStatusSnapshot && preparedPartition) {
return {
kind: "ready",
partition: proxyStatusSnapshot.partition,
partition: preparedPartition,
isRemoteHost: true,
effectiveRoutingMode: "host",
hostLabel,
@@ -179,8 +187,9 @@ export function resolveBrowserProxyPaneState(input: {
export function useHostBrowserProxy(input: {
serverId: string;
routingMode?: BrowserRoutingMode;
profileSlug: string;
}): BrowserProxyPaneState {
const { serverId, routingMode } = input;
const { serverId, routingMode, profileSlug } = input;
const hosts = useHosts();
const host = useMemo(
() => hosts.find((entry) => entry.serverId === serverId) ?? null,
@@ -200,6 +209,9 @@ export function useHostBrowserProxy(input: {
);
const [retryCounter, setRetryCounter] = useState(0);
// A retry replaces the host tunnel once. Later runs (another profile on the same host)
// reuse the tunnel that other tabs on this host share.
const reconnectedRetryRef = useRef(0);
const [ensureError, setEnsureError] = useState<string | null>(null);
const effectiveRoutingMode = resolveBrowserRoutingMode(
@@ -225,10 +237,13 @@ export function useHostBrowserProxy(input: {
installBrowserProxyRendererBridge();
setEnsureError(null);
const forceReconnect = retryCounter > reconnectedRetryRef.current;
reconnectedRetryRef.current = retryCounter;
void ensureHostBrowserProxy({
serverId,
target: supportedTarget,
forceReconnect: retryCounter > 0,
profileSlug,
forceReconnect,
})
.then((snapshot) => {
if (cancelled) return undefined;
@@ -249,13 +264,12 @@ export function useHostBrowserProxy(input: {
};
// targetKey serializes supportedTarget deterministically.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [effectiveRoutingMode, retryCounter, serverId, targetKey]);
}, [effectiveRoutingMode, profileSlug, retryCounter, serverId, targetKey]);
const localPartition = getDesktopHost()?.browser?.profilePartition ?? "persist:paseo-browser";
return resolveBrowserProxyPaneState({
routing,
effectiveRoutingMode,
localPartition,
profileSlug,
hostLabel,
proxyStatusSnapshot,
ensureError,
+3 -1
View File
@@ -177,7 +177,8 @@ export type DesktopBrowserProxyStatus = "idle" | "connecting" | "ready" | "recon
export interface DesktopBrowserProxyStatusSnapshot {
serverId: string;
partition: string;
/** Profile slug -> partition, for every profile session bound to this host's proxy. */
profilePartitions: Record<string, string>;
status: DesktopBrowserProxyStatus;
error: string | null;
socksPort: number | null;
@@ -218,6 +219,7 @@ export interface DesktopBrowserBridge {
ensureHostProxy?: (input: {
serverId: string;
target: HostTransportSpec;
profileSlug?: string;
forceReconnect?: boolean;
}) => Promise<DesktopBrowserProxyStatusSnapshot>;
updateHostProxyTarget?: (input: { serverId: string; target: HostTransportSpec }) => Promise<void>;
+276 -12
View File
@@ -587,6 +587,236 @@ function describeProcess(pid) {
return { pid, serverId: serverId ?? null, command };
}
async function evaluateMainProcess(inspectorPort, expression) {
const [target] = await (await fetch(`http://127.0.0.1:${inspectorPort}/json/list`)).json();
const socket = new WebSocket(target.webSocketDebuggerUrl);
try {
return await new Promise((resolve, reject) => {
socket.once("error", reject);
socket.on("message", (data) => {
const response = JSON.parse(String(data));
if (response.id !== 1) return;
if (response.error || response.result?.exceptionDetails) reject(new Error(String(data)));
else resolve(response.result.result.value);
});
socket.once("open", () =>
socket.send(
JSON.stringify({
id: 1,
method: "Runtime.evaluate",
params: {
expression: `(async () => { const electron = process.mainModule.require('electron'); ${expression} })()`,
returnByValue: true,
awaitPromise: true,
},
}),
),
);
});
} finally {
socket.close();
}
}
/** Accepts the next native confirm dialog by clicking the button labeled `label`. */
async function acceptNextDialog(inspect, label) {
await inspect(`const { dialog } = electron; const show = dialog.showMessageBox;
dialog.showMessageBox = async (owner, options) => {
dialog.showMessageBox = show;
return { response: options.buttons.indexOf(${JSON.stringify(label)}), checkboxChecked: false };
}; return true;`);
}
async function openBrowserProfileSettings(page) {
await page.getByRole("button", { name: "Settings", exact: true }).click();
await page
.locator('[data-testid="settings-sidebar"]:visible')
.getByRole("button", { name: "Chat & panes", exact: true })
.click();
await expect(page.getByTestId("settings-browser-profile-row-default")).toBeVisible();
}
/**
* On a host-proxied tab, creates and switches profiles, and proves each profile on the
* host has its own storage while its requests still leave through the host daemon over
* the host's one tunnel. Then clears and removes the profile from Settings.
*/
async function verifyHostProxiedProfiles({
page,
inspect,
relayBridge,
targetServer,
targetUrl,
hostPartition,
routingPill,
userData,
}) {
const picker = () => page.locator('[data-testid="browser-profile-picker"]:visible');
const hostWorkPartition = `${hostPartition}-profile-work`;
const guestAt = (partition) => readGuestState(page, { exactPartition: partition });
const runInGuest = (partition, code) =>
page.evaluate(
async (input) => {
const wv = [...document.querySelectorAll("webview")].find(
(el) => el.getAttribute("partition") === input.partition,
);
return await wv.executeJavaScript(input.code);
},
{ partition, code },
);
const markGuest = (partition, marker) =>
runInGuest(
partition,
`localStorage.setItem("partition_marker", ${JSON.stringify(marker)}); document.cookie = "profile=${marker}; Path=/; Max-Age=86400";`,
);
const cookieAt = (partition) => runInGuest(partition, "document.cookie");
const choose = async (slug, name) => {
await picker().click();
await page.getByTestId(`browser-profile-option-${slug}`).click();
await expect(picker()).toHaveAttribute("aria-label", `Browser profile: ${name}`);
};
const tunnelStats = () => {
const stats = relayBridge.getStats("e2e-remote-host");
return {
clientConnections: stats.clientConnections,
tunnelBytes: stats.connections[1]?.serverToClientBytes ?? 0,
};
};
const loadedPage = {
found: true,
heading: "Proxied HTTP OK",
wsResult: "WS_OK:ack:hello-tunnel",
};
const poll = (fn) => expect.poll(fn, { timeout: 30_000, intervals: [250, 500, 1000] });
// 1. The profile picker is on the host-proxied tab; create Work there.
await expect(picker()).toHaveAttribute("aria-label", "Browser profile: Default");
const before = tunnelStats();
const wsCountBefore = targetServer.wsClientPorts.length;
await picker().click();
await page.getByTestId("browser-profile-create-trigger").click();
await page.getByTestId("browser-create-profile-input").fill("Work");
await page.getByTestId("browser-create-profile-submit").click();
await expect(picker()).toHaveAttribute("aria-label", "Browser profile: Work");
await poll(() => guestAt(hostWorkPartition)).toMatchObject({ ...loadedPage, marker: null });
// 2. Work still goes through the host: same SOCKS5 port, same tunnel, host daemon egress.
const status = await page.evaluate(
async () => await window.paseoDesktop.browser.getHostProxyStatus("e2e-remote-host"),
);
assert(
status?.status === "ready" &&
status.profilePartitions.default === hostPartition &&
status.profilePartitions.work === hostWorkPartition &&
typeof status.socksPort === "number",
`Expected Default and Work bound to the host proxy, got ${JSON.stringify(status)}`,
);
const resolvedProxy = await inspect(
`return await electron.session.fromPartition(${JSON.stringify(hostWorkPartition)}).resolveProxy("http://localhost:${targetServer.port}/");`,
);
assert(
resolvedProxy.includes(`SOCKS5 127.0.0.1:${status.socksPort}`),
`Expected Work to resolve to the host SOCKS5 port ${status.socksPort}, got ${resolvedProxy}`,
);
const after = tunnelStats();
assert(
after.clientConnections === before.clientConnections && after.tunnelBytes > before.tunnelBytes,
`Expected Work to reuse the host tunnel, before=${JSON.stringify(before)} after=${JSON.stringify(after)}`,
);
const workWsPort = targetServer.wsClientPorts.slice(wsCountBefore).at(-1);
assert(workWsPort, "Expected a guest WebSocket from the Work profile");
const egressPid =
process.platform === "linux"
? processOwningConnection({ localPort: workWsPort, peerPort: targetServer.port })
: null;
const egressProcess = egressPid ? describeProcess(egressPid) : "skipped: needs Linux";
assert(
process.platform !== "linux" || egressProcess.serverId === "e2e-remote-host",
`Expected the remote daemon to own Work's target connection, got ${JSON.stringify(egressProcess)}`,
);
// 3. Default and Work keep separate storage and cookies on the same host.
await markGuest(hostWorkPartition, "host-work");
await choose("default", "Default");
await poll(() => guestAt(hostPartition)).toMatchObject({
...loadedPage,
marker: "from-host-partition",
});
assert(
!(await cookieAt(hostPartition)).includes("profile=host-work"),
"Expected the host Default profile not to see Work's cookie",
);
await choose("work", "Work");
await poll(() => guestAt(hostWorkPartition)).toMatchObject({
...loadedPage,
marker: "host-work",
});
// 4. Work on the local route is a different partition from Work on the host route.
await routingPill.click();
await expect(routingPill).toHaveAttribute(
"aria-label",
"Switch browser routing from Local to Remote Proxy Host",
{ timeout: 15_000 },
);
await poll(() => guestAt("persist:paseo-profile-work")).toMatchObject({
...loadedPage,
marker: null,
});
await routingPill.click();
await expect(routingPill).toHaveAttribute(
"aria-label",
"Switch browser routing from Remote Proxy Host to Local",
{ timeout: 15_000 },
);
await poll(() => guestAt(hostWorkPartition)).toMatchObject({
...loadedPage,
marker: "host-work",
});
// 5. A second host tab on Default, to prove Clear and Remove leave Default alone.
await openNewBrowserTabAndNavigate(page, targetUrl);
await expect(picker()).toHaveAttribute("aria-label", "Browser profile: Default");
await poll(() => guestAt(hostPartition)).toMatchObject({
...loadedPage,
marker: "from-host-partition",
});
// 6. Clear Work in Settings clears it on the host route too; Default keeps its data.
const hostWorkDir = path.join(userData, "Partitions", hostWorkPartition.slice("persist:".length));
await poll(() => fs.existsSync(hostWorkDir)).toBe(true);
await openBrowserProfileSettings(page);
await acceptNextDialog(inspect, "Clear data");
await page.getByTestId("settings-browser-profile-menu-work").click();
await page.getByTestId("settings-browser-profile-clear-work").click();
await expect(page.getByText("Browser data cleared", { exact: true })).toBeVisible();
await poll(() => guestAt(hostWorkPartition)).toMatchObject({ ...loadedPage, marker: null });
assert(
!(await cookieAt(hostWorkPartition)).includes("profile=host-work"),
"Expected Clear data to remove Work's cookie on the host route",
);
await poll(() => guestAt(hostPartition)).toMatchObject({ marker: "from-host-partition" });
// 7. Remove Work closes its host-proxied tab and deletes its host partition directory.
await acceptNextDialog(inspect, "Remove");
await page.getByTestId("settings-browser-profile-menu-work").click();
await page.getByTestId("settings-browser-profile-remove-work").click();
await expect(page.getByTestId("settings-browser-profile-row-work")).toHaveCount(0);
await poll(() => fs.existsSync(hostWorkDir)).toBe(false);
await page.getByTestId("settings-back-to-workspace").click();
await poll(async () => (await guestAt(hostWorkPartition)).found).toBe(false);
await poll(() => guestAt(hostPartition)).toMatchObject({ marker: "from-host-partition" });
return {
hostWorkPartition,
socksPort: status.socksPort,
resolvedProxy,
tunnelConnections: after.clientConnections,
egressProcess,
clearAndRemove: "passed",
};
}
async function waitForAppPage(browser, expoPort) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
@@ -679,8 +909,10 @@ async function openNewBrowserTabAndNavigate(page, url) {
await expect(newTabBtn).toBeVisible({ timeout: 30_000 });
await newTabBtn.click();
// An empty pane lists launchers as buttons; a pane with tabs opens a menu instead.
const browserOption = page
.getByRole("button", { name: /^Browser/i })
.or(page.getByRole("menuitem", { name: /^Browser/i }))
.and(page.locator(":visible"))
.first();
await expect(browserOption).toBeVisible({ timeout: 15_000 });
@@ -750,7 +982,7 @@ async function verifyRoutedHostBrowsing({ page, targetServer, targetUrl }) {
);
assert(
routedProxyStatus?.status === "ready" &&
routedProxyStatus.partition === routedPartition &&
routedProxyStatus.profilePartitions.default === routedPartition &&
typeof routedProxyStatus.socksPort === "number",
`Expected a ready routed host proxy, got ${JSON.stringify(routedProxyStatus)}`,
);
@@ -793,15 +1025,23 @@ async function main() {
const userData = path.join(runtimeDir, "electron-user-data");
const workspaceRoot = path.join(runtimeDir, "workspaces");
const [localDaemonPort, remoteDaemonPort, oldDaemonPort, routedDaemonPort, expoPort, cdpPort] =
await Promise.all([
reservePort(),
reservePort(),
reservePort(),
reservePort(),
reservePort(),
reservePort(),
]);
const [
localDaemonPort,
remoteDaemonPort,
oldDaemonPort,
routedDaemonPort,
expoPort,
cdpPort,
inspectorPort,
] = await Promise.all([
reservePort(),
reservePort(),
reservePort(),
reservePort(),
reservePort(),
reservePort(),
reservePort(),
]);
// The local daemon requires a password the renderer never sees, so the routed
// tunnel can only authenticate to it with the desktop-managed local credential.
const localDaemonPassword = "browser-proxy-e2e-local-password";
@@ -811,6 +1051,7 @@ async function main() {
const children = [];
let legacyAdapter = null;
let browser = null;
let appPage = null;
try {
seedPaseoHome({
@@ -956,6 +1197,7 @@ async function main() {
const desktopArgs = [
process.execPath,
devRunner,
`--inspect=127.0.0.1:${inspectorPort}`,
...(process.platform === "linux" ? ["--no-sandbox"] : []),
];
const desktopCommand = process.platform === "linux" ? "xvfb-run" : desktopArgs.shift();
@@ -990,6 +1232,7 @@ async function main() {
browser = await chromium.connectOverCDP(`http://127.0.0.1:${cdpPort}`);
const page = await waitForAppPage(browser, expoPort);
appPage = page;
await hideDeveloperToasts(page);
await waitForDesktopStatus(page);
@@ -1169,7 +1412,22 @@ async function main() {
});
// -------------------------------------------------------------------------
// 3. Old daemon without features.networkTunnel fails closed + Browse locally
// 3. Browser profiles on the host-proxied tab
// -------------------------------------------------------------------------
const hostProfiles = await verifyHostProxiedProfiles({
page,
inspect: (expression) => evaluateMainProcess(inspectorPort, expression),
relayBridge,
targetServer,
targetUrl,
hostPartition: hostGuest.partition,
routingPill,
userData,
});
await page.screenshot({ path: path.join(artifactDir, "03-host-profiles.png") });
// -------------------------------------------------------------------------
// 4. Old daemon without features.networkTunnel fails closed + Browse locally
// -------------------------------------------------------------------------
const oldWsButton = page
.getByRole("button", {
@@ -1233,7 +1491,7 @@ async function main() {
await page.screenshot({ path: path.join(artifactDir, "04-old-daemon-browse-locally.png") });
// -------------------------------------------------------------------------
// 4. Routed host: desktop -> local daemon -> routed daemon -> target
// 5. Routed host: desktop -> local daemon -> routed daemon -> target
// -------------------------------------------------------------------------
const routedHost = await verifyRoutedHostBrowsing({
page,
@@ -1254,6 +1512,7 @@ async function main() {
binaryFrames: secondaryTunnelConn.binaryFrames,
},
togglePartitionIsolation: "passed",
hostProfiles,
oldDaemonFailClosedAndBrowseLocally: "passed",
routedHost,
artifactDir,
@@ -1262,6 +1521,11 @@ async function main() {
2,
),
);
} catch (error) {
await appPage
?.screenshot({ path: path.join(artifactDir, "failure.png") })
.catch(() => undefined);
throw error;
} finally {
await browser?.close().catch(() => undefined);
legacyAdapter?.close();
@@ -0,0 +1,74 @@
import { describe, expect, test } from "vitest";
import { getBrowserPartition, parseBrowserPartition } from "./browser-partition.js";
const LOCAL = { kind: "local" } as const;
const host = (serverId: string) => ({ kind: "host", serverId }) as const;
describe("browser partition naming", () => {
test("keeps the existing local and host default partition names", () => {
expect(getBrowserPartition(LOCAL, "default")).toBe("persist:paseo-browser");
expect(getBrowserPartition(LOCAL, "work")).toBe("persist:paseo-profile-work");
expect(getBrowserPartition(host("srv_alpha_123"), "default")).toMatch(
/^persist:paseo-browser-host-[0-9a-f]{16}$/,
);
});
test("composes a host route with a named profile into its own deterministic partition", () => {
const hostDefault = getBrowserPartition(host("srv_alpha_123"), "default");
const hostWork = getBrowserPartition(host("srv_alpha_123"), "work");
expect(hostWork).toBe(`${hostDefault}-profile-work`);
expect(getBrowserPartition(host("srv_alpha_123"), "work")).toBe(hostWork);
expect(getBrowserPartition(host("srv_beta_456"), "work")).not.toBe(hostWork);
expect(getBrowserPartition(host("srv_alpha_123"), "customer")).not.toBe(hostWork);
});
test("rejects invalid routes and profile slugs", () => {
expect(() => getBrowserPartition(host(" "), "default")).toThrow();
expect(() => getBrowserPartition(LOCAL, "Work")).toThrow();
expect(() => getBrowserPartition(host("srv"), "a--b")).toThrow();
});
test("parses every route and profile combination back", () => {
const hostDefault = getBrowserPartition(host("srv"), "default");
expect(parseBrowserPartition("persist:paseo-browser")).toEqual({
route: "local",
profileSlug: "default",
});
expect(parseBrowserPartition("persist:paseo-profile-work")).toEqual({
route: "local",
profileSlug: "work",
});
expect(parseBrowserPartition(hostDefault)).toEqual({ route: "host", profileSlug: "default" });
expect(parseBrowserPartition(`${hostDefault}-profile-work`)).toEqual({
route: "host",
profileSlug: "work",
});
// A slug may itself look like a host suffix; the local prefix still owns it.
expect(parseBrowserPartition("persist:paseo-profile-work-host-0123456789abcdef")).toEqual({
route: "local",
profileSlug: "work-host-0123456789abcdef",
});
});
test("rejects partitions outside the Paseo browser namespace", () => {
for (const partition of [
undefined,
42,
"persist:foreign",
"paseo-browser",
"persist:paseo-profile-default",
"persist:paseo-profile-Work",
"persist:paseo-browser-tab-a",
"persist:paseo-browser-host-0123456789abcde",
"persist:paseo-browser-host-0123456789ABCDEF",
"persist:paseo-browser-host-0123456789abcdef0",
"persist:paseo-browser-host-0123456789abcdef-profile-",
"persist:paseo-browser-host-0123456789abcdef-profile-default",
"persist:paseo-browser-host-0123456789abcdef-profile-Work",
"persist:paseo-browser-11111111-1111-4111-8111-111111111111",
]) {
expect(parseBrowserPartition(partition)).toBeNull();
}
});
});
@@ -0,0 +1,81 @@
import { createHash } from "node:crypto";
/**
* A browser tab's Electron session partition is the pair (route, profile).
* Electron binds `session.setProxy` per partition, so the route lives in the name,
* and the profile keeps cookies and storage apart on that route.
*
* local + default persist:paseo-browser
* local + <slug> persist:paseo-profile-<slug>
* host + default persist:paseo-browser-host-<16hex>
* host + <slug> persist:paseo-browser-host-<16hex>-profile-<slug>
*
* The first three names predate this module and must not change: they hold the user's
* existing cookies and storage on disk.
*/
export type BrowserRoute = { kind: "local" } | { kind: "host"; serverId: string };
export interface ParsedBrowserPartition {
route: BrowserRoute["kind"];
profileSlug: string;
}
export const DEFAULT_BROWSER_PROFILE_SLUG = "default";
export const PASEO_BROWSER_PROFILE_PARTITION = "persist:paseo-browser";
const PERSIST = "persist:";
const LOCAL_PROFILE_PREFIX = "paseo-profile-";
const HOST_PREFIX = "paseo-browser-host-";
const HOST_PROFILE_INFIX = "-profile-";
const NAMED_SLUG = /^(?=.{1,48}$)[a-z0-9]+(?:-[a-z0-9]+)*$/;
const HOST_PARTITION = /^paseo-browser-host-([0-9a-f]{16})(?:-profile-(.+))?$/;
export function isNamedBrowserProfileSlug(slug: string): boolean {
return NAMED_SLUG.test(slug) && slug !== DEFAULT_BROWSER_PROFILE_SLUG;
}
function hostKey(serverId: string): string {
const normalized = serverId.trim();
if (!normalized) {
throw new Error("Host serverId is required to derive a browser partition");
}
return createHash("sha256").update(normalized, "utf8").digest("hex").slice(0, 16);
}
export function getBrowserPartition(route: BrowserRoute, profileSlug: string): string {
const isDefault = profileSlug === DEFAULT_BROWSER_PROFILE_SLUG;
if (!isDefault && !isNamedBrowserProfileSlug(profileSlug)) {
throw new Error(`Invalid browser profile slug: ${profileSlug}`);
}
if (route.kind === "local") {
return isDefault
? PASEO_BROWSER_PROFILE_PARTITION
: `${PERSIST}${LOCAL_PROFILE_PREFIX}${profileSlug}`;
}
const hostPartition = `${PERSIST}${HOST_PREFIX}${hostKey(route.serverId)}`;
return isDefault ? hostPartition : `${hostPartition}${HOST_PROFILE_INFIX}${profileSlug}`;
}
/** Returns the (route, profile) of a Paseo browser partition, or null for any other partition. */
export function parseBrowserPartition(partition: unknown): ParsedBrowserPartition | null {
if (typeof partition !== "string" || !partition.startsWith(PERSIST)) {
return null;
}
if (partition === PASEO_BROWSER_PROFILE_PARTITION) {
return { route: "local", profileSlug: DEFAULT_BROWSER_PROFILE_SLUG };
}
const name = partition.slice(PERSIST.length);
if (name.startsWith(LOCAL_PROFILE_PREFIX)) {
const slug = name.slice(LOCAL_PROFILE_PREFIX.length);
return isNamedBrowserProfileSlug(slug) ? { route: "local", profileSlug: slug } : null;
}
const host = HOST_PARTITION.exec(name);
if (!host) {
return null;
}
const slug = host[2];
if (slug === undefined) {
return { route: "host", profileSlug: DEFAULT_BROWSER_PROFILE_SLUG };
}
return isNamedBrowserProfileSlug(slug) ? { route: "host", profileSlug: slug } : null;
}
@@ -2,11 +2,8 @@ import { randomUUID } from "node:crypto";
import { readFile, rename, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { z } from "zod";
import {
BROWSER_PROFILE_COLORS,
isNamedBrowserProfileSlug,
type BrowserProfileColor,
} from "./browser-profile.js";
import { isNamedBrowserProfileSlug } from "./browser-partition.js";
import { BROWSER_PROFILE_COLORS, type BrowserProfileColor } from "./browser-profile.js";
const colorSchema = z.enum(BROWSER_PROFILE_COLORS);
const nameSchema = z.string().trim().min(1).max(80);
@@ -2,24 +2,27 @@ import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, it, vi } from "vitest";
import { getBrowserPartition, PASEO_BROWSER_PROFILE_PARTITION } from "./browser-partition.js";
import {
clearPaseoBrowserProfile,
deleteBrowserProfilePartitionDirectory,
getBrowserProfilePartition,
deleteBrowserProfilePartitionDirectories,
getLegacyPaseoBrowserProfileSession,
getPaseoBrowserProfileSession,
getPaseoBrowserProfileSessions,
isNamedBrowserProfileSlug,
isPaseoBrowserProfilePartition,
listBrowserPartitionDirectories,
listDiskHostBrowserProxyPartitions,
listPaseoBrowserProfileGuests,
PASEO_BROWSER_PROFILE_PARTITION,
pruneOrphanedBrowserProfilePartitions,
readHostBrowserProxyPartitions,
readLegacyPaseoBrowserIds,
} from "./browser-profile.js";
import { getHostBrowserProxyPartition } from "./browser-proxy/partition.js";
function getHostBrowserProxyPartition(serverId: string, profileSlug = "default"): string {
return getBrowserPartition({ kind: "host", serverId }, profileSlug);
}
function directoryOf(partition: string): string {
return partition.slice("persist:".length);
}
function createFakeSession() {
return {
@@ -29,34 +32,37 @@ function createFakeSession() {
};
}
describe("browser profile partition naming", () => {
it("maps default and named slugs to persistent partitions", () => {
expect(getBrowserProfilePartition("default")).toBe(PASEO_BROWSER_PROFILE_PARTITION);
expect(getBrowserProfilePartition("work")).toBe("persist:paseo-profile-work");
expect(isNamedBrowserProfileSlug("work")).toBe(true);
expect(isNamedBrowserProfileSlug("default")).toBe(false);
expect(isNamedBrowserProfileSlug("Work")).toBe(false);
expect(isNamedBrowserProfileSlug("a--b")).toBe(false);
expect(isPaseoBrowserProfilePartition(PASEO_BROWSER_PROFILE_PARTITION)).toBe(true);
expect(isPaseoBrowserProfilePartition("persist:paseo-profile-work")).toBe(true);
expect(isPaseoBrowserProfilePartition("persist:paseo-profile-default")).toBe(false);
expect(isPaseoBrowserProfilePartition("persist:other")).toBe(false);
});
it("deletes a named profile partition directory and refuses default", async () => {
describe("browser profile partition directories", () => {
it("deletes a named profile's local and host-proxied directories and refuses default", async () => {
const userData = await mkdtemp(path.join(os.tmpdir(), "paseo-partitions-"));
try {
const workDir = path.join(userData, "Partitions", "paseo-profile-work");
const defaultDir = path.join(userData, "Partitions", "paseo-browser");
await mkdir(workDir, { recursive: true });
await mkdir(defaultDir, { recursive: true });
const partitions = (name: string) => path.join(userData, "Partitions", name);
const workDir = partitions("paseo-profile-work");
const hostWorkDir = partitions(directoryOf(getHostBrowserProxyPartition("remote-a", "work")));
const otherHostWorkDir = partitions(
directoryOf(getHostBrowserProxyPartition("remote-b", "work")),
);
const kept = [
partitions("paseo-browser"),
partitions(directoryOf(getHostBrowserProxyPartition("remote-a"))),
partitions(directoryOf(getHostBrowserProxyPartition("remote-a", "customer"))),
partitions("paseo-profile-customer"),
];
for (const dir of [workDir, hostWorkDir, otherHostWorkDir, ...kept]) {
await mkdir(dir, { recursive: true });
}
await writeFile(path.join(workDir, "Cookies"), "alice");
await writeFile(path.join(hostWorkDir, "Cookies"), "alice-on-host");
await deleteBrowserProfilePartitionDirectory(userData, "work");
await deleteBrowserProfilePartitionDirectories(userData, "work");
await expect(stat(workDir)).rejects.toThrow();
expect((await stat(defaultDir)).isDirectory()).toBe(true);
await expect(deleteBrowserProfilePartitionDirectory(userData, "default")).rejects.toThrow();
for (const dir of [workDir, hostWorkDir, otherHostWorkDir]) {
await expect(stat(dir)).rejects.toThrow();
}
for (const dir of kept) {
expect((await stat(dir)).isDirectory()).toBe(true);
}
await expect(deleteBrowserProfilePartitionDirectories(userData, "default")).rejects.toThrow();
} finally {
await rm(userData, { recursive: true, force: true });
}
@@ -109,9 +115,9 @@ describe("listPaseoBrowserProfileGuests", () => {
});
describe("getPaseoBrowserProfileSessions", () => {
it("scopes single-profile clearing to only that profile session", () => {
function createSessions() {
const byPartition = new Map<string, ReturnType<typeof createFakeSession>>();
const sessions = {
return {
fromPartition: vi.fn((partition: string) => {
let existing = byPartition.get(partition);
if (!existing) {
@@ -121,46 +127,82 @@ describe("getPaseoBrowserProfileSessions", () => {
return existing;
}),
};
}
const openedPartitions = (sessions: ReturnType<typeof createSessions>) =>
sessions.fromPartition.mock.calls.map(([partition]) => partition);
const directories = [
"paseo-profile-work",
"paseo-profile-customer",
"paseo-browser-11111111-1111-4111-8111-111111111111",
];
const hostDefault = getHostBrowserProxyPartition("remote-host-1");
const hostWork = getHostBrowserProxyPartition("remote-host-1", "work");
const otherHostWork = getHostBrowserProxyPartition("remote-host-2", "work");
const hostCustomer = getHostBrowserProxyPartition("remote-host-1", "customer");
const legacy = "paseo-browser-11111111-1111-4111-8111-111111111111";
const directories = [
"paseo-profile-work",
"paseo-profile-customer",
legacy,
directoryOf(hostDefault),
directoryOf(otherHostWork),
directoryOf(hostCustomer),
"unrelated",
];
const workOnly = getPaseoBrowserProfileSessions(sessions, directories, { slug: "work" });
expect(workOnly).toHaveLength(1);
expect(sessions.fromPartition).toHaveBeenCalledWith("persist:paseo-profile-work");
sessions.fromPartition.mockClear();
const hostPartition = getHostBrowserProxyPartition("remote-host-1");
const defaultWithHost = getPaseoBrowserProfileSessions(sessions, directories, {
slug: "default",
hostPartitions: [hostPartition],
it("clears a named profile across the local route and every host route", () => {
const sessions = createSessions();
const work = getPaseoBrowserProfileSessions(sessions, directories, {
slug: "work",
hostPartitions: [hostWork, hostDefault],
});
expect(defaultWithHost).toHaveLength(3);
expect(sessions.fromPartition.mock.calls.map(([p]) => p)).toEqual([
PASEO_BROWSER_PROFILE_PARTITION,
"persist:paseo-browser-11111111-1111-4111-8111-111111111111",
hostPartition,
expect(work).toHaveLength(3);
expect(openedPartitions(sessions)).toEqual([
"persist:paseo-profile-work",
otherHostWork,
hostWork,
]);
});
sessions.fromPartition.mockClear();
it("clears Default across the local route, legacy tabs, and every host route", () => {
const sessions = createSessions();
const defaults = getPaseoBrowserProfileSessions(sessions, directories, {
slug: "default",
hostPartitions: [hostWork, getHostBrowserProxyPartition("remote-host-3")],
});
expect(defaults).toHaveLength(4);
expect(openedPartitions(sessions)).toEqual([
PASEO_BROWSER_PROFILE_PARTITION,
`persist:${legacy}`,
hostDefault,
getHostBrowserProxyPartition("remote-host-3"),
]);
});
it("clears every profile and route, including live sessions, without a slug", () => {
const sessions = createSessions();
const liveSession = createFakeSession();
const all = getPaseoBrowserProfileSessions(sessions, directories, {
hostPartitions: [hostPartition],
hostPartitions: [hostWork],
liveSessions: [liveSession],
});
expect(all).toContain(liveSession);
expect(sessions.fromPartition.mock.calls.map(([p]) => p)).toEqual([
expect(openedPartitions(sessions)).toEqual([
PASEO_BROWSER_PROFILE_PARTITION,
"persist:paseo-profile-work",
"persist:paseo-profile-customer",
"persist:paseo-browser-11111111-1111-4111-8111-111111111111",
hostPartition,
`persist:${legacy}`,
hostDefault,
otherHostWork,
hostCustomer,
hostWork,
]);
});
it("opens nothing for an invalid slug", () => {
const sessions = createSessions();
expect(getPaseoBrowserProfileSessions(sessions, directories, { slug: "Not Valid" })).toEqual(
[],
);
expect(sessions.fromPartition).not.toHaveBeenCalled();
});
it("reads host proxy and legacy browser IDs safely", () => {
expect(getPaseoBrowserProfileSession({ fromPartition: (p) => ({ p }) as never })).toEqual({
p: PASEO_BROWSER_PROFILE_PARTITION,
@@ -220,30 +262,30 @@ describe("clearPaseoBrowserProfile", () => {
});
describe("partition directory discovery", () => {
it("lists partition directories and host proxy partitions on disk", async () => {
it("lists partition directories and prunes orphaned profiles on every route", async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), "paseo-partitions-list-"));
try {
expect(await listBrowserPartitionDirectories(directory)).toEqual([]);
expect(listDiskHostBrowserProxyPartitions(directory)).toEqual([]);
const hostDir = getHostBrowserProxyPartition("remote-a").slice("persist:".length);
for (const name of ["paseo-profile-work", hostDir, "unrelated"]) {
const hostDefaultDir = directoryOf(getHostBrowserProxyPartition("remote-a"));
const hostWorkDir = directoryOf(getHostBrowserProxyPartition("remote-a", "work"));
const hostOrphanDir = directoryOf(getHostBrowserProxyPartition("remote-a", "orphaned"));
for (const name of [
"paseo-profile-work",
"paseo-profile-orphaned",
hostDefaultDir,
hostWorkDir,
hostOrphanDir,
"unrelated",
]) {
await mkdir(path.join(directory, "Partitions", name), { recursive: true });
}
await writeFile(path.join(directory, "Partitions", "paseo-profile-file"), "");
expect((await listBrowserPartitionDirectories(directory)).sort()).toEqual(
["paseo-profile-work", hostDir, "unrelated"].sort(),
);
expect(listDiskHostBrowserProxyPartitions(directory)).toEqual([`persist:${hostDir}`]);
await mkdir(path.join(directory, "Partitions", "paseo-profile-orphaned"), {
recursive: true,
});
const pruned = await pruneOrphanedBrowserProfilePartitions(directory, new Set(["work"]));
expect(pruned).toEqual(["orphaned"]);
expect((await listBrowserPartitionDirectories(directory)).sort()).toEqual(
["paseo-profile-work", hostDir, "unrelated"].sort(),
["paseo-profile-work", hostDefaultDir, hostWorkDir, "unrelated"].sort(),
);
} finally {
await rm(directory, { recursive: true, force: true });
+69 -102
View File
@@ -1,13 +1,12 @@
import { readdir, rm } from "node:fs/promises";
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";
export const PASEO_BROWSER_NAMED_PROFILE_PREFIX = "paseo-profile-";
DEFAULT_BROWSER_PROFILE_SLUG,
getBrowserPartition,
isNamedBrowserProfileSlug,
PASEO_BROWSER_PROFILE_PARTITION,
parseBrowserPartition,
} from "./browser-partition.js";
export const BROWSER_PROFILE_COLORS = [
"violet",
@@ -24,42 +23,15 @@ export const BROWSER_PROFILE_COLORS = [
export type BrowserProfileColor = (typeof BROWSER_PROFILE_COLORS)[number];
const NAMED_SLUG = /^(?=.{1,48}$)[a-z0-9]+(?:-[a-z0-9]+)*$/;
const LEGACY_PREFIX = "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}$/;
export function isNamedBrowserProfileSlug(slug: string): boolean {
return NAMED_SLUG.test(slug) && slug !== "default";
}
export function getBrowserProfilePartition(slug: string): string {
if (slug === "default") {
return PASEO_BROWSER_PROFILE_PARTITION;
}
if (!isNamedBrowserProfileSlug(slug)) {
throw new Error(`Invalid browser profile slug: ${slug}`);
}
return `persist:${PASEO_BROWSER_NAMED_PROFILE_PREFIX}${slug}`;
}
export function isNamedProfileDirectory(name: string): boolean {
return (
name.startsWith(PASEO_BROWSER_NAMED_PROFILE_PREFIX) &&
isNamedBrowserProfileSlug(name.slice(PASEO_BROWSER_NAMED_PROFILE_PREFIX.length))
);
}
export function isPaseoBrowserProfilePartition(partition: unknown): partition is string {
return (
partition === PASEO_BROWSER_PROFILE_PARTITION ||
(typeof partition === "string" &&
partition.startsWith("persist:") &&
isNamedProfileDirectory(partition.slice("persist:".length)))
);
/** The profile a partition directory under `<userData>/Partitions` belongs to, on any route. */
function readDirectoryProfileSlug(name: string): string | null {
return parseBrowserPartition(`persist:${name}`)?.profileSlug ?? null;
}
export async function listBrowserPartitionDirectories(userData: string): Promise<string[]> {
@@ -72,19 +44,20 @@ export async function listBrowserPartitionDirectories(userData: string): Promise
}
}
export async function deleteBrowserProfilePartitionDirectory(
/** Deletes a named profile's partition directories on the local route and every host route. */
export async function deleteBrowserProfilePartitionDirectories(
userData: string,
slug: string,
): Promise<void> {
if (!isNamedBrowserProfileSlug(slug)) {
throw new Error(`Cannot delete browser profile partition for slug: ${slug}`);
throw new Error(`Cannot delete browser profile partitions for slug: ${slug}`);
}
const partitionDir = path.join(
userData,
"Partitions",
`${PASEO_BROWSER_NAMED_PROFILE_PREFIX}${slug}`,
const directories = await listBrowserPartitionDirectories(userData);
await Promise.all(
directories
.filter((name) => readDirectoryProfileSlug(name) === slug)
.map((name) => rm(path.join(userData, "Partitions", name), { recursive: true, force: true })),
);
await rm(partitionDir, { recursive: true, force: true });
}
export async function pruneOrphanedBrowserProfilePartitions(
@@ -92,15 +65,17 @@ export async function pruneOrphanedBrowserProfilePartitions(
activeSlugs: ReadonlySet<string>,
): Promise<string[]> {
const directories = await listBrowserPartitionDirectories(userData);
const removed: string[] = [];
const orphanedSlugs = new Set<string>();
for (const name of directories) {
if (!isNamedProfileDirectory(name)) continue;
const slug = name.slice(PASEO_BROWSER_NAMED_PROFILE_PREFIX.length);
if (activeSlugs.has(slug)) continue;
await deleteBrowserProfilePartitionDirectory(userData, slug);
removed.push(slug);
const slug = readDirectoryProfileSlug(name);
if (slug && isNamedBrowserProfileSlug(slug) && !activeSlugs.has(slug)) {
orphanedSlugs.add(slug);
}
}
return removed;
for (const slug of orphanedSlugs) {
await deleteBrowserProfilePartitionDirectories(userData, slug);
}
return [...orphanedSlugs];
}
const PASEO_BROWSER_STORAGE_TYPES = [
@@ -133,10 +108,10 @@ interface BrowserProfileWebContents extends BrowserProfileGuest {
getType(): string;
}
interface ListBrowserProfileGuestsInput {
interface ListBrowserProfileGuestsInput<W extends BrowserProfileWebContents> {
profileSession?: object;
profileSessions?: Iterable<object>;
webContents: BrowserProfileWebContents[];
webContents: W[];
}
interface ClearBrowserProfileInput {
@@ -180,6 +155,7 @@ export function readLegacyPaseoBrowserIds(input: unknown): string[] {
return [...browserIds];
}
/** Default-profile host partitions for renderer-supplied host server ids. */
export function readHostBrowserProxyPartitions(input: unknown): string[] {
if (!Array.isArray(input)) {
return [];
@@ -190,7 +166,9 @@ export function readHostBrowserProxyPartitions(input: unknown): string[] {
const trimmed = value.trim();
if (!trimmed) continue;
partitions.add(
isHostBrowserProxyPartition(trimmed) ? trimmed : getHostBrowserProxyPartition(trimmed),
parseBrowserPartition(trimmed)?.route === "host"
? trimmed
: getBrowserPartition({ kind: "host", serverId: trimmed }, DEFAULT_BROWSER_PROFILE_SLUG),
);
if (partitions.size >= MAX_HOST_BROWSER_PROFILES) {
break;
@@ -199,22 +177,12 @@ export function readHostBrowserProxyPartitions(input: unknown): string[] {
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 [];
}
}
/**
* Sessions that hold a profile's data on every route. With a slug, only that profile
* (Default also owns legacy per-tab partitions). Without a slug, every Paseo profile.
* Host partitions come from disk directories and from `hostPartitions`, the ones
* this process bound to a host proxy.
*/
export function getPaseoBrowserProfileSessions<S extends BrowserProfileSession>(
sessions: { fromPartition(partition: string): S },
directories: readonly string[],
@@ -224,43 +192,42 @@ export function getPaseoBrowserProfileSessions<S extends BrowserProfileSession>(
slug?: string;
} = {},
): S[] {
if (options.slug && options.slug !== "default") {
if (!isNamedBrowserProfileSlug(options.slug)) {
return [];
}
return [sessions.fromPartition(getBrowserProfilePartition(options.slug))];
}
const result = new Set<S>([sessions.fromPartition(PASEO_BROWSER_PROFILE_PARTITION)]);
if (options.slug === "default") {
// Clearing Default also sweeps legacy per-tab partitions and remote host-proxy partitions.
for (const name of directories) {
if (isLegacyDirectory(name)) {
result.add(sessions.fromPartition(`persist:${name}`));
}
}
for (const partition of options.hostPartitions ?? []) {
if (isHostBrowserProxyPartition(partition)) {
result.add(sessions.fromPartition(partition));
}
}
return [...result];
const { slug } = options;
if (
slug !== undefined &&
slug !== DEFAULT_BROWSER_PROFILE_SLUG &&
!isNamedBrowserProfileSlug(slug)
) {
return [];
}
const includes = (profileSlug: string) => slug === undefined || profileSlug === slug;
const partitions = new Set<string>([
getBrowserPartition({ kind: "local" }, slug ?? DEFAULT_BROWSER_PROFILE_SLUG),
]);
for (const name of directories) {
if (isNamedProfileDirectory(name) || isLegacyDirectory(name)) {
result.add(sessions.fromPartition(`persist:${name}`));
const profileSlug = readDirectoryProfileSlug(name);
if (
profileSlug !== null
? includes(profileSlug)
: isLegacyDirectory(name) && includes(DEFAULT_BROWSER_PROFILE_SLUG)
) {
partitions.add(`persist:${name}`);
}
}
for (const partition of options.hostPartitions ?? []) {
if (isHostBrowserProxyPartition(partition)) {
result.add(sessions.fromPartition(partition));
const parsed = parseBrowserPartition(partition);
if (parsed?.route === "host" && includes(parsed.profileSlug)) {
partitions.add(partition);
}
}
// A newly created profile's directory may not exist yet while its guest is live.
for (const live of options.liveSessions ?? []) {
result.add(live);
const result = new Set<S>([...partitions].map((partition) => sessions.fromPartition(partition)));
if (slug === undefined) {
// A newly created profile's directory may not exist yet while its guest is live.
for (const live of options.liveSessions ?? []) {
result.add(live);
}
}
return [...result];
}
@@ -276,9 +243,9 @@ export function getLegacyPaseoBrowserProfileSession(
: null;
}
export function listPaseoBrowserProfileGuests(
input: ListBrowserProfileGuestsInput,
): BrowserProfileGuest[] {
export function listPaseoBrowserProfileGuests<W extends BrowserProfileWebContents>(
input: ListBrowserProfileGuestsInput<W>,
): W[] {
const allowedSessions = new Set<object>(input.profileSessions ?? []);
if (input.profileSession) {
allowedSessions.add(input.profileSession);
@@ -1,11 +1,6 @@
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,
@@ -20,10 +15,7 @@ import {
export {
createBrowserProxyManager,
getHostBrowserProxyPartition,
isHostBrowserProxyPartition,
parseBrowserProxyTarget,
PASEO_BROWSER_HOST_PARTITION_PREFIX,
type BrowserProxyManager,
type BrowserProxyStatus,
type BrowserProxyStatusSnapshot,
@@ -125,9 +117,13 @@ export function createElectronBrowserProxyController(deps: {
if (!target) {
throw new Error("Invalid browser proxy target");
}
if (rawInput.profileSlug !== undefined && typeof rawInput.profileSlug !== "string") {
throw new Error("Invalid browser proxy profile");
}
return await manager.ensureHostProxy({
serverId: rawInput.serverId,
target,
...(rawInput.profileSlug !== undefined ? { profileSlug: rawInput.profileSlug } : {}),
forceReconnect: rawInput.forceReconnect === true,
});
});
@@ -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);
}
@@ -6,7 +6,7 @@ import {
type DecodedNetworkTunnelFrame,
type NetworkTunnelFrame,
} from "@getpaseo/protocol/network-tunnel";
import { getHostBrowserProxyPartition } from "./partition.js";
import { getBrowserPartition } from "../../browser-partition.js";
import {
createBrowserProxyManager,
type BrowserProxyManager,
@@ -204,10 +204,13 @@ describe("BrowserProxyManager", () => {
const target = "tcp://10.0.0.5:6767";
const ready = await manager.ensureHostProxy({ serverId: "remote-1", target });
const expectedPartition = getHostBrowserProxyPartition("remote-1");
const expectedPartition = getBrowserPartition(
{ kind: "host", serverId: "remote-1" },
"default",
);
expect(ready.status).toBe("ready");
expect(ready.partition).toBe(expectedPartition);
expect(ready.profilePartitions).toEqual({ default: expectedPartition });
expect(ready.socksPort).toBeGreaterThan(0);
expect(manager.isAllowedHostPartition(expectedPartition)).toBe(true);
expect(manager.isProxiedSession(sessionsByPartition.get(expectedPartition)!)).toBe(true);
@@ -304,7 +307,12 @@ describe("BrowserProxyManager", () => {
expect(result.status).toBe("error");
expect(result.socksPort).toBeNull();
expect(result.error).toMatch(/resolveProxy|proxy/i);
expect(manager.isAllowedHostPartition(result.partition)).toBe(false);
expect(result.profilePartitions).toEqual({});
expect(
manager.isAllowedHostPartition(
getBrowserPartition({ kind: "host", serverId: "remote-broken-proxy" }, "default"),
),
).toBe(false);
});
test("keeps socksPort null on initial tunnel failure, and preserves socksPort across later reconnect errors", async () => {
@@ -335,7 +343,7 @@ describe("BrowserProxyManager", () => {
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);
expect(initialFail.profilePartitions).toEqual({});
failTicket = false;
const ready = await manager.ensureHostProxy({ serverId: "remote-flaky", target });
@@ -362,4 +370,85 @@ describe("BrowserProxyManager", () => {
expect(recovered.status).toBe("ready");
expect(recovered.socksPort).toBe(ready.socksPort);
});
test("binds every profile session on a host to the same SOCKS5 port and tunnel", async () => {
const sessionsByPartition = new Map<string, ReturnType<typeof createFakeSession>>();
const wires: Array<ReturnType<typeof createEchoTunnelWire>> = [];
const statuses: BrowserProxyStatusSnapshot[] = [];
const manager = createBrowserProxyManager({
verifySocketOwner: async () => true,
requestTicket: async () => "ticket",
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 route = { kind: "host", serverId: "remote-profiles" } as const;
const defaultPartition = getBrowserPartition(route, "default");
const workPartition = getBrowserPartition(route, "work");
const target = "tcp://10.0.0.20:6767";
const [first, second] = await Promise.all([
manager.ensureHostProxy({ serverId: "remote-profiles", target }),
manager.ensureHostProxy({ serverId: "remote-profiles", target, profileSlug: "work" }),
]);
expect(first.socksPort).toBeGreaterThan(0);
expect(second.socksPort).toBe(first.socksPort);
expect(second.profilePartitions).toEqual({ default: defaultPartition, work: workPartition });
expect(manager.getHostProxyStatus("remote-profiles")?.profilePartitions).toEqual({
default: defaultPartition,
work: workPartition,
});
expect(statuses.at(-1)?.profilePartitions).toEqual({
default: defaultPartition,
work: workPartition,
});
for (const partition of [defaultPartition, workPartition]) {
const session = sessionsByPartition.get(partition)!;
expect(session.lastProxyConfig?.proxyRules).toBe(`socks5://127.0.0.1:${first.socksPort}`);
expect(manager.isAllowedHostPartition(partition)).toBe(true);
expect(manager.isProxiedSession(session)).toBe(true);
}
expect(manager.listKnownPartitions().sort()).toEqual([defaultPartition, workPartition].sort());
expect(wires).toHaveLength(1);
const reply = await socks5ConnectAndExchange(first.socksPort!, "localhost", 5173, "work");
expect(reply).toBe("ECHO:work");
expect(wires).toHaveLength(1);
await manager.releaseHostProxy("remote-profiles");
expect(manager.isAllowedHostPartition(defaultPartition)).toBe(false);
expect(manager.isAllowedHostPartition(workPartition)).toBe(false);
});
test("refuses to bind an invalid profile slug", async () => {
const manager = createBrowserProxyManager({
verifySocketOwner: async () => true,
requestTicket: async () => "ticket",
openTunnelWire: async () => createEchoTunnelWire().wire,
getSessionForPartition: () => createFakeSession(),
});
managers.push(manager);
await expect(
manager.ensureHostProxy({
serverId: "remote-invalid",
target: "tcp://10.0.0.21:6767",
profileSlug: "Not Valid",
}),
).rejects.toThrow(/profile/i);
});
});
@@ -1,5 +1,9 @@
import net, { type AddressInfo, type Server, type Socket } from "node:net";
import { getHostBrowserProxyPartition, isHostBrowserProxyPartition } from "./partition.js";
import {
DEFAULT_BROWSER_PROFILE_SLUG,
getBrowserPartition,
parseBrowserPartition,
} from "../../browser-partition.js";
import { createOsSocketOwnerVerifier, type SocketOwnerVerifier } from "./socket-owner.js";
import {
performSocks5Handshake,
@@ -17,7 +21,8 @@ export type BrowserProxyStatus = "idle" | "connecting" | "ready" | "reconnecting
export interface BrowserProxyStatusSnapshot {
serverId: string;
partition: string;
/** Profile slug -> partition, for every profile session bound and verified on this host. */
profilePartitions: Record<string, string>;
status: BrowserProxyStatus;
error: string | null;
socksPort: number | null;
@@ -51,6 +56,8 @@ export interface BrowserProxyManagerDeps {
export interface EnsureHostProxyInput {
serverId: string;
target: HostTransportSpec;
/** The browser profile whose session to bind to the host proxy. Defaults to `default`. */
profileSlug?: string;
forceReconnect?: boolean;
}
@@ -65,19 +72,23 @@ export interface BrowserProxyManager {
disposeAll(): Promise<void>;
}
/**
* One host route: one loopback SOCKS5 server and one tunnel. Every profile session
* on the host points `setProxy` at the same SOCKS5 port.
*/
interface HostProxyEntry {
readonly serverId: string;
readonly partition: string;
target: HostTransportSpec;
status: BrowserProxyStatus;
error: string | null;
socksServer: Server | null;
socksPort: number | null;
session: BrowserProxySessionLike | null;
sessionConfigured: boolean;
/** Profile slug -> partition whose session is bound and verified. */
boundPartitions: Map<string, string>;
bindPromises: Map<string, Promise<void>>;
mux: TunnelMuxClient | null;
connectPromise: Promise<TunnelMuxClient> | null;
ensurePromise: Promise<BrowserProxyStatusSnapshot> | null;
routePromise: Promise<number> | null;
activeSockets: Set<Socket>;
disposed: boolean;
}
@@ -110,15 +121,19 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
function snapshotOf(entry: HostProxyEntry): BrowserProxyStatusSnapshot {
return {
serverId: entry.serverId,
partition: entry.partition,
profilePartitions: Object.fromEntries(entry.boundPartitions),
status: entry.status,
error: entry.error,
// Only expose socksPort once Chromium's session proxy has been configured and
// Only expose socksPort once a Chromium session proxy has been configured and
// verified via resolveProxy so renderers never mount an unverified partition.
socksPort: entry.sessionConfigured ? entry.socksPort : null,
socksPort: hasBoundSession(entry) ? entry.socksPort : null,
};
}
function hasBoundSession(entry: HostProxyEntry): boolean {
return entry.boundPartitions.size > 0;
}
function setEntryStatus(
entry: HostProxyEntry,
status: BrowserProxyStatus,
@@ -167,12 +182,44 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
return address.port;
}
async function ensureSessionConfigured(entry: HostProxyEntry, socksPort: number): Promise<void> {
if (entry.sessionConfigured && entry.session) {
async function bindSession(
entry: HostProxyEntry,
profileSlug: string,
partition: string,
socksPort: number,
): Promise<void> {
if (entry.boundPartitions.has(profileSlug)) {
return;
}
let bindTask = entry.bindPromises.get(profileSlug);
if (!bindTask) {
bindTask = (async () => {
const session = await configureSession(partition, socksPort);
if (entry.disposed) {
throw new Error("Host browser proxy was disposed");
}
entry.boundPartitions.set(profileSlug, partition);
allowedPartitions.add(partition);
proxiedSessions.add(session);
deps.onStatusChange?.(snapshotOf(entry));
})();
entry.bindPromises.set(profileSlug, bindTask);
const settled = () => {
if (entry.bindPromises.get(profileSlug) === bindTask) {
entry.bindPromises.delete(profileSlug);
}
};
bindTask.then(settled, settled);
}
await bindTask;
}
const hostSession = deps.getSessionForPartition(entry.partition);
async function configureSession(
partition: string,
socksPort: number,
): Promise<BrowserProxySessionLike> {
knownPartitions.add(partition);
const hostSession = deps.getSessionForPartition(partition);
await hostSession.setProxy({
mode: "fixed_servers",
proxyRules: `socks5://127.0.0.1:${socksPort}`,
@@ -194,12 +241,26 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
`Session resolveProxy verification failed (localhost="${resolvedLocalhost}", 127.0.0.1="${resolvedLoopbackIp}")`,
);
}
return hostSession;
}
entry.session = hostSession;
entry.sessionConfigured = true;
allowedPartitions.add(entry.partition);
knownPartitions.add(entry.partition);
proxiedSessions.add(hostSession);
/** The host route: its fixed SOCKS5 port and a connected tunnel, shared by every profile. */
async function ensureRoute(entry: HostProxyEntry): Promise<number> {
if (!entry.routePromise) {
const routeTask = (async () => {
const socksPort = await ensureSocksServer(entry);
await ensureTunnelConnected(entry);
return socksPort;
})();
entry.routePromise = routeTask;
const settled = () => {
if (entry.routePromise === routeTask) {
entry.routePromise = null;
}
};
routeTask.then(settled, settled);
}
return await entry.routePromise;
}
async function ensureTunnelConnected(entry: HostProxyEntry): Promise<TunnelMuxClient> {
@@ -214,7 +275,7 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
}
const nextStatus: BrowserProxyStatus =
entry.sessionConfigured || entry.status === "ready" || entry.status === "reconnecting"
hasBoundSession(entry) || entry.status === "ready" || entry.status === "reconnecting"
? "reconnecting"
: "connecting";
setEntryStatus(entry, nextStatus, null);
@@ -238,13 +299,13 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
mux.onClose(() => {
if (entry.mux === mux) {
entry.mux = null;
if (!entry.disposed && entry.sessionConfigured) {
if (!entry.disposed && hasBoundSession(entry)) {
setEntryStatus(entry, "reconnecting", null);
}
}
});
if (entry.sessionConfigured) {
if (hasBoundSession(entry)) {
setEntryStatus(entry, "ready", null);
}
return mux;
@@ -358,21 +419,18 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
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,
boundPartitions: new Map(),
bindPromises: new Map(),
mux: null,
connectPromise: null,
ensurePromise: null,
routePromise: null,
activeSockets: new Set(),
disposed: false,
};
@@ -385,6 +443,8 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
if (!serverId) {
throw new Error("Host serverId is required");
}
const profileSlug = input.profileSlug ?? DEFAULT_BROWSER_PROFILE_SLUG;
const partition = getBrowserPartition({ kind: "host", serverId }, profileSlug);
const entry = getOrCreateEntry(serverId, input.target);
if (input.forceReconnect && entry.mux) {
@@ -392,37 +452,19 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
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;
if (entry.status !== "ready") {
setEntryStatus(entry, hasBoundSession(entry) ? "reconnecting" : "connecting", null);
}
const socksPort = await ensureRoute(entry);
await bindSession(entry, profileSlug, partition, socksPort);
setEntryStatus(entry, "ready", null);
} catch (error) {
if (!entry.disposed) {
setEntryStatus(entry, "error", formatError(error));
}
}
return snapshotOf(entry);
}
function updateHostProxyTarget(input: { serverId: string; target: HostTransportSpec }): void {
@@ -432,7 +474,7 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
entry.target = input.target;
entry.mux?.close();
entry.mux = null;
if (entry.sessionConfigured) {
if (hasBoundSession(entry)) {
setEntryStatus(entry, "reconnecting", null);
}
}
@@ -444,7 +486,7 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
}
function isAllowedHostPartition(partition: string): boolean {
return isHostBrowserProxyPartition(partition) && allowedPartitions.has(partition);
return parseBrowserPartition(partition)?.route === "host" && allowedPartitions.has(partition);
}
function isProxiedSession(session: object): boolean {
@@ -459,7 +501,9 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
if (entry.disposed) return;
entry.disposed = true;
entriesByServerId.delete(entry.serverId);
allowedPartitions.delete(entry.partition);
for (const partition of entry.boundPartitions.values()) {
allowedPartitions.delete(partition);
}
entry.mux?.close();
entry.mux = null;
@@ -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 { getBrowserPartition, PASEO_BROWSER_PROFILE_PARTITION } from "../browser-partition.js";
import {
getPaseoBrowserIdForWebContents,
getPaseoBrowserWorkspaceId,
@@ -11,6 +10,10 @@ import {
unregisterPaseoBrowserFromHost,
} from "./index.js";
function hostPartitionFor(serverId: string, profileSlug = "default"): string {
return getBrowserPartition({ kind: "host", serverId }, profileSlug);
}
class FakeRenderer {
public constructor(public readonly id: number) {}
@@ -46,8 +49,8 @@ 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 hostPartition = hostPartitionFor("remote-host-a");
const unregisteredHostPartition = hostPartitionFor("remote-host-b");
const isAllowedHostPartition = (partition: string) => partition === hostPartition;
expect(
@@ -88,7 +91,7 @@ describe("browser webview attachment", () => {
});
test("registers a guest attached to an allowed host proxy session", () => {
const hostPartition = getHostBrowserProxyPartition("remote-host-a");
const hostPartition = hostPartitionFor("remote-host-a");
const proxiedSession = {};
const renderer = new FakeRenderer(9);
const guest = new FakeBrowserGuest(901, renderer, proxiedSession);
@@ -109,6 +112,53 @@ describe("browser webview attachment", () => {
unregisterPaseoBrowser("browser-proxied");
});
test("admits a host-proxied named profile only once its session is bound to the host proxy", () => {
const boundWork = hostPartitionFor("remote-host-a", "work");
const unboundWork = hostPartitionFor("remote-host-b", "work");
const isAllowedHostPartition = (partition: string) => partition === boundWork;
expect(
isPaseoBrowserWebviewAttach({
src: "http://localhost:3000",
partition: boundWork,
isAllowedHostPartition,
}),
).toBe(true);
expect(
isPaseoBrowserWebviewAttach({
src: "http://localhost:3000",
partition: unboundWork,
isAllowedHostPartition,
}),
).toBe(false);
expect(
isPaseoBrowserWebviewAttach({ src: "http://localhost:3000", partition: boundWork }),
).toBe(false);
});
test("registers a guest on a host-proxied named profile only when its session is proxied", () => {
const workPartition = hostPartitionFor("remote-host-a", "work");
const proxiedSession = {};
const renderer = new FakeRenderer(10);
const guest = new FakeBrowserGuest(1001, renderer, proxiedSession);
const register = (isAllowedHostSession: (session: object) => boolean) =>
registerAttachedPaseoBrowser({
browserId: "browser-proxied-work",
workspaceId: "workspace-remote",
webContentsId: guest.id,
sender: renderer,
partition: workPartition,
sessionFromPartition: (partition) => (partition === workPartition ? proxiedSession : {}),
isAllowedHostSession,
findWebContents: () => guest,
});
expect(register(() => false)).toBe(false);
expect(register((session) => session === proxiedSession)).toBe(true);
expect(getPaseoBrowserIdForWebContents(guest)).toBe("browser-proxied-work");
unregisterPaseoBrowser("browser-proxied-work");
});
test("admits only complete lowercase named profile partitions on allowed URLs", () => {
const valid = "persist:paseo-profile-work";
for (const partition of [valid, `persist:paseo-profile-${"a".repeat(48)}`]) {
@@ -1,6 +1,5 @@
import { webContents as allWebContents, type WebContents } from "electron";
import { isPaseoBrowserProfilePartition } from "../browser-profile.js";
import { isHostBrowserProxyPartition } from "../browser-proxy/partition.js";
import { parseBrowserPartition } from "../browser-partition.js";
import {
BROWSER_NEW_TAB_REQUEST_EVENT,
buildBrowserPopupWebPreferences,
@@ -52,13 +51,12 @@ export function isPaseoBrowserWebviewAttach(input: {
if (!isAllowedBrowserWebviewUrl(input.src)) {
return false;
}
if (isPaseoBrowserProfilePartition(input.partition)) {
return true;
const parsed = parseBrowserPartition(input.partition);
if (!parsed || !input.partition) {
return false;
}
return (
isHostBrowserProxyPartition(input.partition) &&
(input.isAllowedHostPartition?.(input.partition) ?? false)
);
// A host-routed partition attaches only once main bound its session to the host proxy.
return parsed.route === "local" || (input.isAllowedHostPartition?.(input.partition) ?? false);
}
export function listRegisteredPaseoBrowserIds(): string[] {
@@ -83,14 +81,11 @@ export function registerAttachedPaseoBrowser(input: RegisterAttachedBrowserInput
if (!guest || guest.isDestroyed() || guest.hostWebContents !== input.sender) {
return false;
}
const sessionMatchesProfile =
isPaseoBrowserProfilePartition(input.partition) &&
guest.session === input.sessionFromPartition(input.partition);
const sessionMatchesHostProxy =
isHostBrowserProxyPartition(input.partition) &&
guest.session === input.sessionFromPartition(input.partition) &&
(input.isAllowedHostSession?.(guest.session) ?? false);
if (!sessionMatchesProfile && !sessionMatchesHostProxy) {
const parsed = parseBrowserPartition(input.partition);
if (!parsed || guest.session !== input.sessionFromPartition(input.partition)) {
return false;
}
if (parsed.route === "host" && !(input.isAllowedHostSession?.(guest.session) ?? false)) {
return false;
}
+20 -24
View File
@@ -79,16 +79,13 @@ import {
setWorkspaceActivePaseoBrowserId,
unregisterPaseoBrowserHost,
} from "./features/browser-webviews/index.js";
import { isNamedBrowserProfileSlug, parseBrowserPartition } from "./features/browser-partition.js";
import {
clearPaseoBrowserProfile,
deleteBrowserProfilePartitionDirectory,
getBrowserProfilePartition,
deleteBrowserProfilePartitionDirectories,
getLegacyPaseoBrowserProfileSession,
getPaseoBrowserProfileSessions,
isNamedBrowserProfileSlug,
isPaseoBrowserProfilePartition,
listBrowserPartitionDirectories,
listDiskHostBrowserProxyPartitions,
listPaseoBrowserProfileGuests,
pruneOrphanedBrowserProfilePartitions,
readHostBrowserProxyPartitions,
@@ -97,7 +94,6 @@ import {
import {
applyProxiedWebContentsPolicy,
createElectronBrowserProxyController,
isHostBrowserProxyPartition,
} from "./features/browser-proxy/index.js";
import { parseOpenProjectPathFromArgv } from "./open-project-routing.js";
import {
@@ -172,10 +168,7 @@ function readAttachedBrowserInput(input: unknown): AttachedBrowserInput | null {
}
const record = input as Record<string, unknown>;
const partition = record.partition;
if (
typeof partition !== "string" ||
(!isPaseoBrowserProfilePartition(partition) && !isHostBrowserProxyPartition(partition))
) {
if (typeof partition !== "string" || parseBrowserPartition(partition) === null) {
return null;
}
if (typeof record.browserId !== "string" || record.browserId.trim().length === 0) {
@@ -436,16 +429,17 @@ ipcMain.handle("paseo:browser:remove-profile", async (_event, input: unknown) =>
if (!removed.ok) {
return removed;
}
const partition = getBrowserProfilePartition(slug);
const profileSession = session.fromPartition(partition);
const openGuests = webContents
.getAllWebContents()
.filter(
(contents) =>
!contents.isDestroyed() &&
(contents.getType() === "webview" || contents.getType() === "window") &&
contents.session === profileSession,
);
const userData = app.getPath("userData");
// The profile's sessions on the local route and on every host route.
const profileSessions = getPaseoBrowserProfileSessions(
session,
await listBrowserPartitionDirectories(userData),
{ slug, hostPartitions: browserProxy.manager.listKnownPartitions() },
);
const openGuests = listPaseoBrowserProfileGuests({
profileSessions,
webContents: webContents.getAllWebContents(),
});
for (const guest of openGuests) {
getPaseoBrowserWebviewRegistry().unregisterWebContents(guest.id);
try {
@@ -460,11 +454,13 @@ ipcMain.handle("paseo:browser:remove-profile", async (_event, input: unknown) =>
}
try {
await clearPaseoBrowserProfile({
profileSessions: [profileSession],
profileSessions,
listGuests: () => [],
logReloadError: () => {},
});
profileSession.flushStorageData();
for (const profileSession of profileSessions) {
profileSession.flushStorageData();
}
} catch (error) {
log.warn("[browser-profile] failed to clear session before deleting partition", {
slug,
@@ -472,7 +468,7 @@ ipcMain.handle("paseo:browser:remove-profile", async (_event, input: unknown) =>
});
}
try {
await deleteBrowserProfilePartitionDirectory(app.getPath("userData"), slug);
await deleteBrowserProfilePartitionDirectories(userData, slug);
} catch (error) {
log.warn("[browser-profile] failed to delete profile partition directory", {
slug,
@@ -619,10 +615,10 @@ ipcMain.handle("paseo:browser:clear-profile", async (_event, rawInput?: unknown)
(browserId) => `paseo-browser-${browserId}`,
);
const allDirectories = [...new Set([...directories, ...legacyDirectories])];
// Host partitions on disk arrive through `directories`.
const hostPartitions = [
...browserProxy.manager.listKnownPartitions(),
...readHostBrowserProxyPartitions(options?.hostServerIds),
...listDiskHostBrowserProxyPartitions(app.getPath("userData")),
];
const liveSessions = webContents
.getAllWebContents()
+1 -1
View File
@@ -3,7 +3,7 @@ import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import ts from "typescript";
import { describe, expect, it } from "vitest";
import { PASEO_BROWSER_PROFILE_PARTITION } from "./features/browser-profile.js";
import { PASEO_BROWSER_PROFILE_PARTITION } from "./features/browser-partition.js";
// The preload runs inside Electron's sandbox and is tsc-compiled (not bundled), so at
// runtime it may only load Electron's sandbox allowlist. Any other module (local or
+1
View File
@@ -150,6 +150,7 @@ contextBridge.exposeInMainWorld("paseoDesktop", {
ensureHostProxy: (input: {
serverId: string;
target: HostTransportSpec;
profileSlug?: string;
forceReconnect?: boolean;
}) =>
ipcRenderer.invoke(