Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
fix(desktop): offer the system browser when a previewed site refuses framing
jeffrey16ee26a67bfa
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.mdindex b0d73da2..c44add0a 100644--- a/apps/desktop/AGENTS.md+++ b/apps/desktop/AGENTS.md@@ -45,6 +45,13 @@ Gateway and runs Agents. The daemon exits with the app.The callback restores the originating window and forwards the return to itssigned-in SPA, which requests TeamHub verification.+- The Web link preview panel frames other sites. The window drops their+ framing refusals (`X-Frame-Options`, CSP `frame-ancestors`) for frames of+ the app, except the panel's frame, named `linger-url-preview:<id>`. When+ that frame's final response refuses framing, the window sends+ `preview.frame-refused`, and the panel offers the system browser instead,+ where the user's sign-ins work.+- `src/main/modules.ts`: `Module` interface, typed bus and the host that startsmodules in dependency layers and stops them in reverse.- `src/main/*.ts`: one file per module (Enrollment, WorkspaceGrants,diff --git a/apps/desktop/src/main/navigation.test.ts b/apps/desktop/src/main/navigation.test.tsindex 02f1277c..c3818638 100644--- a/apps/desktop/src/main/navigation.test.ts+++ b/apps/desktop/src/main/navigation.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";import {framableHeaders,+ refusesFraming,navigationDecision,parseServerUrl,permissionAllowed,@@ -136,6 +137,41 @@ describe("framableHeaders", () => {});});+describe("refusesFraming", () => {+ it("reads X-Frame-Options and lets CSP frame-ancestors override it", () => {+ expect(refusesFraming({ "X-Frame-Options": ["SAMEORIGIN"] })).toBe(true);+ expect(refusesFraming({ "x-frame-options": ["deny"] })).toBe(true);+ expect(refusesFraming({ "X-Frame-Options": ["ALLOWALL"] })).toBe(false);+ expect(+ refusesFraming({+ "Content-Security-Policy": [+ "default-src 'self'; frame-ancestors 'self'",+ ],+ }),+ ).toBe(true);+ expect(+ refusesFraming({+ "X-Frame-Options": ["DENY"],+ "Content-Security-Policy": ["frame-ancestors *"],+ }),+ ).toBe(false);+ expect(+ refusesFraming({+ "Content-Security-Policy": [+ "frame-ancestors *",+ "frame-ancestors 'none'",+ ],+ }),+ ).toBe(true);+ expect(+ refusesFraming({+ "Content-Security-Policy": ["default-src 'self'"],+ "Content-Type": ["text/html"],+ }),+ ).toBe(false);+ });+});+describe("windowLoadDecision", () => {const local = "http://localhost:3000";const moved = "http://localhost:3001";diff --git a/apps/desktop/src/main/navigation.ts b/apps/desktop/src/main/navigation.tsindex 49fc9a1a..73eb147c 100644--- a/apps/desktop/src/main/navigation.ts+++ b/apps/desktop/src/main/navigation.ts@@ -184,9 +184,49 @@ export const parseServerUrl = (value: string): string | undefined => {}};-// A page opened in the app's preview panel is framed by the app. Many sites-// refuse every frame (X-Frame-Options, CSP frame-ancestors) and the panel-// stays blank, so the window drops those two rules for its own frames. The+// The Web link preview panel names its frame with this prefix. For such a+// frame the window keeps the site's framing rules and, when they refuse the+// frame, tells the page so it can offer the system browser instead; a site+// that refuses frames usually needs a sign-in the frame does not have.+// Frames without the name, from Web builds before it, keep framableHeaders.+export const PREVIEW_FRAME_PREFIX = "linger-url-preview:";++const frameAncestorSources = (policy: string): string[] | undefined => {+ for (const directive of policy.split(";")) {+ const [name, ...sources] = directive.trim().split(/\s+/);+ if (name?.toLowerCase() === "frame-ancestors") return sources;+ }+ return undefined;+};++// Whether a response refuses to be framed by a page of another origin. CSP+// frame-ancestors, when present, overrides X-Frame-Options, as in Chromium.+// A source list other than * is taken as a refusal: a site never lists the+// Linger server among its ancestors.+export const refusesFraming = (headers: Record<string, string[]>): boolean => {+ const values = (wanted: string): string[] =>+ Object.entries(headers).flatMap(([name, value]) =>+ name.toLowerCase() === wanted ? value : [],+ );+ const ancestors = values("content-security-policy").flatMap((policy) => {+ const sources = frameAncestorSources(policy);+ return sources ? [sources] : [];+ });+ if (ancestors.length)+ return ancestors.some((sources) => !sources.includes("*"));+ return values("x-frame-options").some((value) =>+ value+ .split(",")+ .some((option) =>+ ["deny", "sameorigin"].includes(option.trim().toLowerCase()),+ ),+ );+};++// Frames of the app without the PREVIEW_FRAME_PREFIX name, such as a preview+// panel from an older Web build or a frame nested in a previewed page, would+// stay blank where a site refuses every frame (X-Frame-Options, CSP+// frame-ancestors), so the window drops those two rules for them. The// panel's frame is sandboxed and cannot navigate or script the app.export const framableHeaders = (headers: Record<string, string[]>,diff --git a/apps/desktop/src/main/window-manager.ts b/apps/desktop/src/main/window-manager.tsindex 2091aa6e..e22fddb4 100644--- a/apps/desktop/src/main/window-manager.ts+++ b/apps/desktop/src/main/window-manager.ts@@ -21,12 +21,14 @@ import {type ShellPlatform,type TitlebarState,} from "../shared/shell.js";+import { IPC } from "../shared/api.js";import type { DiagnosticsModule } from "./diagnostics.js";import { diagnosticsDialogs } from "./diagnostics-dialogs.js";import { sendWithPrompts } from "./diagnostics-upload.js";import type { Module, ModuleContext } from "./modules.js";import {OFFLINE_ORIGIN,+ PREVIEW_FRAME_PREFIX,SHELL_ORIGIN,type WindowLoadReason,type WindowLoadState,@@ -34,6 +36,7 @@ import {navigationDecision,parseServerUrl,permissionAllowed,+ refusesFraming,sameOrigin,serverSwitch,windowLoadDecision,@@ -731,17 +734,28 @@ export class WindowManagerModule implements Module {target.webRequest.onHeadersReceived((details, done) => {const contents = this.#content?.webContents;const server = this.#serverUrl();- done(- details.resourceType === "subFrame" &&- details.responseHeaders &&- contents &&- !contents.isDestroyed() &&- details.webContentsId === contents.id &&- server &&- sameOrigin(contents.getURL(), server)- ? { responseHeaders: framableHeaders(details.responseHeaders) }- : {},- );+ if (+ details.resourceType !== "subFrame" ||+ !details.responseHeaders ||+ !contents ||+ contents.isDestroyed() ||+ details.webContentsId !== contents.id ||+ !server ||+ !sameOrigin(contents.getURL(), server)+ ) {+ done({});+ return;+ }+ const name = details.frame?.name ?? "";+ if (!name.startsWith(PREVIEW_FRAME_PREFIX)) {+ done({ responseHeaders: framableHeaders(details.responseHeaders) });+ return;+ }+ // Chromium applies framing rules to the final response only.+ const redirect = details.statusCode >= 300 && details.statusCode < 400;+ if (!redirect && refusesFraming(details.responseHeaders))+ contents.send(IPC.previewFrameRefused, name, details.url);+ done({});});}diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsindex da600f3c..5ffe4dda 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -61,6 +61,14 @@ const api: LingerDesktopApi = {return () => ipcRenderer.off(IPC.connectorOAuthReturn, listener);},},+ preview: {+ onFrameRefused: (callback) => {+ const listener = (_event: unknown, name: string, url: string): void =>+ callback(name, url);+ ipcRenderer.on(IPC.previewFrameRefused, listener);+ return () => ipcRenderer.off(IPC.previewFrameRefused, listener);+ },+ },...(process.platform === "darwin"? {permissions: {diff --git a/apps/desktop/src/shared/api.ts b/apps/desktop/src/shared/api.tsindex f319d28e..934d640e 100644--- a/apps/desktop/src/shared/api.ts+++ b/apps/desktop/src/shared/api.ts@@ -106,6 +106,13 @@ export interface LingerDesktopApi {prepare(): Promise<string>;onReturn(callback: (connectedAccountId?: string) => void): () => void;};+ // The link preview panel's frame, named PREVIEW_FRAME_PREFIX + an id,+ // refused to be framed; url is the page that refused.+ readonly preview: {+ onFrameRefused(+ callback: (frameName: string, url: string) => void,+ ): () => void;+ };// macOS only.readonly permissions?: {act(step: DesktopPermissionStep): Promise<void>;@@ -131,4 +138,5 @@ export const IPC = {updateCheck: "update.check",connectorOAuthPrepare: "connector-oauth.prepare",connectorOAuthReturn: "connector-oauth.return",+ previewFrameRefused: "preview.frame-refused",} as const;diff --git a/apps/web/src/features/rooms/task-sidebar/url-preview-panel.test.tsx b/apps/web/src/features/rooms/task-sidebar/url-preview-panel.test.tsxindex 6a7939f0..508157e9 100644--- a/apps/web/src/features/rooms/task-sidebar/url-preview-panel.test.tsx+++ b/apps/web/src/features/rooms/task-sidebar/url-preview-panel.test.tsx@@ -1,4 +1,4 @@-import { fireEvent, render, screen } from "@testing-library/react";+import { act, fireEvent, render, screen } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";import { UrlPreviewPanel } from "./url-preview-panel";@@ -99,3 +99,38 @@ describe("URL preview fallback", () => {}});});++describe("URL preview in the desktop app", () => {+ afterEach(() => {+ delete (window as { lingerDesktop?: unknown }).lingerDesktop;+ });++ it("replaces a frame the site refused with a link to open it in a new tab", () => {+ let report: ((frameName: string, url: string) => void) | undefined;+ (window as { lingerDesktop?: unknown }).lingerDesktop = {+ preview: {+ onFrameRefused: (+ callback: (frameName: string, url: string) => void,+ ) => {+ report = callback;+ return () => (report = undefined);+ },+ },+ };+ render(<UrlPreviewPanel url="https://linear.app/team/issue/A-1" />);+ const frame = document.querySelector("iframe")!;+ expect(frame.name).toMatch(/^linger-url-preview:/);++ act(() => report!("linger-url-preview:another", "https://linear.app/"));+ expect(document.querySelector("iframe")).not.toBeNull();++ act(() => report!(frame.name, "https://linear.app/login"));+ expect(document.querySelector("iframe")).toBeNull();+ expect(screen.getByText("Open this site in a new tab")).toBeInTheDocument();+ expect(+ screen.getByText("linear.app does not allow being shown in the app."),+ ).toBeInTheDocument();+ const links = screen.getAllByRole("link", { name: "Open in new tab" });+ expect(links.at(-1)).toHaveAttribute("href", "https://linear.app/login");+ });+});diff --git a/apps/web/src/features/rooms/task-sidebar/url-preview-panel.tsx b/apps/web/src/features/rooms/task-sidebar/url-preview-panel.tsxindex 128df3f5..10303fa2 100644--- a/apps/web/src/features/rooms/task-sidebar/url-preview-panel.tsx+++ b/apps/web/src/features/rooms/task-sidebar/url-preview-panel.tsx@@ -4,7 +4,7 @@ import {ArrowUpRight01Icon,RotateClockwiseIcon,} from "@hugeicons/core-free-icons";-import { useEffect, useRef, useState } from "react";+import { useEffect, useId, useRef, useState } from "react";import { isDesktopShell } from "@/app/desktop-shell";import { Icon } from "@/components/ui/icon";@@ -13,10 +13,30 @@ import { shouldOpenUrlExternally } from "../url-preview-policy";const previewSandbox = "allow-forms allow-scripts";+// The desktop app keeps the framing rules of a frame named with this prefix+// and reports a refusal through `window.lingerDesktop.preview`. It must match+// the desktop's PREVIEW_FRAME_PREFIX.+const PREVIEW_FRAME_PREFIX = "linger-url-preview:";++interface DesktopPreview {+ onFrameRefused(+ callback: (frameName: string, url: string) => void,+ ): () => void;+}++function desktopPreview() {+ return (window as { lingerDesktop?: { preview?: DesktopPreview } })+ .lingerDesktop?.preview;+}++interface RefusedFrame {+ frameKey: string;+ url: string;+}+// The development server proxies previews, so its frames share the app's-// origin and get no storage. The desktop app lets sites be framed directly-// (its window drops their frame refusals), even when it runs a development-// server on this computer.+// origin and get no storage. The desktop app frames sites directly, even when+// it runs a development server on this computer.function previewProxied() {return import.meta.env.DEV && !isDesktopShell();}@@ -83,11 +103,23 @@ function UrlPreviewSession({const [error, setError] = useState<string | null>(null);const [reloadKey, setReloadKey] = useState(0);const frameRef = useRef<HTMLIFrameElement>(null);+ const frameName = PREVIEW_FRAME_PREFIX + useId();+ const [refusedFrame, setRefusedFrame] = useState<RefusedFrame | null>(null);const currentUrl = history[index];+ const frameKey = `${currentUrl}:${reloadKey}`;+ const refused = refusedFrame?.frameKey === frameKey ? refusedFrame : null;const externalOnly = currentUrl? shouldOpenUrlExternally(new URL(currentUrl)): false;+ useEffect(+ () =>+ desktopPreview()?.onFrameRefused((name, url) => {+ if (name === frameName) setRefusedFrame({ frameKey, url });+ }),+ [frameKey, frameName],+ );+useEffect(() => {function onMessage(event: MessageEvent) {if (event.source !== frameRef.current?.contentWindow) return;@@ -209,10 +241,29 @@ function UrlPreviewSession({<p className="p-4 text-sm text-muted-foreground">Open this address in a browser tab to view it.</p>+ ) : refused ? (+ <div className="flex flex-col items-start gap-2 p-4 text-sm">+ <p className="font-medium text-foreground">+ Open this site in a new tab+ </p>+ <p className="text-muted-foreground">+ {new URL(refused.url).host} does not allow being shown in the app.+ </p>+ <a+ className="inline-flex items-center gap-1 rounded-lg border border-border px-3 py-1.5 text-xs font-medium text-foreground transition-colors hover:bg-accent"+ href={refused.url}+ rel="noopener noreferrer"+ target="_blank"+ >+ Open in new tab+ <Icon icon={ArrowUpRight01Icon} size={14} />+ </a>+ </div>) : (<iframeclassName="h-full w-full border-0 bg-white"- key={`${currentUrl}:${reloadKey}`}+ key={frameKey}+ name={frameName}ref={frameRef}sandbox={previewProxied()