A desktop coding agent with free access to frontier models.
TypeScript
fix(desktop): close the DevTools port and harden links, deep links and IPC
Ramshouriesh Rf34c02a7b8e9
diff --git a/apps/app/src/app/lib/omnirush-links.ts b/apps/app/src/app/lib/omnirush-links.tsindex b3d304ad..d533e9ae 100644--- a/apps/app/src/app/lib/omnirush-links.ts+++ b/apps/app/src/app/lib/omnirush-links.ts@@ -1,4 +1,4 @@-import { DEFAULT_DEN_BASE_URL, normalizeDenBaseUrl } from "./den";+import { DEFAULT_DEN_BASE_URL, denOriginComparisonKey, normalizeDenBaseUrl, resolveDenBaseUrls } from "./den";import { normalizeOmniRushServerUrl } from "./omnirush-server";export type RemoteWorkspaceDefaults = {@@ -144,6 +144,68 @@ export function parseDenAuthDeepLink(rawUrl: string): DenAuthDeepLink | null {};}+export type DenAuthDeepLinkReview =+ | { kind: "blocked"; host: string }+ | { kind: "confirm"; host: string; currentHost: string | null };++function hostOf(value: string): string {+ try {+ return new URL(value).host;+ } catch {+ return "";+ }+}++function isLoopbackOrigin(origin: string): boolean {+ try {+ const { hostname } = new URL(origin);+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";+ } catch {+ return false;+ }+}++/**+ * A den-auth link signs the app in to the control plane it names, so it may+ * only name one this device is already set up for (`configuredBaseUrls`:+ * build default, desktop bootstrap or confirmed connect link, local gateway,+ * development overrides), and the user always confirms it. `allowLoopback`+ * also accepts local control planes in development builds.+ */+export function reviewDenAuthDeepLink(input: {+ denBaseUrl: string;+ configuredBaseUrls: ReadonlyArray<string | null | undefined>;+ currentBaseUrl: string | null;+ allowLoopback: boolean;+}): DenAuthDeepLinkReview {+ const target = resolveDenBaseUrls(input.denBaseUrl);+ const host = hostOf(target.baseUrl);+ const allowed = new Set<string>();+ for (const configured of input.configuredBaseUrls) {+ if (!normalizeDenBaseUrl(configured)) continue;+ const resolved = resolveDenBaseUrls(configured);+ for (const value of [configured, resolved.baseUrl, resolved.apiBaseUrl]) {+ const origin = denOriginComparisonKey(value);+ if (origin) allowed.add(origin);+ }+ }+ const targetOrigins = [target.baseUrl, target.apiBaseUrl].map((value) => denOriginComparisonKey(value));+ const permitted = targetOrigins.every((origin) => (+ origin !== null && (allowed.has(origin) || (input.allowLoopback && isLoopbackOrigin(origin)))+ ));+ if (!host || !permitted) return { kind: "blocked", host };+ const currentHost = input.currentBaseUrl ? hostOf(resolveDenBaseUrls(input.currentBaseUrl).baseUrl) : "";+ return { kind: "confirm", host, currentHost: currentHost && currentHost !== host ? currentHost : null };+}++/** Development-only extra control planes, comma-separated (VITE_DEN_ALLOWED_ORIGINS). */+export function readDevAllowedDenOrigins(): string[] {+ const raw = typeof import.meta !== "undefined" && typeof import.meta.env?.VITE_DEN_ALLOWED_ORIGINS === "string"+ ? import.meta.env.VITE_DEN_ALLOWED_ORIGINS+ : "";+ return raw.split(",").map((value: string) => value.trim()).filter(Boolean);+}+export function parseConnectDeepLink(rawUrl: string): ConnectDeepLink | null {let url: URL;try {@@ -179,6 +241,20 @@ export function parseConnectDeepLink(rawUrl: string): ConnectDeepLink | null {return { rawUrl, key: signed ? `signed:${token}` : `exchange:${apiBaseUrl}:${code}` };}+/**+ * Host an unsigned exchange connect link asks the app to contact, shown to+ * the user before anything is sent there. Null for other links.+ */+export function connectExchangeHost(rawUrl: string): string | null {+ const link = parseConnectDeepLink(rawUrl);+ if (!link || !link.key.startsWith("exchange:")) return null;+ try {+ return new URL(new URL(rawUrl).searchParams.get("apiBaseUrl")?.trim() ?? "").host || null;+ } catch {+ return null;+ }+}+function normalizeDebugDeepLinkInput(rawValue: string): string {const trimmed = rawValue.trim();if (!trimmed) return "";diff --git a/apps/app/src/components/markdown/markdown-primitive.ts b/apps/app/src/components/markdown/markdown-primitive.tsindex 28976747..e026f1ac 100644--- a/apps/app/src/components/markdown/markdown-primitive.ts+++ b/apps/app/src/components/markdown/markdown-primitive.ts@@ -99,6 +99,13 @@ function safeHref(href: string) {return "#";}+ // `//host/x` and `\\host\x` are network paths: under the packaged+ // `file://` page they resolve to `file://host/...` (UNC on Windows). URL+ // parsing drops tabs and newlines and reads `\` as `/`, so check that form.+ if (/^[\\/]{2}/.test(trimmed.replace(/[\t\n\r]/g, ""))) {+ return "#";+ }+if (trimmed.startsWith("#") || trimmed.startsWith("/") || trimmed.startsWith("./") || trimmed.startsWith("../")) {return trimmed;}diff --git a/apps/app/src/i18n/locales/en.ts b/apps/app/src/i18n/locales/en.tsindex 32e211f4..8d54ad1f 100644--- a/apps/app/src/i18n/locales/en.ts+++ b/apps/app/src/i18n/locales/en.ts@@ -533,6 +533,9 @@ export default {"connect.verifying_title": "Checking connection link…","connect.verifying_body": "Checking the organization and server before anything changes.","connect.confirm_title": "Set up {appName} for {org}?",+ "connect.contact_body": "This setup link was not signed by a server this app trusts. Continuing sends its one-time code to {host} to look up the organization. Nothing is changed yet; continue only if your administrator sent you this link.",+ "connect.contact_cta": "Continue",+ "connect.contact_title": "Contact {host}?","connect.confirm_body": "This app will use {host} as its organization server. Nothing has been changed yet.","connect.confirm_switch_body": "This app is currently connected to {current}. Confirming switches it to {host}.","connect.confirm_server_label": "Server",@@ -625,9 +628,15 @@ export default {"den.signed_out": "Signed out","den.signin_button": "Sign in","den.signin_code_note": "Accepts an omnirush://den-auth link or the raw one-time grant.",+ "den.signin_link_blocked_body": "This sign-in link points to {host}, which is not a server this device is set up for, so it was ignored. If your organization uses that server, connect to it first with the link your administrator sent.",+ "den.signin_link_blocked_title": "Sign-in link not accepted",+ "den.signin_link_confirm_body": "A sign-in link asks to sign this app in to {host}. Continue only if you just started signing in.",+ "den.signin_link_confirm_cta": "Sign in",+ "den.signin_link_confirm_title": "Sign in to {host}?","den.signin_link_copied": "Copied","den.signin_link_hint": "If your browser doesn't bounce back into omnirush.ai automatically, paste the sign-in link or one-time code from omnirush.ai Cloud here.","den.signin_link_label": "Sign-in link or one-time code",+ "den.signin_link_no_server": "no server","den.signin_link_placeholder": "omnirush://den-auth?... or pasted code","den.signin_title": "Sign in to omnirush.ai Cloud","den.signing_in": "Finishing omnirush.ai Cloud sign-in...",diff --git a/apps/app/src/react-app/domains/cloud/connect-confirm-dialog.tsx b/apps/app/src/react-app/domains/cloud/connect-confirm-dialog.tsxindex 2bdd3cfb..3a887dc3 100644--- a/apps/app/src/react-app/domains/cloud/connect-confirm-dialog.tsx+++ b/apps/app/src/react-app/domains/cloud/connect-confirm-dialog.tsx@@ -14,13 +14,15 @@ import {} from "../../../components/ui/dialog";import { formatControlPlaneHost } from "../settings/cloud/control-plane-url";-export type ConnectConfirmPhase = "verifying" | "confirm" | "applying" | "error";+export type ConnectConfirmPhase = "contact" | "verifying" | "confirm" | "applying" | "error";export type ConnectConfirmDialogProps = {open: boolean;phase: ConnectConfirmPhase;claims: ConnectLinkClaims | null;transport: ConnectLinkTransport | null;+ /** Server an unsigned exchange link would contact, during the "contact" phase. */+ contactHost: string | null;/** Host currently configured, when the app is already connected somewhere. */currentHost: string | null;error: { code: ConnectLinkVerifyErrorCode; message: string } | null;@@ -68,6 +70,7 @@ export function ConnectConfirmDialog({phase,claims,transport,+ contactHost,currentHost,error,onConfirm,@@ -96,6 +99,23 @@ export function ConnectConfirmDialog({</Button></DialogFooter></>+ ) : phase === "contact" && contactHost ? (+ <>+ <DialogHeader>+ <DialogTitle>{t("connect.contact_title", { host: contactHost })}</DialogTitle>+ <DialogDescription data-testid="connect-contact-host">+ {t("connect.contact_body", { host: contactHost })}+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button variant="outline" onClick={onDismiss} data-testid="connect-contact-cancel">+ {t("common.cancel")}+ </Button>+ <Button onClick={onConfirm} data-testid="connect-contact-accept">+ {t("connect.contact_cta")}+ </Button>+ </DialogFooter>+ </>) : phase === "verifying" ? (<DialogHeader><DialogTitle>{t("connect.verifying_title")}</DialogTitle>diff --git a/apps/app/src/react-app/domains/cloud/connect-link-provider.tsx b/apps/app/src/react-app/domains/cloud/connect-link-provider.tsxindex c23535c3..4f8c9d17 100644--- a/apps/app/src/react-app/domains/cloud/connect-link-provider.tsx+++ b/apps/app/src/react-app/domains/cloud/connect-link-provider.tsx@@ -16,7 +16,7 @@ import {drainPendingDeepLinks,type DeepLinkBridgeDetail,} from "../../../app/lib/deep-link-bridge";-import { parseConnectDeepLink } from "../../../app/lib/omnirush-links";+import { connectExchangeHost, parseConnectDeepLink } from "../../../app/lib/omnirush-links";import { isDesktopRuntime } from "../../../app/utils";import { ConnectConfirmDialog, type ConnectConfirmPhase } from "./connect-confirm-dialog";@@ -46,6 +46,9 @@ export function ConnectLinkProvider({ children }: ConnectLinkProviderProps) {const [error, setError] = useState<ConnectLinkError | null>(null);const handledLinksRef = useRef<Set<string>>(new Set());const pendingRef = useRef<PendingConnectLink | null>(null);+ // An unsigned exchange link names its own server; nothing is sent there+ // until the user agrees to contact that host.+ const [contact, setContact] = useState<{ rawUrl: string; key: string; host: string } | null>(null);const beginVerify = useCallback((rawUrl: string, key: string) => {handledLinksRef.current.add(key);@@ -76,6 +79,16 @@ export function ConnectLinkProvider({ children }: ConnectLinkProviderProps) {for (const rawUrl of urls) {const parsed = parseConnectDeepLink(rawUrl);if (!parsed || handledLinksRef.current.has(parsed.key)) continue;+ const host = connectExchangeHost(parsed.rawUrl);+ if (host) {+ handledLinksRef.current.add(parsed.key);+ setError(null);+ setPending(null);+ pendingRef.current = null;+ setContact({ rawUrl: parsed.rawUrl, key: parsed.key, host });+ setPhase("contact");+ break;+ }beginVerify(parsed.rawUrl, parsed.key);// One prompt at a time; later links can arrive again as new deep-link// events after the current prompt is resolved.@@ -99,10 +112,16 @@ export function ConnectLinkProvider({ children }: ConnectLinkProviderProps) {setPhase("idle");setPending(null);pendingRef.current = null;+ setContact(null);setError(null);}, []);const confirm = useCallback(() => {+ if (phase === "contact" && contact) {+ setContact(null);+ beginVerify(contact.rawUrl, contact.key);+ return;+ }const current = pendingRef.current;if (!current) return;setPhase("applying");@@ -121,7 +140,7 @@ export function ConnectLinkProvider({ children }: ConnectLinkProviderProps) {setError({ code: "invalid_token", message: "Could not apply the connect link." });setPhase("error");});- }, [dismiss]);+ }, [beginVerify, contact, dismiss, phase]);return (<>@@ -131,6 +150,7 @@ export function ConnectLinkProvider({ children }: ConnectLinkProviderProps) {phase={phase === "idle" ? "verifying" : phase}claims={pending?.claims ?? null}transport={pending?.transport ?? null}+ contactHost={contact?.host ?? null}currentHost={null}error={error}onConfirm={confirm}diff --git a/apps/app/src/react-app/domains/cloud/den-auth-provider.tsx b/apps/app/src/react-app/domains/cloud/den-auth-provider.tsxindex 992276ad..32b98bc4 100644--- a/apps/app/src/react-app/domains/cloud/den-auth-provider.tsx+++ b/apps/app/src/react-app/domains/cloud/den-auth-provider.tsx@@ -13,12 +13,11 @@ import {import {clearDenSession,createDenClient,+ DEFAULT_DEN_BASE_URL,ensureDenActiveOrganization,- denOriginComparisonKey,isDenSessionRevokedError,readDenBootstrapConfig,readDenSettings,- resolveDenBaseUrls,setDenBootstrapConfig,type DenBootstrapConfig,type DenOrgSummary,@@ -35,7 +34,13 @@ import {deepLinkBridgeEvent,drainPendingDeepLinks,} from "../../../app/lib/deep-link-bridge";-import { parseDenAuthDeepLink } from "../../../app/lib/omnirush-links";+import { getOmniRushGatewayOrigin } from "../../../app/lib/gateway-runtime";+import {+ parseDenAuthDeepLink,+ readDevAllowedDenOrigins,+ reviewDenAuthDeepLink,+ type DenAuthDeepLinkReview,+} from "../../../app/lib/omnirush-links";import {AlertDialog,AlertDialogAction,@@ -133,18 +138,11 @@ type PendingServerSwitch = {grant: string;denBaseUrl: string;isEnterpriseActivation: boolean;- currentHost: string;+ /** Set when the link would move this device to a different server. */+ currentHost: string | null;newHost: string;};-function hostLabel(value: string): string {- try {- return new URL(value).host;- } catch {- return value.replace(/^https?:\/\//, "").replace(/\/+$/, "");- }-}-function readDeepLinkEventUrls(detail: unknown): string[] {if (!detail || typeof detail !== "object" || !("urls" in detail)) return [];const urlsValue = detail.urls;@@ -152,31 +150,27 @@ function readDeepLinkEventUrls(detail: unknown): string[] {return items.flatMap((url) => typeof url === "string" ? [url] : []);}-function pendingServerSwitchForDeepLink(input: {- grant: string;- denBaseUrl: string;- isEnterpriseActivation: boolean;-}): PendingServerSwitch | null {+/**+ * Any page or program can open an omnirush://den-auth link, and it would sign+ * this app in to the server it names. So every link waits for the user, and+ * one naming a server this device is not set up for is refused.+ */+export function reviewDenAuthDeepLinkForDevice(denBaseUrl: string): DenAuthDeepLinkReview {const bootstrap = readDenBootstrapConfig();- // An enterprise activation permanently binds the installation to the issuing- // Den, so confirm a control-plane change even when no bootstrap file- // provisioned one. Otherwise any omnirush://den-auth link can repoint the- // control plane and activate the app in a single unattended step.- if (bootstrap.source !== "file" && !input.isEnterpriseActivation) return null;-- const currentApiBaseUrl = resolveDenBaseUrls(bootstrap).apiBaseUrl;- const newApiBaseUrl = resolveDenBaseUrls(input.denBaseUrl).apiBaseUrl;- const currentOrigin = denOriginComparisonKey(currentApiBaseUrl);- const newOrigin = denOriginComparisonKey(newApiBaseUrl);- if (!currentOrigin || !newOrigin || currentOrigin === newOrigin) return null;-- return {- grant: input.grant,- denBaseUrl: input.denBaseUrl,- isEnterpriseActivation: input.isEnterpriseActivation,- currentHost: hostLabel(currentApiBaseUrl),- newHost: hostLabel(newApiBaseUrl),- };+ const settings = readDenSettings();+ return reviewDenAuthDeepLink({+ denBaseUrl,+ configuredBaseUrls: [+ DEFAULT_DEN_BASE_URL,+ bootstrap.baseUrl,+ bootstrap.apiBaseUrl,+ settings.baseUrl,+ getOmniRushGatewayOrigin(),+ ...readDevAllowedDenOrigins(),+ ],+ currentBaseUrl: bootstrap.baseUrl || settings.baseUrl || null,+ allowLoopback: typeof import.meta !== "undefined" && import.meta.env?.DEV === true,+ });}/**@@ -201,6 +195,7 @@ export function DenAuthProvider({ children }: DenAuthProviderProps) {const signalRetryInFlightRef = useRef(false);const handledGrantsRef = useRef<Set<string>>(new Set());const [pendingServerSwitch, setPendingServerSwitch] = useState<PendingServerSwitch | null>(null);+ const [blockedDenAuthHost, setBlockedDenAuthHost] = useState<string | null>(null);const updateStatus = useCallback((nextStatus: DenAuthStatus) => {statusRef.current = nextStatus;@@ -503,22 +498,18 @@ export function DenAuthProvider({ children }: DenAuthProviderProps) {if (!parsed || handledGrantsRef.current.has(parsed.grant)) continue;handledGrantsRef.current.add(parsed.grant);- const isEnterpriseActivation =- readDesktopDistributionInfo().flavor === "enterprise";- const pending = pendingServerSwitchForDeepLink({- ...parsed,- isEnterpriseActivation,- });- if (pending) {- setPendingServerSwitch(pending);+ const review = reviewDenAuthDeepLinkForDevice(parsed.denBaseUrl);+ if (review.kind === "blocked") {+ setBlockedDenAuthHost(review.host);continue;}-- exchangeDeepLinkGrant(- parsed.grant,- parsed.denBaseUrl,- isEnterpriseActivation,- );+ setPendingServerSwitch({+ grant: parsed.grant,+ denBaseUrl: parsed.denBaseUrl,+ isEnterpriseActivation: readDesktopDistributionInfo().flavor === "enterprise",+ currentHost: review.currentHost,+ newHost: review.host,+ });}};@@ -554,14 +545,20 @@ export function DenAuthProvider({ children }: DenAuthProviderProps) {><AlertDialogContent><AlertDialogHeader>- <AlertDialogTitle>{t("den.switch_server_title")}</AlertDialogTitle>- <AlertDialogDescription>- {pendingServerSwitch+ <AlertDialogTitle>+ {pendingServerSwitch?.currentHost+ ? t("den.switch_server_title")+ : t("den.signin_link_confirm_title", { host: pendingServerSwitch?.newHost ?? "" })}+ </AlertDialogTitle>+ <AlertDialogDescription data-testid="den-auth-link-confirm-body">+ {pendingServerSwitch?.currentHost? t("den.switch_server_body", {currentHost: pendingServerSwitch.currentHost,newHost: pendingServerSwitch.newHost,})- : null}+ : pendingServerSwitch+ ? t("den.signin_link_confirm_body", { host: pendingServerSwitch.newHost })+ : null}</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter>@@ -580,7 +577,27 @@ export function DenAuthProvider({ children }: DenAuthProviderProps) {);}}>- {t("den.switch_server_confirm")}+ {pendingServerSwitch?.currentHost ? t("den.switch_server_confirm") : t("den.signin_link_confirm_cta")}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ <AlertDialog+ open={blockedDenAuthHost !== null}+ onOpenChange={(open) => {+ if (!open) setBlockedDenAuthHost(null);+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t("den.signin_link_blocked_title")}</AlertDialogTitle>+ <AlertDialogDescription data-testid="den-auth-link-blocked-body">+ {t("den.signin_link_blocked_body", { host: blockedDenAuthHost || t("den.signin_link_no_server") })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogAction onClick={() => setBlockedDenAuthHost(null)}>+ {t("common.close")}</AlertDialogAction></AlertDialogFooter></AlertDialogContent>diff --git a/apps/app/src/react-app/domains/session/chat/session-page.tsx b/apps/app/src/react-app/domains/session/chat/session-page.tsxindex 4a5124fd..be4d31f8 100644--- a/apps/app/src/react-app/domains/session/chat/session-page.tsx+++ b/apps/app/src/react-app/domains/session/chat/session-page.tsx@@ -791,7 +791,7 @@ export function SessionPage(props: SessionPageProps) {const openBrowserUrlControlAction = useMemo<OmniRushControlAction>(() => ({id: "browser.open_url",label: "Open URL in built-in browser",- description: "Open a built-in browser tab and return its tab_id and CDP handle. The tab is protected from suspension for its task lifetime until browser.release_tab declares all running and queued browser work complete.",+ description: "Open a built-in browser tab and return its tab_id and target_id (browser_url is a CDP endpoint in development builds only and null in released apps; use the browser_* tools). The tab is protected from suspension for its task lifetime until browser.release_tab declares all running and queued browser work complete.",sideEffect: "navigation",requiresArgs: true,args: [@@ -819,7 +819,7 @@ export function SessionPage(props: SessionPageProps) {const restoreBrowserTabControlAction = useMemo<OmniRushControlAction>(() => ({id: "browser.restore_tab",label: "Restore browser tab",- description: "Acquire a fresh protected CDP handle for a tab owned by this conversation. A suspended tab reloads its saved URL, not its previous document, retaining tab_id with a new target_id. A live tab keeps its document. Always use the returned handle. Protection lasts until browser.release_tab.",+ description: "Acquire a fresh protected handle (tab_id, target_id; browser_url only in development builds) for a tab owned by this conversation. A suspended tab reloads its saved URL, not its previous document, retaining tab_id with a new target_id. A live tab keeps its document. Always use the returned handle. Protection lasts until browser.release_tab.",sideEffect: "mutation",requiresArgs: true,args: [{ name: "tabId", type: "string", required: true, description: "The logical tab_id returned by browser.open_url or browser.restore_tab." }],diff --git a/apps/app/src/react-app/kernel/local-provider.tsx b/apps/app/src/react-app/kernel/local-provider.tsxindex 67a1dd9c..d6dc54e7 100644--- a/apps/app/src/react-app/kernel/local-provider.tsx+++ b/apps/app/src/react-app/kernel/local-provider.tsx@@ -11,6 +11,8 @@ import {} from "react";import { MODEL_PREF_KEY, THINKING_PREF_KEY } from "../../app/constants";+import { desktopBridge } from "../../app/lib/desktop";+import { isElectronRuntime } from "../../app/lib/runtime-env";import { coerceReleaseChannel } from "../../app/lib/release-channels";import type { ModelRef, ReleaseChannel, SettingsTab, View } from "../../app/types";import {@@ -169,6 +171,13 @@ export function LocalProvider({ children }: LocalProviderProps) {writePersisted(LOCAL_PREFERENCES_KEY, prefs);}, [prefs]);+ // Desktop error reports (apps/desktop/electron/sentry.mjs) follow the same+ // "Share anonymous usage" setting as product analytics.+ useEffect(() => {+ if (!isElectronRuntime()) return;+ void desktopBridge.desktopSentrySetConsent(prefs.analyticsEnabled).catch(() => undefined);+ }, [prefs.analyticsEnabled]);+useEffect(() => {const updateDefaultModel = () => {const model = readStoredDefaultModel();diff --git a/apps/app/tests/connect-link-parse.test.ts b/apps/app/tests/connect-link-parse.test.tsindex e5ba0c48..65042e1c 100644--- a/apps/app/tests/connect-link-parse.test.ts+++ b/apps/app/tests/connect-link-parse.test.ts@@ -1,5 +1,5 @@import { describe, expect, test } from "bun:test";-import { parseConnectDeepLink } from "../src/app/lib/omnirush-links";+import { connectExchangeHost, parseConnectDeepLink, reviewDenAuthDeepLink } from "../src/app/lib/omnirush-links";const TOKEN = "eyJhbGciOiJFZERTQSJ9.eyJmYWtlIjoxfQ.c2ln";@@ -29,3 +29,36 @@ describe("parseConnectDeepLink", () => {expect(parseConnectDeepLink("not a url")).toBeNull();});});++describe("connectExchangeHost", () => {+ test("names the server an unsigned exchange link would contact", () => {+ const code = "abcdefghijklmnopqrstuvwxyz123456";+ const link = (apiBaseUrl: string) => `omnirush://connect?code=${code}&apiBaseUrl=${encodeURIComponent(apiBaseUrl)}`;+ expect(connectExchangeHost(link("https://den.example.com/api/den"))).toBe("den.example.com");+ expect(connectExchangeHost(link("https://[email protected]/"))).toBe("den.example.com");+ expect(connectExchangeHost(link("https://ехаmple.com/"))).toStartWith("xn--");+ expect(connectExchangeHost(`omnirush://connect?token=${TOKEN}`)).toBeNull();+ });+});++describe("reviewDenAuthDeepLink", () => {+ const configured = ["https://den.example.com"];+ test("always asks, and only for a server this device is set up for", () => {+ expect(reviewDenAuthDeepLink({ denBaseUrl: "https://den.example.com", configuredBaseUrls: configured, currentBaseUrl: "https://den.example.com", allowLoopback: false }))+ .toEqual({ kind: "confirm", host: "den.example.com", currentHost: null });+ expect(reviewDenAuthDeepLink({ denBaseUrl: "https://den.attacker.example", configuredBaseUrls: configured, currentBaseUrl: "https://den.example.com", allowLoopback: false }))+ .toEqual({ kind: "blocked", host: "den.attacker.example" });+ expect(reviewDenAuthDeepLink({ denBaseUrl: "", configuredBaseUrls: [], currentBaseUrl: null, allowLoopback: false }).kind).toBe("blocked");+ });++ test("a second configured server is a switch the user sees", () => {+ expect(reviewDenAuthDeepLink({ denBaseUrl: "https://other.example.com", configuredBaseUrls: [...configured, "https://other.example.com"], currentBaseUrl: "https://den.example.com", allowLoopback: false }))+ .toEqual({ kind: "confirm", host: "other.example.com", currentHost: "den.example.com" });+ });++ test("local control planes count only in development builds", () => {+ const input = { denBaseUrl: "http://localhost:3005", configuredBaseUrls: [], currentBaseUrl: null };+ expect(reviewDenAuthDeepLink({ ...input, allowLoopback: false }).kind).toBe("blocked");+ expect(reviewDenAuthDeepLink({ ...input, allowLoopback: true }).kind).toBe("confirm");+ });+});diff --git a/apps/app/tests/markdown-links.test.ts b/apps/app/tests/markdown-links.test.tsnew file mode 100644index 00000000..d5b20e8b--- /dev/null+++ b/apps/app/tests/markdown-links.test.ts@@ -0,0 +1,29 @@+import { describe, expect, test } from "bun:test";++import { renderMarkdownHtml } from "../src/components/markdown/markdown-primitive";++function hrefs(html: string): string[] {+ return [...html.matchAll(/<a [^>]*?href="([^"]*)"/g)].map((match) => match[1] ?? "");+}++describe("markdown link targets", () => {+ test("network paths never become clickable links", () => {+ // Markdown source; after its backslash unescaping each href starts with+ // two slashes or backslashes (`\\\\` in the source is `\\` in the href).+ for (const target of ["//attacker.example/share/setup.exe", "\\\\\\\\attacker.example\\share\\setup.exe", "/\\\\attacker.example/x.exe", "\\\\/attacker.example/x.exe", "/\t/attacker.example/x.exe"]) {+ const html = renderMarkdownHtml(`[report](<${target}>)`);+ expect(hrefs(html)).toEqual(["#"]);+ const image = renderMarkdownHtml(``);+ expect(image).not.toContain("attacker.example/share");+ }+ });++ test("web, mail and local relative links keep working", () => {+ expect(hrefs(renderMarkdownHtml("[site](https://example.com/a?b=1)"))).toEqual(["https://example.com/a?b=1"]);+ expect(hrefs(renderMarkdownHtml("[mail](mailto:[email protected])"))).toEqual(["mailto:[email protected]"]);+ expect(hrefs(renderMarkdownHtml("[notes](./docs/notes.md)"))).toEqual(["./docs/notes.md"]);+ expect(hrefs(renderMarkdownHtml("[abs](/docs/notes.md)"))).toEqual(["/docs/notes.md"]);+ expect(hrefs(renderMarkdownHtml("[anchor](#section)"))).toEqual(["#section"]);+ expect(hrefs(renderMarkdownHtml("[script](javascript:alert(1))"))).toEqual(["#"]);+ });+});diff --git a/apps/desktop/electron-builder.base.yml b/apps/desktop/electron-builder.base.ymlindex 7df6aa7b..3baf8e29 100644--- a/apps/desktop/electron-builder.base.yml+++ b/apps/desktop/electron-builder.base.yml@@ -34,6 +34,15 @@ extraResources:- "**/*.mdx"- "docs.json"asar: true+# Electron fuses, flipped in the packaged binary before signing. runAsNode+# stays on: the bundled UI-control and computer-use MCPs, the nuke worker and+# cleanup helpers run this binary with ELECTRON_RUN_AS_NODE=1. Asar integrity+# validation stays off until it is verified on signed macOS/Windows builds.+electronFuses:+ runAsNode: true+ enableNodeOptionsEnvironmentVariable: false+ enableNodeCliInspectArguments: false+ onlyLoadAppFromAsar: trueasarUnpack:- node_modules/koffi/**- node_modules/.pnpm/@lydell+node-pty*/**diff --git a/apps/desktop/electron/browser-panel.mjs b/apps/desktop/electron/browser-panel.mjsindex d1ae7343..481d7c3a 100644--- a/apps/desktop/electron/browser-panel.mjs+++ b/apps/desktop/electron/browser-panel.mjs@@ -16,6 +16,7 @@ import { listInstalledBrowsers } from "./installed-browsers.mjs";import { BrowserTaskError, createBrowserTaskHost } from "./browser-task.mjs";import { createWebMcpBroker } from "./webmcp-host.mjs";import { createWebMcpFramePolicy } from "./webmcp-policy.mjs";+import { installBrowserPanelPermissionHandlers } from "./media-permissions.mjs";const __dirname = path.dirname(fileURLToPath(import.meta.url));const BROWSER_SESSION_PARTITION = "persist:omnirush-browser";@@ -23,6 +24,37 @@ const BROWSER_DEFAULT_URL = "about:blank";// URL a user-initiated new tab (the "+" button / opening the browser panel)// lands on. The agent's programmatic path keeps BROWSER_DEFAULT_URL.const BROWSER_NEW_TAB_URL = "https://www.google.com";++function isDesktopDeepLink(url) {+ return /^omnirush(?:-dev)?:/i.test(String(url ?? ""));+}++function hostLabel(value) {+ try {+ return new URL(value).host || null;+ } catch {+ return null;+ }+}++/**+ * What a desktop deep link asks for and which server it names, for the+ * confirmation prompt. Never includes its grant, token, or code.+ */+export function describeDesktopDeepLink(url, sourceUrl) {+ let parsed;+ try {+ parsed = new URL(url);+ } catch {+ return `From: ${hostLabel(sourceUrl) ?? "a web page"}`;+ }+ const route = (parsed.hostname || parsed.pathname.replace(/^\/+|\/+$/g, "")).toLowerCase();+ const server = ["denBaseUrl", "apiBaseUrl", "omnirushHostUrl", "omnirushUrl"]+ .map((key) => hostLabel(parsed.searchParams.get(key)?.trim() ?? ""))+ .find(Boolean);+ const action = route === "den-auth" ? "Sign in" : route === "connect" ? "Connect to an organization" : route === "connect-remote" ? "Connect a remote workspace" : `Open "${route || "link"}"`;+ return [`From: ${hostLabel(sourceUrl) ?? "a web page"}`, `Asks to: ${action}`, ...(server ? [`Server: ${server}`] : [])].join("\n");+}// Bound native page allocation across conversations. Refuse new work rather// than evicting a live document (unsaved input and CDP handles cannot be restored// from a URL). This is a tab bound, not a Chromium process or memory limit.@@ -96,6 +128,7 @@ export function createBrowserPanel({ getWindow, remoteDebugPort, onDeepLink, che// Capture the first response, before a view can load any document.webMcpFramePolicy = createWebMcpFramePolicy(browserSession);webMcpFramePolicy.install();+ installBrowserPanelPermissionHandlers(browserSession, { confirmExternal: confirmExternalProtocol });}return browserSession;}@@ -168,6 +201,48 @@ export function createBrowserPanel({ getWindow, remoteDebugPort, onDeepLink, chereturn `tab_${Date.now().toString(36)}_${browserTabCounter.toString(36)}`;}+ /** A page asked the OS to open another app's link (mailto:, zoommtg:, ...). */+ async function confirmExternalProtocol(url, sourceUrl) {+ const mainWindow = window();+ let scheme = "external";+ try { scheme = new URL(url).protocol.replace(/:$/, ""); } catch { /* keep the generic label */ }+ /** @type {import("electron").MessageBoxOptions} */+ const options = {+ type: "question",+ buttons: ["Cancel", "Open"],+ defaultId: 0,+ cancelId: 0,+ noLink: true,+ title: "Open in another app?",+ message: `A page in the built-in browser wants to open a "${scheme}:" link in another app.`,+ detail: `From: ${hostLabel(sourceUrl) ?? "a web page"}`,+ };+ const { response } = mainWindow && !mainWindow.isDestroyed()+ ? await dialog.showMessageBox(mainWindow, options)+ : await dialog.showMessageBox(options);+ return response === 1;+ }++ async function confirmBrowserDeepLink(url, sourceUrl) {+ if (typeof onDeepLink !== "function") return;+ const mainWindow = window();+ /** @type {import("electron").MessageBoxOptions} */+ const options = {+ type: "warning",+ buttons: ["Cancel", "Open link"],+ defaultId: 0,+ cancelId: 0,+ noLink: true,+ title: "Open OmniRush.ai link?",+ message: "A page in the built-in browser wants to open an OmniRush.ai link.",+ detail: `${describeDesktopDeepLink(url, sourceUrl)}\n\nOnly continue if you started this yourself, for example by signing in on this page.`,+ };+ const { response } = mainWindow && !mainWindow.isDestroyed()+ ? await dialog.showMessageBox(mainWindow, options)+ : await dialog.showMessageBox(options);+ if (response === 1) onDeepLink([url]);+ }+function normalizeBrowserUrl(url, fallback = BROWSER_DEFAULT_URL) {const target = typeof url === "string" && url.trim() ? url.trim() : fallback;if (!target || target === "about:blank") return "about:blank";@@ -184,18 +259,43 @@ export function createBrowserPanel({ getWindow, remoteDebugPort, onDeepLink, che}}+ // The main window holds the privileged desktop bridge, so it may only show+ // the app's own document (main.mjs registers it before loading) and the+ // exact internal pages main.mjs loads itself, never other file:, data: or+ // localhost documents.+ let mainWindowEntryUrl = null;+ const mainWindowInternalUrls = new Set();++ function setMainWindowEntryUrl(url) {+ mainWindowEntryUrl = url;+ }++ function canonicalUrl(url) {+ try {+ return new URL(url).href;+ } catch {+ return null;+ }+ }++ function allowMainWindowInternalUrl(url) {+ const canonical = canonicalUrl(url);+ if (canonical) mainWindowInternalUrls.add(canonical);+ }+function isMainWindowAllowedNavigation(url) {- if (!url) return true;- if (url.startsWith("file://") || url.startsWith("data:")) return true;+ if (!url || url === "about:blank" || mainWindowInternalUrls.has(canonicalUrl(url))) return true;+ if (!mainWindowEntryUrl) return false;try {const target = new URL(url);- if (target.hostname === "127.0.0.1" || target.hostname === "localhost" || target.hostname === "[::1]") return true;- const currentUrl = window()?.webContents.getURL();- if (!currentUrl || currentUrl === "about:blank") return true;- const current = new URL(currentUrl);- return target.origin === current.origin;+ const entry = new URL(mainWindowEntryUrl);+ if (entry.protocol !== "file:") return target.origin === entry.origin;+ if (target.protocol !== "file:" || target.host !== entry.host) return false;+ // Chromium may re-case a Windows drive letter; those file systems ignore case.+ const fold = (value) => (process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value);+ return fold(decodeURIComponent(target.pathname)) === fold(decodeURIComponent(entry.pathname));} catch {- return true;+ return false;}}@@ -205,8 +305,9 @@ export function createBrowserPanel({ getWindow, remoteDebugPort, onDeepLink, cherunDetachedTask("open linked browser page", () => openBrowserUrlForAutomation(url, "builtin", { ownerSessionId }));}+ /** Packaged builds open no DevTools port (main.mjs), so there is none to hand out. */function cdpBrowserUrl() {- return `http://127.0.0.1:${remoteDebugPort}`;+ return remoteDebugPort > 0 ? `http://127.0.0.1:${remoteDebugPort}` : null;}/**@@ -855,12 +956,13 @@ export function createBrowserPanel({ getWindow, remoteDebugPort, onDeepLink, che// data: loads are internal plumbing (CDP target-marker pages), not// user-visible navigations — don't surface the panel for them.if (target === "about:blank" || target.startsWith("data:")) return;- // Intercept omnirush:// deep links (e.g. den-auth handoff grants) so- // in-app browser auth works without the system protocol handler.- if (target.startsWith("omnirush://") || target.startsWith("omnirush-dev://")) {- if (typeof onDeepLink === "function") {- onDeepLink([target]);- }+ // omnirush:// links (e.g. den-auth handoff grants) can sign the app in or+ // repoint it, and any page can start such a navigation, so the user+ // confirms each one before the app sees it (the system protocol+ // handler stays blocked by the session's openExternal permission).+ if (isDesktopDeepLink(target)) {+ const sourceUrl = view.webContents.getURL();+ runDetachedTask("confirm browser deep link", () => confirmBrowserDeepLink(target, sourceUrl));// Navigate the tab to about:blank to prevent the custom-scheme load// from erroring, then hide the panel. Avoid closing the tab// synchronously during a navigation event to prevent renderer crashes.@@ -1531,6 +1633,8 @@ export function createBrowserPanel({ getWindow, remoteDebugPort, onDeepLink, chereturn {destroy: destroyBrowserView,isMainWindowAllowedNavigation,+ setMainWindowEntryUrl,+ allowMainWindowInternalUrl,browserTask: (args, options) => taskHost.request(args, options),listWebMcpTools: (args, options) => taskHost.request({ sessionId: args?.sessionId, operation: "site_tools", args }, options),executeWebMcpTool: (args, options) => taskHost.request({ sessionId: args?.sessionId, operation: "site_tool", args }, options),diff --git a/apps/desktop/electron/browser-panel.test.mjs b/apps/desktop/electron/browser-panel.test.mjsindex ad77cffd..a55049f8 100644--- a/apps/desktop/electron/browser-panel.test.mjs+++ b/apps/desktop/electron/browser-panel.test.mjs@@ -17,6 +17,8 @@ export const dialog = { async showMessageBox(_window, options) { effects.push({export const requestHooks = [];export const browserSession = new EventEmitter();browserSession.webRequest = { onBeforeRequest(_filter, listener) { requestHooks.push(listener); } };+browserSession.setPermissionRequestHandler = (handler) => { browserSession.permissionRequest = handler; };+browserSession.setPermissionCheckHandler = (handler) => { browserSession.permissionCheck = handler; };export const session = { fromPartition() {if (!controls.ready) throw new Error("Session can only be received when app is ready");return browserSession;@@ -186,8 +188,9 @@ function createPanel(checkPolicy = async (_request) => {}, remoteDebugPort = 0)handle(channel, handler) { handlers.set(channel, handler); },on(channel, handler) { handlers.set(channel, handler); },};+ const deepLinks = [];const panel = createBrowserPanel({- getWindow: () => mainWindow, remoteDebugPort, onDeepLink: () => {},+ getWindow: () => mainWindow, remoteDebugPort, onDeepLink: (urls) => deepLinks.push(...urls),checkPolicy: async (request) => { policies.push(request); await checkPolicy(request); },});panel.registerIpc(ipcMain);@@ -216,7 +219,7 @@ function createPanel(checkPolicy = async (_request) => {}, remoteDebugPort = 0)const choose = (itemId) => emit("omnirush:menu-overlay:choose", { sender: view.webContents }, { requestId: request.id, itemId });return { view, request, choose };}- return { invoke, emit, mainContents, onScreen, commands, children, messages, views, policies, openLinkMenu, panel, approve };+ return { invoke, emit, mainContents, onScreen, commands, children, messages, views, policies, openLinkMenu, panel, approve, deepLinks };}const flush = () => new Promise((resolve) => setImmediate(resolve));@@ -1350,3 +1353,93 @@ test("parent observations preserve popup approval and grants, but deliberate lifassert.deepEqual(child.destinations, ["http://localhost:4173/preview", "http://localhost:4173/next"], ending);}});++test("released builds hand out no DevTools endpoint with automation handles", async () => {+ const { invoke, views, approve } = createPanel(undefined, 0);+ invoke("omnirush:browser:show", PANEL_BOUNDS, "A");+ invoke("omnirush:browser:createTab", "https://a.example", "A");+ const opening = invoke("omnirush:browser:openUrl", "https://b.example/", "builtin", { sessionId: "B" });+ await flush();+ invoke("omnirush:browser:setVisibleSession", "B");+ approve();+ const opened = await opening;+ assert.equal(opened.browser_url, null, "no CDP port is open, so none is advertised");+ assert.equal(opened.target_id, views()[1].webContents.getOrCreateDevToolsTargetId());+ assert.equal(opened.url, "https://b.example/");+});++test("an omnirush:// navigation from a page reaches the app only after the user confirms", async () => {+ const { invoke, views, deepLinks } = createPanel();+ invoke("omnirush:browser:show", PANEL_BOUNDS, "A");+ invoke("omnirush:browser:createTab", "https://page.example/", "A");+ await flush();+ const contents = views().at(-1).webContents;+ const prompts = [];+ controls.confirm = async (options) => { prompts.push(options); return 0; };+ const declined = "omnirush://den-auth?grant=SECRET-GRANT&denBaseUrl=https%3A%2F%2Fden.attacker.example";+ contents.emit("did-start-navigation", declined, false, true);+ await flush();+ await flush();+ assert.deepEqual(deepLinks, [], "a declined link never reaches the app");+ assert.equal(prompts.length, 1);+ assert.equal(prompts[0].defaultId, 0, "Cancel is the default");+ assert.match(prompts[0].detail, /page\.example/);+ assert.match(prompts[0].detail, /Server: den\.attacker\.example/);+ assert.doesNotMatch(prompts[0].detail, /SECRET-GRANT/, "the grant is never shown");++ controls.confirm = async () => 1;+ const accepted = "omnirush://den-auth?grant=OK&denBaseUrl=https%3A%2F%2Fden.example.com";+ contents.emit("did-start-navigation", accepted, false, true);+ await flush();+ await flush();+ assert.deepEqual(deepLinks, [accepted]);+ // Let the panel's deferred about:blank reset finish before the next test.+ await new Promise((resolve) => setTimeout(resolve, 250));+});++test("the built-in browser denies camera, microphone and location and asks before other apps open", async () => {+ const { invoke } = createPanel();+ invoke("omnirush:browser:createTab", "about:blank", "A");+ await flush();+ const request = (permission, details = {}) => new Promise((resolve) => browserSession.permissionRequest(null, permission, resolve, details));+ assert.equal(await request("media", { mediaTypes: ["audio", "video"] }), false);+ assert.equal(await request("media", { mediaTypes: ["audio"] }), false);+ assert.equal(await request("geolocation"), false);+ assert.equal(await request("notifications"), false);+ assert.equal(await request("display-capture"), false);+ assert.equal(await request("fullscreen"), true);+ assert.equal(browserSession.permissionCheck(null, "media", "https://page.example"), false);+ assert.equal(browserSession.permissionCheck(null, "clipboard-sanitized-write", "https://page.example"), true);++ const prompts = [];+ controls.confirm = async (options) => { prompts.push(options); return 1; };+ assert.equal(await request("openExternal", { externalURL: "omnirush://den-auth?grant=x", requestingUrl: "https://page.example/" }), false);+ assert.equal(prompts.length, 0, "omnirush:// never goes to the OS protocol handler");+ assert.equal(await request("openExternal", { externalURL: "mailto:[email protected]", requestingUrl: "https://page.example/" }), true);+ assert.match(prompts[0].message, /"mailto:"/);+ controls.confirm = async () => 0;+ assert.equal(await request("openExternal", { externalURL: "ms-settings:privacy", requestingUrl: "https://page.example/" }), false);+});++test("the main window only shows the app document and pages the main process loads", () => {+ const { panel } = createPanel();+ const entry = "file:///opt/OmniRush/resources/app-dist/index.html";+ assert.equal(panel.isMainWindowAllowedNavigation(entry), false, "nothing is allowed before the entry is known");+ panel.setMainWindowEntryUrl(entry);+ assert.equal(panel.isMainWindowAllowedNavigation(`${entry}#/session/1`), true);+ assert.equal(panel.isMainWindowAllowedNavigation("about:blank"), true);+ for (const url of [+ "file:///home/user/Downloads/page.html",+ "file://attacker.example/share/index.html",+ "data:text/html,<script>1</script>",+ "http://127.0.0.1:8080/",+ "http://localhost:5173/",+ "https://example.com/",+ ]) assert.equal(panel.isMainWindowAllowedNavigation(url), false, url);+ const shutdown = `data:text/html;charset=utf-8,${encodeURIComponent("<p>Stopping</p>")}`;+ panel.allowMainWindowInternalUrl(shutdown);+ assert.equal(panel.isMainWindowAllowedNavigation(shutdown), true);+ panel.setMainWindowEntryUrl("http://localhost:5173/");+ assert.equal(panel.isMainWindowAllowedNavigation("http://localhost:5173/#/settings"), true);+ assert.equal(panel.isMainWindowAllowedNavigation("http://localhost:5174/"), false);+});diff --git a/apps/desktop/electron/electron-builder-config.test.mjs b/apps/desktop/electron/electron-builder-config.test.mjsindex afe06111..f23ef0a7 100644--- a/apps/desktop/electron/electron-builder-config.test.mjs+++ b/apps/desktop/electron/electron-builder-config.test.mjs@@ -32,6 +32,16 @@ describe("Electron distribution configs", () => {});});+ it("disables the Node debugging and NODE_OPTIONS fuses but keeps run-as-node", async () => {+ const config = await readConfig("electron-builder.base.yml");+ assert.deepEqual(config.electronFuses, {+ runAsNode: true,+ enableNodeOptionsEnvironmentVariable: false,+ enableNodeCliInspectArguments: false,+ onlyLoadAppFromAsar: true,+ });+ });+it("ships only architecture-specific sidecars for every desktop OS", async () => {const config = await readConfig("electron-builder.base.yml");const cases = [diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjsindex 987d7a22..53046778 100644--- a/apps/desktop/electron/main.mjs+++ b/apps/desktop/electron/main.mjs@@ -16,7 +16,7 @@ import {import { createRequire } from "node:module";import os from "node:os";import path from "node:path";-import { fileURLToPath } from "node:url";+import { fileURLToPath, pathToFileURL } from "node:url";import { globalOpencodeConfigDir, workspaceOpencodeConfigCandidates } from "@omnirush/paths";import { configureFakeMediaForTests, installMediaPermissionHandlers } from "./media-permissions.mjs";@@ -75,6 +75,7 @@ import {} from "./connect-link-branding.mjs";import { resolveConnectLinkPublicKeys } from "./connect-link-keys.mjs";import { openExternalUrl } from "./open-external.mjs";+import { classifyLocalOpen, isNetworkPath, localPathFromFileUrl } from "./open-local-path.mjs";import { resolveAppIdentifier, resolveUserDataPath } from "./dev-profile.mjs";import { fetchAgentContextDiagnosticsResponse } from "./agent-context-diagnostics-fetch.mjs";import { downloadBinaryToPath, uploadMultipartFromBytes } from "./binary-transfer.mjs";@@ -107,6 +108,7 @@ import { UPDATE_GATE_CHANNEL, createUpdateGate } from "./update-gate.mjs";import { createExternalFetch, createExternalFileUpload } from "./external-fetch.mjs";import {clearOmniRushSentrySession,+ setOmniRushSentryConsent,initOmniRushSentry,setOmniRushSentrySession,} from "./sentry.mjs";@@ -991,9 +993,13 @@ if (process.platform === "darwin" && INITIAL_APP_ICON_IMAGE && !INITIAL_APP_ICONapp.dock.setIcon(INITIAL_APP_ICON_IMAGE);}-// Expose Chrome DevTools Protocol so the opencode-chrome-devtools plugin can-// drive the built-in browser panel. Use OMNIRUSH_ELECTRON_REMOTE_DEBUG_PORT to-// pin a specific port; otherwise probe for a free one starting at 9223.+// Chrome DevTools Protocol over TCP. The agent's browser tools do not use it:+// they reach the built-in browser through the authenticated UI-control bridge+// (/browser/task), which drives each tab in-process via webContents.debugger.+// An open port lets any local process (sandboxed agent code shares the host+// network) attach without credentials and control the whole app, so packaged+// builds open none unless OMNIRUSH_ELECTRON_REMOTE_DEBUG_PORT pins one (test+// harnesses). Development builds still probe for a free port from 9223.// Must resolve before app.commandLine.appendSwitch (before `ready`).function probePort(port) {return new Promise((resolve) => {@@ -1018,13 +1024,18 @@ const explicitCdpPort = Number.parseInt();const remoteDebugPort = Number.isFinite(explicitCdpPort) && explicitCdpPort > 0? explicitCdpPort- : await findFreeCdpPort([9223, 9224, 9225, 9226, 9227]);+ : app.isPackaged ? 0 : await findFreeCdpPort([9223, 9224, 9225, 9226, 9227]);if (remoteDebugPort > 0) {+ if (app.isPackaged) {+ console.warn(`[omnirush] OMNIRUSH_ELECTRON_REMOTE_DEBUG_PORT opened an unauthenticated DevTools port on 127.0.0.1:${remoteDebugPort}; any local process can control this app until it quits.`);+ }app.commandLine.appendSwitch("remote-debugging-port", String(remoteDebugPort));app.commandLine.appendSwitch("remote-debugging-address", "127.0.0.1");+} else if (app.isPackaged) {+ // A --remote-debugging-port argument (e.g. an edited shortcut) opens no port either.+ app.commandLine.removeSwitch("remote-debugging-port");}-// Make the resolved port available to the embedded server so it flows into-// agent instructions via ensureOmniRushAgent → resolveAgentTemplate.+// Child processes and relaunches see the resolved port; 0 means none.process.env.OMNIRUSH_ELECTRON_REMOTE_DEBUG_PORT = String(remoteDebugPort);if (isDevMode && !app.isPackaged) {const cdpAddress = remoteDebugPort > 0 ? `http://127.0.0.1:${remoteDebugPort}` : "disabled";@@ -1644,7 +1655,7 @@ function showShutdownScreen() {if (!win || win.isDestroyed()) return;try {win.show();- void win.webContents.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(`<!doctype html>+ const shutdownScreenUrl = `data:text/html;charset=utf-8,${encodeURIComponent(`<!doctype html><html><head><meta charset="utf-8" />@@ -1665,7 +1676,9 @@ function showShutdownScreen() {<div class="body">Closing local workers and background services...</div></main></body>-</html>`)}`).catch(() => undefined);+</html>`)}`;+ browserPanel.allowMainWindowInternalUrl(shutdownScreenUrl);+ void win.webContents.loadURL(shutdownScreenUrl).catch(() => undefined);} catch {// Ignore renderer teardown races during quit.}@@ -2215,6 +2228,9 @@ const desktopCommandHandlers = {"desktopSentryClearSession": async (event, ...args) => {return { enabled: clearOmniRushSentrySession() };},+ "desktopSentrySetConsent": async (event, ...args) => {+ return { enabled: setOmniRushSentryConsent(args[0] === true) };+ },"desktopIntegrationStatus": async (event, ...args) => {return linuxDesktopIntegration.getStatus();},@@ -2595,11 +2611,13 @@ const desktopCommandHandlers = {"__openPath": async (event, ...args) => {const target = String(args[0] ?? "").trim();if (!target) return "Path is required.";- return shell.openPath(target);+ return openLocalPath(target);},"__revealItemInDir": async (event, ...args) => {const target = String(args[0] ?? "").trim();if (!target) return "Path is required.";+ // Even checking a UNC path makes Windows authenticate to that host.+ if (isNetworkPath(target)) return "This path cannot be opened.";if (existsSync(target)) {shell.showItemInFolder(target);return undefined;@@ -2615,7 +2633,7 @@ const desktopCommandHandlers = {},"__getFileIcon": async (event, ...args) => {const target = String(args[0] ?? "").trim();- if (!target) return null;+ if (!target || isNetworkPath(target)) return null;const requestedSize = args[1];/** @type {"small" | "normal" | "large"} */let validSize = "normal";@@ -2722,6 +2740,7 @@ const desktopCommandHandlers = {const target = String(args[0] ?? "").trim();const appPath = String(args[1] ?? "").trim();if (!target || !appPath) return "Target and app path are required.";+ if (isNetworkPath(target) || isNetworkPath(appPath)) return "This path cannot be opened.";const platform = process.platform;try {if (platform === "darwin") {@@ -2893,7 +2912,38 @@ function assertDesktopActivation() {}}+/**+ * shell.openPath with open-local-path.mjs's policy: network paths are refused+ * and programs or scripts are revealed in their folder instead of run.+ * @param {string} target+ * @param {{ workspaceRoots?: string[] | null }} [options]+ * @returns {Promise<string>} "" on success, else an error message (shell.openPath contract)+ */+async function openLocalPath(target, { workspaceRoots = null } = {}) {+ const decision = classifyLocalOpen(target, { workspaceRoots });+ if (decision === "deny") return "This path cannot be opened.";+ if (decision === "reveal") {+ if (!existsSync(target)) return `Could not find "${target}" on disk.`;+ shell.showItemInFolder(target);+ return "";+ }+ return shell.openPath(target);+}++/**+ * The desktop bridge is privileged (files, shell, terminal, tokens). Only the+ * app's own top-level document may call it, never a frame or another view.+ * @param {Electron.IpcMainInvokeEvent} event+ */+function assertMainWindowSender(event) {+ const contents = mainWindow && !mainWindow.isDestroyed() ? mainWindow.webContents : null;+ if (!contents || event.sender !== contents || event.senderFrame !== contents.mainFrame) {+ throw new Error("The OmniRush.ai desktop bridge only answers the app window.");+ }+}+async function handleDesktopInvoke(event, command, ...args) {+ assertMainWindowSender(event);if (!enterprisePreactivationCommandAllowed(command)) {assertDesktopActivation();}@@ -3023,13 +3073,19 @@ async function createMainWindow() {});mainWindow.webContents.setWindowOpenHandler(({ url }) => {- if (url.startsWith("file://")) {- try {- runDetachedTask("open local file", () => shell.openPath(fileURLToPath(url)));- } catch {- runDetachedTask("open local file externally", () => openExternalUrl(url));+ if (/^file:/i.test(url)) {+ // A link to the app's own document (a sanitized "#" href) opens nothing.+ if (browserPanel.isMainWindowAllowedNavigation(url)) return { action: "deny" };+ // Transcript links: a file URL naming a host (UNC) is never opened, and+ // only non-executable files inside a workspace open; others are revealed.+ const target = localPathFromFileUrl(url);+ if (target) {+ runDetachedTask("open local file", async () => openLocalPath(target, {+ workspaceRoots: await workspaceStore.listLocalWorkspacePaths(),+ }));+ } else {+ console.warn("[shell] refused to open a network file link");}-return { action: "deny" };}@@ -3056,24 +3112,33 @@ async function createMainWindow() {// to replace the entire workspace UI with the website, with no way back// (#2000). Catch those at `did-start-navigation`, cancel the load, and// reroute the URL into a built-in browser tab instead.- mainWindow.webContents.on("did-start-navigation", (_event, url, isInPlace, isMainFrame) => {+ mainWindow.webContents.on("did-start-navigation", (details, url, isInPlace, isMainFrame) => {if (!isMainFrame || isInPlace) return;if (browserPanel.isMainWindowAllowedNavigation(url)) return;- try {- mainWindow?.webContents.stop();- } catch {- // best effort — routing below still gives the user a way back- }+ // A page's own navigation (it has an initiator frame) reaches will-navigate+ // next, which cancels and reroutes it. Stopping inside this event aborts the+ // main process (SIGTRAP), so the browser-initiated case stops on the next turn.+ if (details?.initiator) return;+ setImmediate(() => {+ try {+ mainWindow?.webContents.stop();+ } catch {+ // best effort — routing below still gives the user a way back+ }+ });browserPanel.routeBlockedMainWindowNavigation(url);});const startUrl = process.env.OMNIRUSH_ELECTRON_START_URL?.trim() || process.env.ELECTRON_START_URL?.trim();if (startUrl) {+ browserPanel.setMainWindowEntryUrl(startUrl);await mainWindow.loadURL(startUrl);} else {const packagedIndexPath = path.join(process.resourcesPath, "app-dist", "index.html");const devIndexPath = path.resolve(__dirname, "../../app/dist/index.html");- await mainWindow.loadFile(app.isPackaged ? packagedIndexPath : devIndexPath);+ const indexPath = app.isPackaged ? packagedIndexPath : devIndexPath;+ browserPanel.setMainWindowEntryUrl(pathToFileURL(indexPath).href);+ await mainWindow.loadFile(indexPath);}return mainWindow;@@ -3086,7 +3151,8 @@ ipcMain.on("omnirush:desktop-distribution-sync", (event) => {event.returnValue = DESKTOP_DISTRIBUTION;});ipcMain.handle("omnirush:desktop", handleDesktopInvoke);-ipcMain.handle("omnirush:shell:openExternal", async (_event, url) => {+ipcMain.handle("omnirush:shell:openExternal", async (event, url) => {+ assertMainWindowSender(event);if (typeof url !== "string" || url.trim().length === 0) {return { ok: false, error: "empty url" };}diff --git a/apps/desktop/electron/media-permissions.mjs b/apps/desktop/electron/media-permissions.mjsindex 270023b5..70805445 100644--- a/apps/desktop/electron/media-permissions.mjs+++ b/apps/desktop/electron/media-permissions.mjs@@ -55,3 +55,56 @@ export function installMediaPermissionHandlers(session, getMainWindow) {})));}++// The built-in browser shows arbitrary websites. Only harmless, page-local+// capabilities are granted; camera, microphone, location, notifications,+// clipboard reads, screen capture, devices and the rest are denied.+const BROWSER_PANEL_ALLOWED_PERMISSIONS = new Set([+ "clipboard-sanitized-write",+ "fileSystem",+ "fullscreen",+ "keyboardLock",+ "mediaKeySystem",+ "pointerLock",+ "storage-access",+ "top-level-storage-access",+]);++function isDesktopSchemeUrl(url) {+ return /^omnirush(?:-dev)?:/i.test(String(url ?? "").trim());+}++/**+ * @param {string} permission+ */+export function isBrowserPanelPermissionAllowed(permission) {+ return BROWSER_PANEL_ALLOWED_PERMISSIONS.has(permission);+}++/**+ * Permission policy for the built-in browser's session (persist:omnirush-browser).+ * Handing a link to the OS ("openExternal") asks the user first, except+ * omnirush:// links, which only the browser panel's own confirmation forwards.+ *+ * @param {Electron.Session} browserSession+ * @param {{ confirmExternal: (url: string, sourceUrl: string) => Promise<boolean> }} options+ */+export function installBrowserPanelPermissionHandlers(browserSession, { confirmExternal }) {+ browserSession.setPermissionRequestHandler((webContents, permission, callback, details) => {+ if (permission !== "openExternal") {+ callback(isBrowserPanelPermissionAllowed(permission));+ return;+ }+ const request = /** @type {{ externalURL?: string, requestingUrl?: string }} */ (details ?? {});+ const externalUrl = String(request.externalURL ?? "");+ if (!externalUrl || isDesktopSchemeUrl(externalUrl)) {+ callback(false);+ return;+ }+ const sourceUrl = String(request.requestingUrl ?? webContents?.getURL?.() ?? "");+ Promise.resolve()+ .then(() => confirmExternal(externalUrl, sourceUrl))+ .then((allowed) => callback(allowed === true), () => callback(false));+ });+ browserSession.setPermissionCheckHandler((_webContents, permission) => isBrowserPanelPermissionAllowed(permission));+}diff --git a/apps/desktop/electron/media-permissions.test.mjs b/apps/desktop/electron/media-permissions.test.mjsindex a3e05d46..4fd61522 100644--- a/apps/desktop/electron/media-permissions.test.mjs+++ b/apps/desktop/electron/media-permissions.test.mjs@@ -1,7 +1,7 @@import assert from "node:assert/strict";import test from "node:test";-import { configureFakeMediaForTests } from "./media-permissions.mjs";+import { configureFakeMediaForTests, isBrowserPanelPermissionAllowed } from "./media-permissions.mjs";function fakeApp() {const switches = [];@@ -29,3 +29,12 @@ test("OMNIRUSH_VOICE_INPUT_FILE plays the WAV once through the fake microphone",["use-file-for-fake-audio-capture", "/tmp/clip.wav%noloop"],]);});++test("the built-in browser grants only page-local permissions", () => {+ for (const permission of ["media", "geolocation", "notifications", "display-capture", "clipboard-read", "midiSysex", "openExternal", "unknown"]) {+ assert.equal(isBrowserPanelPermissionAllowed(permission), false, permission);+ }+ for (const permission of ["fullscreen", "clipboard-sanitized-write", "pointerLock"]) {+ assert.equal(isBrowserPanelPermissionAllowed(permission), true, permission);+ }+});diff --git a/apps/desktop/electron/open-local-path.mjs b/apps/desktop/electron/open-local-path.mjsnew file mode 100644index 00000000..82d24826--- /dev/null+++ b/apps/desktop/electron/open-local-path.mjs@@ -0,0 +1,127 @@+// Decides how a local path from the renderer or a transcript link may be+// opened with the OS. Opening runs whatever the file's type is associated+// with, so network paths (an SMB request leaks the Windows NTLM hash) are never+// touched and programs or scripts are only revealed in their folder.++import { statSync } from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";++// Types the OS runs, installs, or hands to a script host when "opened".+const COMMON_EXECUTABLE_EXTENSIONS = [".jar", ".jnlp"];+const WINDOWS_EXECUTABLE_EXTENSIONS = [+ ".ade", ".adp", ".app", ".appinstaller", ".application", ".appref-ms", ".appx", ".appxbundle", ".bas", ".bat",+ ".chm", ".cmd", ".com", ".cpl", ".crt", ".der", ".diagcab", ".exe", ".gadget", ".hlp", ".hta", ".htc", ".inf",+ ".ins", ".isp", ".js", ".jse", ".lnk", ".mde", ".msc", ".msh", ".msh1", ".msh2", ".mshxml", ".msi", ".msix",+ ".msixbundle", ".msp", ".mst", ".msu", ".ocx", ".pif", ".pl", ".ps1", ".ps1xml", ".ps2", ".ps2xml", ".psc1",+ ".psc2", ".psd1", ".psm1", ".py", ".pyc", ".pyo", ".pyw", ".pyz", ".pyzw", ".rb", ".reg", ".scf", ".scr",+ ".sct", ".search-ms", ".searchconnector-ms", ".settingcontent-ms", ".shb", ".shs", ".sys", ".dll", ".theme",+ ".url", ".vb", ".vbe", ".vbs", ".vhd", ".vhdx", ".website", ".ws", ".wsc", ".wsf", ".wsh", ".xbap", ".xll",+ ".library-ms", ".iso", ".img",+];+const DARWIN_EXECUTABLE_EXTENSIONS = [+ ".action", ".app", ".command", ".fileloc", ".inetloc", ".mpkg", ".pkg", ".prefpane", ".terminal", ".tool",+ ".webloc", ".workflow",+];+const LINUX_EXECUTABLE_EXTENSIONS = [".appimage", ".desktop", ".run"];++/** @param {NodeJS.Platform} platform */+function executableExtensions(platform) {+ if (platform === "win32") return new Set([...COMMON_EXECUTABLE_EXTENSIONS, ...WINDOWS_EXECUTABLE_EXTENSIONS]);+ if (platform === "darwin") return new Set([...COMMON_EXECUTABLE_EXTENSIONS, ...DARWIN_EXECUTABLE_EXTENSIONS]);+ return new Set([...COMMON_EXECUTABLE_EXTENSIONS, ...LINUX_EXECUTABLE_EXTENSIONS]);+}++/**+ * `\\host\share`, `//host/share`, and the `\\?\` / `\\.\` device forms.+ * @param {string} target+ */+export function isNetworkPath(target) {+ return /^[\\/]{2}/.test(String(target ?? "").trim());+}++/**+ * @param {string} target+ * @param {{ platform?: NodeJS.Platform, stat?: (target: string) => { isFile(): boolean, mode: number } }} [options]+ */+export function isExecutablePath(target, { platform = process.platform, stat = statSync } = {}) {+ // Trailing dots and spaces are dropped by Windows (`x.exe.` runs x.exe).+ const name = platform === "win32" ? target.replace(/[. ]+$/, "") : target;+ if (executableExtensions(platform).has(path.extname(name).toLowerCase())) return true;+ if (platform === "win32") return false;+ try {+ const stats = stat(target);+ return stats.isFile() && (stats.mode & 0o111) !== 0;+ } catch {+ return false;+ }+}++/**+ * @param {string} target+ * @param {string[]} roots+ * @param {NodeJS.Platform} platform+ */+function isInsideAny(target, roots, platform) {+ const pathApi = platform === "win32" ? path.win32 : path.posix;+ const fold = (value) => (platform === "win32" || platform === "darwin" ? value.toLowerCase() : value);+ const resolved = fold(pathApi.resolve(target));+ return roots.some((root) => {+ const base = String(root ?? "").trim();+ if (!base || isNetworkPath(base)) return false;+ const relative = pathApi.relative(fold(pathApi.resolve(base)), resolved);+ return relative === "" || (!relative.startsWith("..") && !pathApi.isAbsolute(relative));+ });+}++/**+ * How to honor an "open this path" request.+ * - "deny": never touch it (network or relative paths).+ * - "reveal": show it in its folder instead of running it.+ * - "open": hand it to the OS default application.+ *+ * @param {string} target+ * @param {{+ * platform?: NodeJS.Platform,+ * stat?: (target: string) => { isFile(): boolean, mode: number },+ * workspaceRoots?: string[] | null,+ * }} [options] workspaceRoots limits "open" to files inside those folders.+ * @returns {"deny" | "reveal" | "open"}+ */+export function classifyLocalOpen(target, options = {}) {+ const platform = options.platform ?? process.platform;+ const value = String(target ?? "").trim();+ if (!value || isNetworkPath(value)) return "deny";+ const pathApi = platform === "win32" ? path.win32 : path.posix;+ if (!pathApi.isAbsolute(value)) return "deny";+ // Past the drive letter a colon names an NTFS stream (`x.txt:y.exe`, `x.exe::$DATA`).+ if (platform === "win32" && value.slice(2).includes(":")) return "deny";+ if (isExecutablePath(value, { platform, stat: options.stat })) return "reveal";+ if (options.workspaceRoots && !isInsideAny(value, options.workspaceRoots, platform)) return "reveal";+ return "open";+}++/**+ * Local path for a `file:` URL, or null for a URL that names a remote host+ * (`file://host/share` is UNC on Windows) or that does not parse.+ *+ * @param {string} url+ * @param {NodeJS.Platform} [platform]+ */+export function localPathFromFileUrl(url, platform = process.platform) {+ let parsed;+ try {+ parsed = new URL(url);+ } catch {+ return null;+ }+ if (parsed.protocol !== "file:") return null;+ if (parsed.hostname && parsed.hostname.toLowerCase() !== "localhost") return null;+ let local;+ try {+ local = fileURLToPath(parsed, { windows: platform === "win32" });+ } catch {+ return null;+ }+ return isNetworkPath(local) ? null : local;+}diff --git a/apps/desktop/electron/open-local-path.test.mjs b/apps/desktop/electron/open-local-path.test.mjsnew file mode 100644index 00000000..75742d8c--- /dev/null+++ b/apps/desktop/electron/open-local-path.test.mjs@@ -0,0 +1,54 @@+import assert from "node:assert/strict";+import test from "node:test";++import { classifyLocalOpen, isExecutablePath, isNetworkPath, localPathFromFileUrl } from "./open-local-path.mjs";++const regularFile = () => ({ isFile: () => true, mode: 0o644 });+const executableFile = () => ({ isFile: () => true, mode: 0o755 });++test("network paths are never touched", () => {+ for (const target of ["\\\\host\\share\\x.exe", "//host/share/x.exe", "\\/host/x", "\\\\?\\C:\\x.txt", "\\\\.\\pipe\\x"]) {+ assert.equal(isNetworkPath(target), true, target);+ assert.equal(classifyLocalOpen(target, { platform: "win32" }), "deny", target);+ }+ assert.equal(classifyLocalOpen("//host/share/notes.md", { platform: "linux", stat: regularFile }), "deny");+});++test("file URLs naming a host are refused, local ones map to paths", () => {+ assert.equal(localPathFromFileUrl("file://host/share/x.exe", "win32"), null);+ assert.equal(localPathFromFileUrl("file:////host/share/x.exe", "win32"), null);+ assert.equal(localPathFromFileUrl("file://attacker.example/x", "linux"), null);+ assert.equal(localPathFromFileUrl("https://example.com/x", "linux"), null);+ assert.equal(localPathFromFileUrl("file:///home/user/w/notes.md", "linux"), "/home/user/w/notes.md");+ assert.equal(localPathFromFileUrl("file://localhost/home/user/w/notes.md", "linux"), "/home/user/w/notes.md");+ assert.equal(localPathFromFileUrl("file:///C:/Users/me/w/notes.md", "win32"), "C:\\Users\\me\\w\\notes.md");+});++test("programs and scripts are revealed in their folder instead of opened on Windows", () => {+ for (const target of ["C:\\w\\setup.exe", "C:\\w\\run.BAT", "C:\\w\\tool.ps1", "C:\\w\\script.js", "C:\\w\\job.py", "C:\\w\\link.lnk", "C:\\w\\x.exe.", "C:\\w\\x.exe ", "C:\\w\\x.msi", "C:\\w\\x.hta", "C:\\w\\x.url"]) {+ assert.equal(classifyLocalOpen(target, { platform: "win32" }), "reveal", target);+ }+ assert.equal(classifyLocalOpen("C:\\w\\report.pdf", { platform: "win32" }), "open");+ assert.equal(classifyLocalOpen("C:\\w\\notes.txt:payload.exe", { platform: "win32" }), "deny", "alternate data stream");+ assert.equal(classifyLocalOpen("relative\\notes.md", { platform: "win32" }), "deny");+});++test("macOS bundles and Linux executables are revealed, documents open", () => {+ assert.equal(classifyLocalOpen("/Users/me/w/Tool.app", { platform: "darwin", stat: regularFile }), "reveal");+ assert.equal(classifyLocalOpen("/Users/me/w/run.command", { platform: "darwin", stat: regularFile }), "reveal");+ assert.equal(classifyLocalOpen("/home/me/w/build.sh", { platform: "linux", stat: executableFile }), "reveal");+ assert.equal(classifyLocalOpen("/home/me/w/app.desktop", { platform: "linux", stat: regularFile }), "reveal");+ assert.equal(classifyLocalOpen("/home/me/w/script.py", { platform: "linux", stat: regularFile }), "open", "non-executable source opens in its editor");+ assert.equal(isExecutablePath("/missing/file.txt", { platform: "linux", stat: () => { throw new Error("ENOENT"); } }), false);+});++test("transcript links open only files inside a workspace", () => {+ /** @type {{ platform: NodeJS.Platform, workspaceRoots: string[] }} */+ const options = { platform: "win32", workspaceRoots: ["C:\\Users\\me\\Project"] };+ assert.equal(classifyLocalOpen("C:\\Users\\me\\Project\\docs\\notes.md", options), "open");+ assert.equal(classifyLocalOpen("c:\\users\\ME\\project\\notes.md", options), "open", "Windows paths compare case-insensitively");+ assert.equal(classifyLocalOpen("C:\\Users\\me\\Project-other\\notes.md", options), "reveal");+ assert.equal(classifyLocalOpen("C:\\Users\\me\\Project\\..\\secrets.txt", options), "reveal");+ assert.equal(classifyLocalOpen("C:\\Windows\\win.ini", options), "reveal");+ assert.equal(classifyLocalOpen("/home/me/w/a.md", { platform: "linux", stat: regularFile, workspaceRoots: ["//host/share"] }), "reveal", "network roots never count");+});diff --git a/apps/desktop/electron/runtime.mjs b/apps/desktop/electron/runtime.mjsindex fbd13a39..e3d4f45e 100644--- a/apps/desktop/electron/runtime.mjs+++ b/apps/desktop/electron/runtime.mjs@@ -1,7 +1,7 @@import { randomUUID, X509Certificate } from "node:crypto";import { spawnSync } from "node:child_process";import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";-import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";+import { chmod, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";import net from "node:net";import os from "node:os";import path from "node:path";@@ -1510,7 +1510,9 @@ export function createRuntimeManager({async function saveTokenStore(store) {const filePath = omnirushServerTokenStorePath();await mkdir(path.dirname(filePath), { recursive: true });- await writeFile(filePath, `${JSON.stringify(store, null, 2)}\n`, "utf8");+ // Server owner/client tokens: owner-only, including files older builds wrote 0644.+ await writeFile(filePath, `${JSON.stringify(store, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });+ await chmod(filePath, 0o600);}async function loadPortState() {diff --git a/apps/desktop/electron/sentry.mjs b/apps/desktop/electron/sentry.mjsindex 68dd988d..c207a75b 100644--- a/apps/desktop/electron/sentry.mjs+++ b/apps/desktop/electron/sentry.mjs@@ -1,12 +1,113 @@import { readFileSync } from "node:fs";+import { homedir } from "node:os";import { dirname, resolve } from "node:path";import { fileURLToPath } from "node:url";let sentry = null;let initialized = false;+// Reports leave only while signed in to a Den (session) and while the user's+// "Share anonymous usage" setting is on (consent, reported by the renderer).+let sessionActive = false;+let consentGranted = false;let telemetryActive = false;const __dirname = dirname(fileURLToPath(import.meta.url));+function updateTelemetryActive() {+ telemetryActive = sessionActive && consentGranted;+}++const FILTERED = "[Filtered]";+const SENSITIVE_KEY = /authorization|cookie|token|secret|passw(or)?d|api[-_]?key|credential|grant|session[-_]?id|signature|private[-_]?key/i;+/** @type {Array<[RegExp, string]>} */+const SECRET_PATTERNS = [+ // HTTP auth schemes and header-style assignments.+ [/\b(Bearer|Basic|Token)\s+[A-Za-z0-9._~+/=-]{8,}/gi, `$1 ${FILTERED}`],+ [/\b(authorization|cookie|x-api-key|api[-_]?key)(["']?\s*[:=]\s*["']?)[^"'\s,;}]+/gi, `$1$2${FILTERED}`],+ // Credentials in URLs: userinfo and secret-bearing query parameters.+ [/(\/\/)[^/\s:@]+:[^/\s@]+@/g, `$1${FILTERED}@`],+ [/([?&#](?:access_token|token|grant|code|key|secret|password|signature|sig|auth|apikey|api_key)=)[^&#\s"']+/gi, `$1${FILTERED}`],+ // Well-known token shapes.+ [/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g, FILTERED],+ [/\b(?:sk-ant-[A-Za-z0-9_-]{8,}|sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|glpat-[A-Za-z0-9_-]{16,}|xox[abprs]-[A-Za-z0-9-]{10,}|npm_[A-Za-z0-9]{20,}|hf_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|cpa-[A-Za-z0-9_-]{16,})/g, FILTERED],+ // E-mail addresses.+ [/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, "[email]"],+];++function escapeRegExp(value) {+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}++/**+ * @param {string} home+ * @returns {Array<[RegExp, string]>}+ */+function homePathPatterns(home) {+ /** @type {Array<[RegExp, string]>} */+ const patterns = [];+ const value = String(home ?? "").replace(/[\\/]+$/, "");+ if (value.length > 1) {+ // The same home written with either separator (file URLs, JSON escapes).+ const flexible = value.split(/[\\/]+/).map(escapeRegExp).join("[\\\\/]+");+ patterns.push([new RegExp(flexible, "gi"), "~"]);+ }+ // Other users' homes and paths seen through a different mount.+ patterns.push([/(^|[\s"'(=:]|file:\/\/\/?)(?:[A-Za-z]:)?[\\/]+(?:Users|home)[\\/]+[^\\/\s"'):]+/gi, "$1~"]);+ return patterns;+}++/**+ * Removes tokens, credentials, e-mail addresses and home-directory paths+ * (which carry the OS user name) from report text.+ * @param {string} value+ * @param {string} [home]+ */+export function scrubSentryText(value, home = homedir()) {+ let text = String(value);+ for (const [pattern, replacement] of [...SECRET_PATTERNS, ...homePathPatterns(home)]) {+ text = text.replace(pattern, replacement);+ }+ return text;+}++/**+ * Deep copy of a Sentry event or breadcrumb with secrets scrubbed. Values+ * under credential-like keys are dropped entirely.+ * @template T+ * @param {T} value+ * @param {string} [home]+ * @returns {T}+ */+export function scrubSentryPayload(value, home = homedir(), depth = 0) {+ if (typeof value === "string") return /** @type {T} */ (scrubSentryText(value, home));+ if (!value || typeof value !== "object" || depth > 12) return value;+ if (Array.isArray(value)) return /** @type {T} */ (value.map((item) => scrubSentryPayload(item, home, depth + 1)));+ /** @type {Record<string, unknown>} */+ const output = {};+ for (const [key, entry] of Object.entries(value)) {+ output[key] = SENSITIVE_KEY.test(key) && entry !== null && entry !== undefined ? FILTERED : scrubSentryPayload(entry, home, depth + 1);+ }+ return /** @type {T} */ (output);+}++/**+ * @template {object} T+ * @param {T} event+ * @returns {T}+ */+export function scrubSentryEvent(event) {+ const scrubbed = scrubSentryPayload(event);+ const fields = /** @type {{ request?: Record<string, unknown>, user?: Record<string, unknown> }} */ (scrubbed);+ if (fields.request) {+ delete fields.request.cookies;+ delete fields.request.data;+ }+ if (fields.user) {+ delete fields.user.email;+ delete fields.user.ip_address;+ delete fields.user.username;+ }+ return scrubbed;+}function envFlagEnabled(name) {const value = process.env[name]?.trim().toLowerCase();return value === "1" || value === "true" || value === "yes" || value === "on";@@ -70,8 +171,9 @@ export async function initOmniRushSentry({ app, distribution, packageMetadata })(integration) => !["BrowserWindowSession", "ElectronMinidump", "MainProcessSession", "SentryMinidump"].includes(integration.name),),tracesSampler: () => telemetryActive ? sampleRate : 0,- beforeSend: (event) => telemetryActive ? event : null,- beforeSendTransaction: (event) => telemetryActive ? event : null,+ beforeSend: (event) => telemetryActive ? scrubSentryEvent(event) : null,+ beforeSendTransaction: (event) => telemetryActive ? scrubSentryEvent(event) : null,+ beforeBreadcrumb: (breadcrumb) => telemetryActive ? scrubSentryPayload(breadcrumb) : null,initialScope: {tags: {app: "desktop",@@ -103,7 +205,8 @@ export function setOmniRushSentrySession(input) {const orgId = normalizeIdentifier(input?.orgId);if (!initialized || !sentry || !userId || !orgId) return false;- telemetryActive = true;+ sessionActive = true;+ updateTelemetryActive();sentry.setUser({ id: userId });sentry.setTag("org_id", orgId);sentry.setContext("omnirush_cloud", {@@ -113,8 +216,19 @@ export function setOmniRushSentrySession(input) {return true;}+/**+ * The renderer's "Share anonymous usage" setting (analyticsEnabled).+ * @param {boolean} enabled+ */+export function setOmniRushSentryConsent(enabled) {+ consentGranted = enabled === true;+ updateTelemetryActive();+ return telemetryActive;+}+export function clearOmniRushSentrySession() {- telemetryActive = false;+ sessionActive = false;+ updateTelemetryActive();if (!initialized || !sentry) return false;sentry.setUser(null);diff --git a/apps/desktop/electron/sentry.test.mjs b/apps/desktop/electron/sentry.test.mjsindex 3cd344b7..e45c4dab 100644--- a/apps/desktop/electron/sentry.test.mjs+++ b/apps/desktop/electron/sentry.test.mjs@@ -4,6 +4,10 @@ import test from "node:test";import {resolveOmniRushSentryAppVersion,resolveOmniRushSentryRelease,+ scrubSentryEvent,+ scrubSentryPayload,+ scrubSentryText,+ setOmniRushSentryConsent,} from "./sentry.mjs";test("unpackaged Sentry release uses the desktop package version", () => {@@ -41,3 +45,37 @@ test("Sentry release still honors an explicit build override", () => {"desktop-main@abcdef",);});++test("report text loses tokens, credentials, e-mail addresses and home paths", () => {+ const scrubbed = scrubSentryText([+ "Authorization: Bearer abcdefghijklmnop",+ "fetch https://user:[email protected]/v1?grant=g-123&page=2",+ "jwt eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTYifQ.c2lnbmF0dXJlLXZhbHVl",+ "keys sk-ant-oat01-abcdefghijkl ghp_abcdefghijklmnopqrstuv npm_abcdefghijklmnopqrstuv",+ "mail [email protected]",+ "at /home/alice/project/src/index.ts and C:\\Users\\Bob\\Desktop\\x.txt and file:///Users/carol/w",+ ].join("\n"), "/home/alice");+ for (const secret of ["abcdefghijklmnop", "user:pass", "g-123", "eyJhbGci", "sk-ant-oat01", "ghp_", "npm_abcdef", "[email protected]", "alice", "Bob", "carol"]) {+ assert.ok(!scrubbed.includes(secret), `${secret} leaked: ${scrubbed}`);+ }+ assert.match(scrubbed, /page=2/, "harmless query parameters stay");+ assert.match(scrubbed, /~\/project\/src\/index\.ts/);+});++test("events drop credential fields, cookies, request bodies and user contact data", () => {+ const event = scrubSentryEvent({+ request: { url: "https://den.example.com/x?token=t", headers: { Authorization: "Bearer x", Accept: "json" }, cookies: "a=b", data: "{\"password\":\"p\"}" },+ user: { id: "user_1", email: "[email protected]", ip_address: "1.2.3.4" },+ extra: { ownerToken: "secret", nested: { apiKey: "k", note: "ok" } },+ breadcrumbs: [{ message: "GET /home/alice/x?code=abc" }],+ });+ assert.deepEqual(event.request, { url: "https://den.example.com/x?token=[Filtered]", headers: { Authorization: "[Filtered]", Accept: "json" } });+ assert.deepEqual(event.user, { id: "user_1" });+ assert.deepEqual(event.extra, { ownerToken: "[Filtered]", nested: { apiKey: "[Filtered]", note: "ok" } });+ assert.equal(scrubSentryPayload({ category: "console", message: "token at /home/alice/x" }, "/home/alice").message, "token at ~/x");+});++test("the usage-sharing setting alone never turns reporting on without a session", () => {+ assert.equal(setOmniRushSentryConsent(true), false);+ assert.equal(setOmniRushSentryConsent(false), false);+});diff --git a/apps/desktop/electron/ui-control-server.mjs b/apps/desktop/electron/ui-control-server.mjsindex a379df89..02f98604 100644--- a/apps/desktop/electron/ui-control-server.mjs+++ b/apps/desktop/electron/ui-control-server.mjs@@ -5,7 +5,7 @@// (createRuntimeManager pattern).import { randomBytes } from "node:crypto";import { createServer } from "node:http";-import { rm, writeFile } from "node:fs/promises";+import { chmod, rm, writeFile } from "node:fs/promises";import path from "node:path";export function createUiControlServer({@@ -211,8 +211,10 @@ export function createUiControlServer({await writeFile(uiControlDiscoveryPath,`${JSON.stringify({ version: 2, app: appName, identifier: appIdentifier, platform: process.platform, baseUrl: `http://127.0.0.1:${port}`, token: uiControlToken }, null, 2)}\n`,- "utf8",+ { encoding: "utf8", mode: 0o600 },);+ // The bridge token drives the app; a file left by an older build may still be 0644.+ await chmod(uiControlDiscoveryPath, 0o600);// Make the discovery path available to child processes (server → managed OpenCode → plugin).process.env.OMNIRUSH_UI_CONTROL_DISCOVERY = uiControlDiscoveryPath;}diff --git a/apps/desktop/electron/workspace-store.mjs b/apps/desktop/electron/workspace-store.mjsindex f86405b9..9b893592 100644--- a/apps/desktop/electron/workspace-store.mjs+++ b/apps/desktop/electron/workspace-store.mjs@@ -102,7 +102,9 @@ async function writeJsonFileAtomic(outputPath, value) {JSON.parse(content);await mkdir(path.dirname(outputPath), { recursive: true });const tempPath = `${outputPath}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;- await writeFile(tempPath, content, "utf8");+ // Owner-only: these hold server tokens and workspace state. The rename+ // replaces any older 0644 file with this one's mode.+ await writeFile(tempPath, content, { encoding: "utf8", mode: 0o600 });try {await renameWithRetry(tempPath, outputPath);} catch (error) {@@ -229,7 +231,7 @@ export function createWorkspaceStore({if (!existsSync(legacy)) return false;await mkdir(path.dirname(current), { recursive: true });const raw = await readFile(legacy, "utf8");- await writeFile(current, raw, "utf8");+ await writeFile(current, raw, { encoding: "utf8", mode: 0o600 });console.info("[migration] copied workspace-state.json to omnirush-workspaces.json");return true;} catch (error) {@@ -427,7 +429,7 @@ export function createWorkspaceStore({async function migrateLegacyDesktopBootstrapConfig(configPath, legacyCandidate) {try {await mkdir(path.dirname(configPath), { recursive: true });- await writeFile(configPath, legacyCandidate.raw, "utf8");+ await writeFile(configPath, legacyCandidate.raw, { encoding: "utf8", mode: 0o600 });console.info("[desktop-bootstrap] migrated legacy config", {from: legacyCandidate.path,to: configPath,diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex e9c3ecbc..17fb498d 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -27,8 +27,8 @@"prepare:sidecar": "node ./scripts/prepare-sidecar.mjs","pretest": "pnpm --filter @omnirush/headless-threads build","test:omnirush-account": "node --test electron/omnirush-account.test.mjs",- "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/quality.test.mjs electron/buildathon.test.mjs electron/turn-guard.test.mjs electron/keep-awake.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs electron/start-report.test.mjs electron/start-reset.test.mjs electron/start-store-check.test.mjs",- "test:core": "node --test scripts/prepare-server-constants.test.mjs electron/workspace-store.test.mjs electron/workspace-archive.test.mjs electron/connect-link.test.mjs electron/open-external.test.mjs electron/secure-vault-key.test.mjs electron/process-resilience.test.mjs electron/stdio-errors.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/automation-runner.test.mjs",+ "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/open-local-path.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/quality.test.mjs electron/buildathon.test.mjs electron/turn-guard.test.mjs electron/keep-awake.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs electron/start-report.test.mjs electron/start-reset.test.mjs electron/start-store-check.test.mjs",+ "test:core": "node --test scripts/prepare-server-constants.test.mjs electron/workspace-store.test.mjs electron/workspace-archive.test.mjs electron/connect-link.test.mjs electron/open-external.test.mjs electron/open-local-path.test.mjs electron/secure-vault-key.test.mjs electron/process-resilience.test.mjs electron/stdio-errors.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/automation-runner.test.mjs","pretest:core": "pnpm --filter @omnirush/headless-threads build"},"dependencies": {diff --git a/packages/browser-tabs/index.d.ts b/packages/browser-tabs/index.d.tsindex b1f8ac8f..f769ad43 100644--- a/packages/browser-tabs/index.d.ts+++ b/packages/browser-tabs/index.d.ts@@ -71,7 +71,8 @@ export type BrowserPanelOwnerPayload = {export type OpenBrowserUrlResult = {provider: "builtin";- browser_url: string;+ /** DevTools endpoint; null in packaged builds, which open no DevTools port. */+ browser_url: string | null;target_id: string;tab_id: string;url: string;diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.tsindex 0d22792b..5dd1ed88 100644--- a/packages/types/src/desktop-ipc.ts+++ b/packages/types/src/desktop-ipc.ts@@ -877,6 +877,8 @@ export type DesktopCommandMap = {result: { enabled: boolean };};desktopSentryClearSession: { args: []; result: { enabled: boolean } };+ /** The "Share anonymous usage" setting; desktop error reports follow it. */+ desktopSentrySetConsent: { args: [enabled: boolean]; result: { enabled: boolean } };desktopIntegrationStatus: { args: []; result: DesktopIntegrationStatus };desktopIntegrationInstall: {args: [options?: { useExternalLauncher?: boolean }];