Privileged helper for system proxy (#796)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Gregory SchierandClaude Opus 5.5 authored and GitHub committed 2026-10-30 00:41:00 -07:00
1 parent 4d38a482f6
commit f7aea62c07
33 files changed
+3536 -176

No files matched your search

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

@@ -0,0 +1,96 @@
import { useQueryClient } from "@tanstack/react-query";
import type { SystemProxyStatus } from "@yaakapp-internal/proxy-lib";
import { Banner, Dialog, DialogFooter, LoadingIcon } from "@yaakapp-internal/ui";
import { useAtom, useSetAtom } from "jotai";
import { useEffect } from "react";
import loginItems from "../assets/login-items.png";
import { useRpcMutation } from "../hooks/useRpcMutation";
import { useRpcQuery } from "../hooks/useRpcQuery";
import { helperDialogOpenAtom, helperRegisteredAtAtom } from "../lib/atoms";
/** Yaak Proxy's row in `login-items.png`, as percentages of the image, for the highlight */
const YAAK_PROXY_ROW = { left: 1, top: 34, width: 98, height: 32 };
/**
* Walks through allowing the helper: registering it opens System Settings, where the user turns
* it on. Stays open while macOS awaits that approval, and closes itself once it is given.
*/
export function HelperDialog() {
const [open, setOpen] = useAtom(helperDialogOpenAtom);
const queryClient = useQueryClient();
const setRegisteredAt = useSetAtom(helperRegisteredAtAtom);
// Polled by the header while approval is pending, so this sees it as soon as it is given.
const status = useRpcQuery("system_proxy_status", {});
const register = useRpcMutation("helper_register", {
onSuccess: (status) => {
setRegisteredAt(Date.now());
queryClient.setQueryData<SystemProxyStatus>(["system_proxy_status", {}], status);
},
});
const helper = status.data?.helper;
const waiting = helper === "requires_approval";
const { reset } = register;
useEffect(() => {
if (open && helper === "enabled") {
setOpen(false);
reset();
}
}, [open, helper, setOpen, reset]);
const close = () => {
setOpen(false);
reset();
};
return (
<Dialog
open={open}
onClose={close}
size="dynamic"
title="Turn on Yaak Proxy under Allow in the Background"
description="In System Settings > General > Login Items. Newer macOS calls the list Background App Activity."
className="w-[34rem]"
>
<div className="grid gap-3 pb-4">
<div className="relative">
<img
src={loginItems}
alt="System Settings, with Yaak Proxy's toggle in the list of apps allowed in the background"
className="block w-full rounded-md border border-border-subtle"
/>
<div
aria-hidden
className="absolute rounded-md ring-2 ring-primary bg-primary/10 pointer-events-none"
style={{
left: `${YAAK_PROXY_ROW.left}%`,
top: `${YAAK_PROXY_ROW.top}%`,
width: `${YAAK_PROXY_ROW.width}%`,
height: `${YAAK_PROXY_ROW.height}%`,
}}
/>
</div>
{register.error != null && <Banner color="danger">{register.error.message}</Banner>}
</div>
<DialogFooter
leftSlot={
waiting && (
<span className="flex items-center gap-2 text-sm text-text-subtle">
<LoadingIcon size="xs" />
Waiting for approval
</span>
)
}
actions={[
{ label: waiting ? "Close" : "Cancel", onClick: close },
{
label: "Open System Settings",
color: "primary",
isLoading: register.isPending,
onClick: () => register.mutate({}),
},
]}
/>
</Dialog>
);
}
@@ -18,6 +18,7 @@ import { FirstRun } from "./FirstRun";
import { FlowDetail } from "./FlowDetail";
import { FlowList } from "./FlowList";
import { ProxyStatus } from "./ProxyStatus";
import { HelperDialog } from "./HelperDialog";
import { SaveDialog } from "./SaveDialog";
import { selectedSidebarLabelAtom, Sidebar } from "./Sidebar";
import { TakeOverBanner } from "./TakeOverBanner";
@@ -139,6 +140,7 @@ export function ProxyLayout() {
</div>
</SidebarLayout>
<SaveDialog />
<HelperDialog />
<Toasts />
</div>
);
+91 -4
View File
@@ -9,15 +9,22 @@ import {
Icon,
} from "@yaakapp-internal/ui";
import classNames from "classnames";
import { useAtomValue, useStore } from "jotai";
import { useAtomValue, useSetAtom, useStore } from "jotai";
import type { HTMLAttributes, ReactNode, Ref } from "react";
import { useRef } from "react";
import { useEffect, useRef } from "react";
import { useRpcEvent } from "../hooks/useRpcEvent";
import { useRpcMutation } from "../hooks/useRpcMutation";
import { useRpcQuery } from "../hooks/useRpcQuery";
import { helperDialogOpenAtom, helperRegisteredAtAtom } from "../lib/atoms";
import { environmentExports } from "../lib/env";
import { proxyStateAtom, refreshProxyState } from "../lib/store";
import { recordingLabel, systemProxySwitch } from "../lib/systemProxy";
import {
helperPollInterval,
helperRow,
recordingLabel,
systemProxySwitch,
} from "../lib/systemProxy";
import { onWindowFocus } from "../lib/tauri";
import { useShowToast } from "../lib/toast";
/**
@@ -34,6 +41,7 @@ export function ProxyStatus() {
const setAtLaunch = useSetSystemProxyAtLaunch();
const setHttpVersion = useSetHttpVersion();
const copyEnvironment = useCopyEnvironment();
const setHelperDialogOpen = useSetAtom(helperDialogOpenAtom);
const { caStatus, trust, systemProxy, setSystemProxy } = setup;
const systemSwitch = useSystemProxySwitch(setup);
@@ -131,6 +139,19 @@ export function ProxyStatus() {
</KeepMenuOpen>
),
},
{
type: "content",
hidden: systemProxy.data?.supported !== true,
label: systemProxy.data != null && (
<HelperMenuRow
status={systemProxy.data}
onOpenDialog={() => {
dropdownRef.current?.close?.();
setHelperDialogOpen(true);
}}
/>
),
},
{
type: "content",
label: caStatus.data?.trusted ? (
@@ -253,7 +274,19 @@ export function ProxyStatus() {
export function useProxySetup() {
const queryClient = useQueryClient();
const caStatus = useRpcQuery("ca_status", {});
const systemProxy = useRpcQuery("system_proxy_status", {});
const registeredAt = useAtomValue(helperRegisteredAtAtom);
const systemProxy = useRpcQuery(
"system_proxy_status",
{},
{
// The helper is approved in System Settings, out of the app's sight.
refetchInterval: (query) =>
helperPollInterval(query.state.data?.helper, registeredAt, Date.now()),
},
);
// The user comes back from System Settings, maybe having just allowed the helper.
const { refetch: refetchSystemProxy } = systemProxy;
useEffect(() => onWindowFocus(() => void refetchSystemProxy()), [refetchSystemProxy]);
const trust = useRpcMutation("ca_trust", {
mutationKey: ["ca_trust"],
onSuccess: (status) => queryClient.setQueryData<CaStatus>(["ca_status", {}], status),
@@ -279,9 +312,63 @@ export function useSystemProxySwitch(setup: ReturnType<typeof useProxySetup>) {
port: proxyState?.port ?? proxyState?.configuredPort ?? null,
pending: setSystemProxy.isPending ? (setSystemProxy.variables?.enabled ?? null) : null,
error: setSystemProxy.error?.message ?? null,
helper: systemProxy.data?.backend === "helper",
});
}
/** The privileged helper: whether it is installed and approved, and which way changes go */
function HelperMenuRow({
status,
onOpenDialog,
}: {
status: SystemProxyStatus;
onOpenDialog: () => void;
}) {
const queryClient = useQueryClient();
const unregister = useRpcMutation("helper_unregister", {
onSuccess: (status) =>
queryClient.setQueryData<SystemProxyStatus>(["system_proxy_status", {}], status),
});
const row = helperRow(status.helper, status.backend);
const error = unregister.error;
return (
<MenuRow
icon={
<Icon
icon={status.helper === "enabled" ? "badge_check" : "lock"}
size="sm"
color={status.helper === "enabled" ? "success" : "secondary"}
/>
}
title={row.title}
description={
error != null ? <span className="text-danger">{error.message}</span> : row.description
}
action={
row.action != null && (
<Button
size="2xs"
variant="border"
color={row.action === "unregister" ? "default" : "primary"}
isLoading={unregister.isPending}
onClick={(e) => {
e.stopPropagation();
if (row.action === "unregister") unregister.mutate({});
else onOpenDialog();
}}
>
{row.action === "install"
? "Install"
: row.action === "approve"
? "Approve"
: "Unregister"}
</Button>
)
}
/>
);
}
/** Saves whether the system proxy turns on as the app launches */
function useSetSystemProxyAtLaunch() {
const store = useStore();
+6
View File
@@ -14,5 +14,11 @@ export const selectedFlowIdAtom = atom((get) => get(selectedFlowAtom)?.id ?? nul
/** The list follows new traffic, rather than being held where it was scrolled or selected */
export const followingAtom = atom(true);
/** When the helper was last registered, so its state is read until approval shows */
export const helperRegisteredAtAtom = atom<number | null>(null);
/** The dialog that walks through allowing the helper in System Settings */
export const helperDialogOpenAtom = atom(false);
/** Stacked by default; the header's toggle switches to side by side */
export const flowLayoutAtom = atomWithStorage<SplitLayoutLayout>("flow_layout", "vertical");
+117 -1
View File
@@ -1,5 +1,12 @@
import type { HelperState } from "@yaakapp-internal/proxy-lib";
import { describe, expect, test } from "vite-plus/test";
import { recordingLabel, type SystemProxyState, systemProxySwitch } from "./systemProxy";
import {
helperPollInterval,
helperRow,
recordingLabel,
type SystemProxyState,
systemProxySwitch,
} from "./systemProxy";
const off: SystemProxyState = { routing: false, port: 9090, pending: null, error: null };
@@ -25,6 +32,14 @@ describe("systemProxySwitch", () => {
});
});
test("waits for no password when the helper makes the change", () => {
expect(systemProxySwitch({ ...off, pending: false, helper: true })).toEqual({
checked: false,
description: "Changing the system proxy",
failed: false,
});
});
test("snaps back on a cancelled prompt and says so", () => {
expect(systemProxySwitch({ ...off, error: "Cancelled in the password dialog" })).toEqual({
checked: false,
@@ -37,6 +52,107 @@ describe("systemProxySwitch", () => {
});
});
describe("helperRow", () => {
test("offers each next step, and says which way changes go", () => {
expect(helperRow("not_registered", "admin_prompt")).toMatchObject({
title: "Helper: not installed",
action: "install",
});
expect(helperRow("requires_approval", "admin_prompt")).toMatchObject({
title: "Helper: awaiting approval",
action: "approve",
});
const enabled = helperRow("enabled", "helper");
expect(enabled).toMatchObject({ title: "Helper: enabled", action: "unregister" });
expect(enabled.description).toMatch(/No password/);
});
test("says when the password prompt still has settings to put back", () => {
expect(helperRow("enabled", "admin_prompt").description).toMatch(/password prompt/);
});
test("offers to install when macOS can't find it, rather than blaming a dev build", () => {
expect(helperRow("not_found", "admin_prompt")).toMatchObject({
title: "Helper: not found by macOS",
action: "install",
});
});
test("keeps every row short", () => {
const states: HelperState[] = [
"unavailable",
"not_found",
"not_registered",
"requires_approval",
"enabled",
];
for (const state of states) {
for (const backend of ["helper", "admin_prompt"] as const) {
const row = helperRow(state, backend);
expect(row.title.length).toBeLessThanOrEqual(30);
expect(row.description.length).toBeLessThanOrEqual(60);
}
}
});
test("has a titled row for every state the backend sends", () => {
// A missing key here fails the typecheck, so a new state can't be left out.
const states: Record<HelperState, true> = {
unavailable: true,
not_found: true,
not_registered: true,
requires_approval: true,
enabled: true,
};
for (const state of Object.keys(states) as HelperState[]) {
for (const backend of ["helper", "admin_prompt", "sudo"] as const) {
expect(helperRow(state, backend).title).toMatch(/^Helper: \S/);
}
}
});
test("still gives a row for a state this build doesn't know", () => {
const row = helperRow("from_the_future" as HelperState, "admin_prompt");
expect(row).toEqual({
title: "Helper: from_the_future",
description: "Changes use the password prompt.",
action: null,
});
});
test("says plainly that a dev build cannot use it", () => {
expect(helperRow("unavailable", "admin_prompt")).toMatchObject({
title: "Helper: not in dev builds",
action: null,
});
});
});
describe("helperPollInterval", () => {
const now = 100_000;
test("polls every 2 seconds while approval is pending", () => {
expect(helperPollInterval("requires_approval", null, now)).toBe(2000);
});
test("stops once enabled or not registered, even just after registering", () => {
expect(helperPollInterval("enabled", now - 500, now)).toBe(false);
expect(helperPollInterval("not_registered", now - 500, now)).toBe(false);
});
test("polls briefly after registering, until approval shows", () => {
expect(helperPollInterval("not_found", now - 500, now)).toBe(2000);
expect(helperPollInterval(undefined, now - 500, now)).toBe(2000);
expect(helperPollInterval("not_found", now - 10_000, now)).toBe(false);
});
test("never polls in other states", () => {
for (const helper of ["unavailable", "not_found", undefined] as const) {
expect(helperPollInterval(helper, null, now)).toBe(false);
}
});
});
describe("recordingLabel", () => {
test("offers the opposite of the current state", () => {
expect(recordingLabel(true)).toBe("Pause Recording");
+87 -3
View File
@@ -1,7 +1,9 @@
import type { HelperState, SystemProxyBackend } from "@yaakapp-internal/proxy-lib";
/**
* "Override system proxy": this Mac's web traffic pointed at the running engine, changed at once
* whenever it is flipped, through the macOS password prompt. Whether it turns on as the app
* launches is a separate setting.
* whenever it is flipped, through the privileged helper or the macOS password prompt. Whether it
* turns on as the app launches is a separate setting.
*/
export interface SystemProxyState {
/** This Mac's web traffic points at the engine now */
@@ -12,6 +14,8 @@ export interface SystemProxyState {
pending: boolean | null;
/** The last change failed, with this message */
error: string | null;
/** Changes go through the helper, with no password prompt */
helper?: boolean;
}
export interface SystemProxySwitch {
@@ -24,7 +28,8 @@ export interface SystemProxySwitch {
/** What the system proxy switch shows */
export function systemProxySwitch(state: SystemProxyState): SystemProxySwitch {
if (state.pending != null) {
return { checked: state.pending, description: "Waiting for your password", failed: false };
const description = state.helper ? "Changing the system proxy" : "Waiting for your password";
return { checked: state.pending, description, failed: false };
}
// A failed change leaves the switch where the system proxy actually is.
const checked = state.routing;
@@ -45,6 +50,85 @@ export function systemProxySwitch(state: SystemProxyState): SystemProxySwitch {
};
}
export interface HelperRow {
title: string;
/** Which way changes go, and why */
description: string;
/** What the row's button does, if it has one: the first two open the approval dialog */
action: "install" | "approve" | "unregister" | null;
}
/** The privileged helper's row in the state pill menu, kept short */
export function helperRow(helper: HelperState, backend: SystemProxyBackend): HelperRow {
switch (helper) {
case "unavailable":
return {
title: "Helper: not in dev builds",
description: "Changes use the password prompt.",
action: null,
};
case "not_found":
// What macOS reports until the helper is first installed.
return {
title: "Helper: not found by macOS",
description: "Changes use the password prompt.",
action: "install",
};
case "not_registered":
return {
title: "Helper: not installed",
description: "Changes use the password prompt.",
action: "install",
};
case "requires_approval":
return {
title: "Helper: awaiting approval",
description: "Changes use the password prompt.",
action: "approve",
};
case "enabled":
return {
title: "Helper: enabled",
description:
backend === "helper"
? "No password prompts."
: "One more password prompt puts back your settings.",
action: "unregister",
};
default: {
// Every state is handled above; one this build doesn't know still gets a row, rather
// than taking the whole menu down.
const unknown: never = helper;
return {
title: `Helper: ${String(unknown)}`,
description: "Changes use the password prompt.",
action: null,
};
}
}
}
/** How often the helper's state is read while it can change outside the app */
export const HELPER_POLL_MS = 2000;
/** How long after registering the state is read even before it shows approval pending */
export const HELPER_REGISTER_POLL_MS = 10_000;
/**
* The interval to read the helper's state at: while it awaits approval in System Settings, and
* briefly after registering, until it settles as enabled or not registered. Never otherwise.
*/
export function helperPollInterval(
helper: HelperState | undefined,
registeredAt: number | null,
now: number,
): number | false {
if (helper === "requires_approval") return HELPER_POLL_MS;
if (helper === "enabled" || helper === "not_registered") return false;
const justRegistered = registeredAt != null && now - registeredAt < HELPER_REGISTER_POLL_MS;
return justRegistered ? HELPER_POLL_MS : false;
}
/** The menu item that pauses or resumes storing flows */
export function recordingLabel(recording: boolean): string {
return recording ? "Pause Recording" : "Resume Recording";
+11
View File
@@ -2,6 +2,7 @@ import { invoke } from "@tauri-apps/api/core";
import { listen as tauriListen } from "@tauri-apps/api/event";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { type as tauriOsType } from "@tauri-apps/plugin-os";
import { unsubscribeWhenReady } from "./unsubscribe";
/** Call a Tauri command. */
export function command<T>(cmd: string, args?: Record<string, unknown>): Promise<T> {
@@ -19,6 +20,16 @@ export function subscribe<T>(event: string, callback: (payload: T) => void): ()
return () => unsub?.();
}
/** Calls `callback` each time the window regains focus. Returns an unsubscribe function. */
export function onWindowFocus(callback: () => void): () => void {
const subscription = unsubscribeWhenReady(
getCurrentWebviewWindow().onFocusChanged(
({ payload: focused }) => focused && subscription.active() && callback(),
),
);
return subscription.unsubscribe;
}
/** Show the current webview window. */
export function showWindow(): Promise<void> {
return getCurrentWebviewWindow().show();
+34
View File
@@ -0,0 +1,34 @@
import { describe, expect, test, vi } from "vite-plus/test";
import { unsubscribeWhenReady } from "./unsubscribe";
function pending() {
let resolve: (fn: () => void) => void = () => {};
const promise = new Promise<() => void>((r) => (resolve = r));
return { promise, resolve };
}
describe("unsubscribeWhenReady", () => {
test("unsubscribes once ready when cleanup ran first", async () => {
const { promise, resolve } = pending();
const unsub = vi.fn();
const subscription = unsubscribeWhenReady(promise);
subscription.unsubscribe();
expect(subscription.active()).toBe(false);
resolve(unsub);
await promise;
await Promise.resolve();
expect(unsub).toHaveBeenCalledTimes(1);
});
test("unsubscribes at once when already ready, and only once", async () => {
const unsub = vi.fn();
const promise = Promise.resolve(unsub);
const subscription = unsubscribeWhenReady(promise);
await promise;
await Promise.resolve();
expect(subscription.active()).toBe(true);
subscription.unsubscribe();
subscription.unsubscribe();
expect(unsub).toHaveBeenCalledTimes(1);
});
});
+25
View File
@@ -0,0 +1,25 @@
/**
* An unsubscribe for a subscription that is still being set up. Called before the setup
* resolves, it unsubscribes as soon as it does; `active` says whether to still deliver events.
*/
export function unsubscribeWhenReady(subscription: Promise<() => void>): {
unsubscribe: () => void;
active: () => boolean;
} {
let unsub: (() => void) | null = null;
let cancelled = false;
subscription
.then((fn) => {
if (cancelled) fn();
else unsub = fn;
})
.catch(console.error);
return {
unsubscribe: () => {
cancelled = true;
unsub?.();
unsub = null;
},
active: () => !cancelled,
};
}